Rollup merge of #54963 - ljedrz:cleanup_rustc_session, r=varkor

Cleanup rustc/session

- improve allocations
- improve common patterns
- use `to_owned` when no string conversion is needed
- move `const`s up to improve readability
- whitespace & formatting improvements
This commit is contained in:
Manish Goregaokar 2018-10-15 10:15:12 -07:00 committed by GitHub
commit 3ffb16f6c6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 132 additions and 160 deletions

View file

@ -490,10 +490,10 @@ pub enum Input {
}
impl Input {
pub fn filestem(&self) -> String {
pub fn filestem(&self) -> &str {
match *self {
Input::File(ref ifile) => ifile.file_stem().unwrap().to_str().unwrap().to_string(),
Input::Str { .. } => "rust_out".to_string(),
Input::File(ref ifile) => ifile.file_stem().unwrap().to_str().unwrap(),
Input::Str { .. } => "rust_out",
}
}
@ -736,19 +736,19 @@ macro_rules! options {
match (value, opt_type_desc) {
(Some(..), None) => {
early_error(error_format, &format!("{} option `{}` takes no \
value", $outputname, key))
value", $outputname, key))
}
(None, Some(type_desc)) => {
early_error(error_format, &format!("{0} option `{1}` requires \
{2} ({3} {1}=<value>)",
$outputname, key,
type_desc, $prefix))
{2} ({3} {1}=<value>)",
$outputname, key,
type_desc, $prefix))
}
(Some(value), Some(type_desc)) => {
early_error(error_format, &format!("incorrect value `{}` for {} \
option `{}` - {} was expected",
value, $outputname,
key, type_desc))
option `{}` - {} was expected",
value, $outputname,
key, type_desc))
}
(None, None) => bug!()
}
@ -758,14 +758,13 @@ macro_rules! options {
}
if !found {
early_error(error_format, &format!("unknown {} option: `{}`",
$outputname, key));
$outputname, key));
}
}
return op;
}
impl<'a> dep_tracking::DepTrackingHash for $struct_name {
fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
let mut sub_hashes = BTreeMap::new();
$({
@ -782,7 +781,7 @@ macro_rules! options {
pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
pub const $stat: &'static [(&'static str, $setter_name,
Option<&'static str>, &'static str)] =
Option<&'static str>, &'static str)] =
&[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
#[allow(non_upper_case_globals, dead_code)]
@ -1062,8 +1061,8 @@ macro_rules! options {
) }
options! {CodegenOptions, CodegenSetter, basic_codegen_options,
build_codegen_options, "C", "codegen",
CG_OPTIONS, cg_type_desc, cgsetters,
build_codegen_options, "C", "codegen",
CG_OPTIONS, cg_type_desc, cgsetters,
ar: Option<String> = (None, parse_opt_string, [UNTRACKED],
"this option is deprecated and does nothing"),
linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
@ -1107,13 +1106,13 @@ options! {CodegenOptions, CodegenSetter, basic_codegen_options,
no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
"disable the use of the redzone"),
relocation_model: Option<String> = (None, parse_opt_string, [TRACKED],
"choose the relocation model to use (rustc --print relocation-models for details)"),
"choose the relocation model to use (rustc --print relocation-models for details)"),
code_model: Option<String> = (None, parse_opt_string, [TRACKED],
"choose the code model to use (rustc --print code-models for details)"),
"choose the code model to use (rustc --print code-models for details)"),
metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
"metadata to mangle symbol names with"),
"metadata to mangle symbol names with"),
extra_filename: String = (String::new(), parse_string, [UNTRACKED],
"extra data to put in each output filename"),
"extra data to put in each output filename"),
codegen_units: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
"divide crate into N units to optimize in parallel"),
remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED],
@ -1134,14 +1133,14 @@ options! {CodegenOptions, CodegenSetter, basic_codegen_options,
panic: Option<PanicStrategy> = (None, parse_panic_strategy,
[TRACKED], "panic strategy to compile crate with"),
incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
"enable incremental compilation"),
"enable incremental compilation"),
default_linker_libraries: Option<bool> = (None, parse_opt_bool, [UNTRACKED],
"allow the linker to link its default libraries"),
"allow the linker to link its default libraries"),
}
options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
build_debugging_options, "Z", "debugging",
DB_OPTIONS, db_type_desc, dbsetters,
build_debugging_options, "Z", "debugging",
DB_OPTIONS, db_type_desc, dbsetters,
codegen_backend: Option<String> = (None, parse_opt_string, [TRACKED],
"the backend to use"),
verbose: bool = (false, parse_bool, [UNTRACKED],
@ -1211,26 +1210,26 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
flowgraph_print_all: bool = (false, parse_bool, [UNTRACKED],
"include all dataflow analysis data in -Z unpretty flowgraph output"),
print_region_graph: bool = (false, parse_bool, [UNTRACKED],
"prints region inference graph. \
Use with RUST_REGION_GRAPH=help for more info"),
"prints region inference graph. \
Use with RUST_REGION_GRAPH=help for more info"),
parse_only: bool = (false, parse_bool, [UNTRACKED],
"parse only; do not compile, assemble, or link"),
"parse only; do not compile, assemble, or link"),
no_codegen: bool = (false, parse_bool, [TRACKED],
"run all passes except codegen; no output"),
"run all passes except codegen; no output"),
treat_err_as_bug: bool = (false, parse_bool, [TRACKED],
"treat all errors that occur as bugs"),
"treat all errors that occur as bugs"),
report_delayed_bugs: bool = (false, parse_bool, [TRACKED],
"immediately print bugs registered with `delay_span_bug`"),
"immediately print bugs registered with `delay_span_bug`"),
external_macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
"show macro backtraces even for non-local macros"),
"show macro backtraces even for non-local macros"),
teach: bool = (false, parse_bool, [TRACKED],
"show extended diagnostic help"),
"show extended diagnostic help"),
continue_parse_after_error: bool = (false, parse_bool, [TRACKED],
"attempt to recover from parse errors (experimental)"),
"attempt to recover from parse errors (experimental)"),
incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
"enable incremental compilation (experimental)"),
"enable incremental compilation (experimental)"),
incremental_queries: bool = (true, parse_bool, [UNTRACKED],
"enable incremental compilation support for queries (experimental)"),
"enable incremental compilation support for queries (experimental)"),
incremental_info: bool = (false, parse_bool, [UNTRACKED],
"print high-level information about incremental reuse (or the lack thereof)"),
incremental_dump_hash: bool = (false, parse_bool, [UNTRACKED],
@ -1240,64 +1239,64 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
incremental_ignore_spans: bool = (false, parse_bool, [UNTRACKED],
"ignore spans during ICH computation -- used for testing"),
dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
"dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
"dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
"enable queries of the dependency graph for regression testing"),
"enable queries of the dependency graph for regression testing"),
profile_queries: bool = (false, parse_bool, [UNTRACKED],
"trace and profile the queries of the incremental compilation framework"),
"trace and profile the queries of the incremental compilation framework"),
profile_queries_and_keys: bool = (false, parse_bool, [UNTRACKED],
"trace and profile the queries and keys of the incremental compilation framework"),
"trace and profile the queries and keys of the incremental compilation framework"),
no_analysis: bool = (false, parse_bool, [UNTRACKED],
"parse and expand the source, but run no analysis"),
"parse and expand the source, but run no analysis"),
extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
"load extra plugins"),
unstable_options: bool = (false, parse_bool, [UNTRACKED],
"adds unstable command line options to rustc interface"),
"adds unstable command line options to rustc interface"),
force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
"force overflow checks on or off"),
"force overflow checks on or off"),
trace_macros: bool = (false, parse_bool, [UNTRACKED],
"for every macro invocation, print its name and arguments"),
"for every macro invocation, print its name and arguments"),
debug_macros: bool = (false, parse_bool, [TRACKED],
"emit line numbers debug info inside macros"),
"emit line numbers debug info inside macros"),
keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
"don't clear the hygiene data after analysis"),
"don't clear the hygiene data after analysis"),
keep_ast: bool = (false, parse_bool, [UNTRACKED],
"keep the AST after lowering it to HIR"),
"keep the AST after lowering it to HIR"),
show_span: Option<String> = (None, parse_opt_string, [TRACKED],
"show spans for compiler debugging (expr|pat|ty)"),
"show spans for compiler debugging (expr|pat|ty)"),
print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
"print layout information for each type encountered"),
"print layout information for each type encountered"),
print_mono_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
"print the result of the monomorphization collection pass"),
"print the result of the monomorphization collection pass"),
mir_opt_level: usize = (1, parse_uint, [TRACKED],
"set the MIR optimization level (0-3, default: 1)"),
"set the MIR optimization level (0-3, default: 1)"),
mutable_noalias: Option<bool> = (None, parse_opt_bool, [TRACKED],
"emit noalias metadata for mutable references (default: yes on LLVM >= 6)"),
"emit noalias metadata for mutable references (default: yes on LLVM >= 6)"),
arg_align_attributes: bool = (false, parse_bool, [TRACKED],
"emit align metadata for reference arguments"),
"emit align metadata for reference arguments"),
dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
"dump MIR state at various points in transforms"),
"dump MIR state at various points in transforms"),
dump_mir_dir: String = (String::from("mir_dump"), parse_string, [UNTRACKED],
"the directory the MIR is dumped into"),
"the directory the MIR is dumped into"),
dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED],
"in addition to `.mir` files, create graphviz `.dot` files"),
"in addition to `.mir` files, create graphviz `.dot` files"),
dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
"if set, exclude the pass number when dumping MIR (used in tests)"),
"if set, exclude the pass number when dumping MIR (used in tests)"),
mir_emit_validate: usize = (0, parse_uint, [TRACKED],
"emit Validate MIR statements, interpreted e.g. by miri (0: do not emit; 1: if function \
contains unsafe block, only validate arguments; 2: always emit full validation)"),
"emit Validate MIR statements, interpreted e.g. by miri (0: do not emit; 1: if function \
contains unsafe block, only validate arguments; 2: always emit full validation)"),
perf_stats: bool = (false, parse_bool, [UNTRACKED],
"print some performance-related statistics"),
"print some performance-related statistics"),
hir_stats: bool = (false, parse_bool, [UNTRACKED],
"print some statistics about AST and HIR"),
"print some statistics about AST and HIR"),
mir_stats: bool = (false, parse_bool, [UNTRACKED],
"print some statistics about MIR"),
"print some statistics about MIR"),
always_encode_mir: bool = (false, parse_bool, [TRACKED],
"encode MIR of all functions into the crate metadata"),
"encode MIR of all functions into the crate metadata"),
osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
"pass `-install_name @rpath/...` to the macOS linker"),
"pass `-install_name @rpath/...` to the macOS linker"),
sanitizer: Option<Sanitizer> = (None, parse_sanitizer, [TRACKED],
"Use a sanitizer"),
"Use a sanitizer"),
linker_flavor: Option<LinkerFlavor> = (None, parse_linker_flavor, [UNTRACKED],
"Linker flavor"),
fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
@ -1313,13 +1312,11 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
profile: bool = (false, parse_bool, [TRACKED],
"insert profiling code"),
pgo_gen: Option<String> = (None, parse_opt_string, [TRACKED],
"Generate PGO profile data, to a given file, or to the default \
location if it's empty."),
"Generate PGO profile data, to a given file, or to the default location if it's empty."),
pgo_use: String = (String::new(), parse_string, [TRACKED],
"Use PGO profile data from the given profile file."),
disable_instrumentation_preinliner: bool =
(false, parse_bool, [TRACKED], "Disable the instrumentation pre-inliner, \
useful for profiling / PGO."),
disable_instrumentation_preinliner: bool = (false, parse_bool, [TRACKED],
"Disable the instrumentation pre-inliner, useful for profiling / PGO."),
relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
"choose which RELRO level to use"),
nll_subminimal_causes: bool = (false, parse_bool, [UNTRACKED],
@ -1341,7 +1338,7 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
inline_in_all_cgus: Option<bool> = (None, parse_opt_bool, [TRACKED],
"control whether #[inline] functions are in all cgus"),
tls_model: Option<String> = (None, parse_opt_string, [TRACKED],
"choose the TLS model to use (rustc --print tls-models for details)"),
"choose the TLS model to use (rustc --print tls-models for details)"),
saturating_float_casts: bool = (false, parse_bool, [TRACKED],
"make float->int casts UB-free: numbers outside the integer type's range are clipped to \
the max/min integer respectively, and NaN is mapped to 0"),
@ -1362,31 +1359,31 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
`hir` (the HIR), `hir,identified`, or
`hir,typed` (HIR with types for each node)."),
run_dsymutil: Option<bool> = (None, parse_opt_bool, [TRACKED],
"run `dsymutil` and delete intermediate object files"),
"run `dsymutil` and delete intermediate object files"),
ui_testing: bool = (false, parse_bool, [UNTRACKED],
"format compiler diagnostics in a way that's better suitable for UI testing"),
"format compiler diagnostics in a way that's better suitable for UI testing"),
embed_bitcode: bool = (false, parse_bool, [TRACKED],
"embed LLVM bitcode in object files"),
"embed LLVM bitcode in object files"),
strip_debuginfo_if_disabled: Option<bool> = (None, parse_opt_bool, [TRACKED],
"tell the linker to strip debuginfo when building without debuginfo enabled."),
share_generics: Option<bool> = (None, parse_opt_bool, [TRACKED],
"make the current crate share its generic instantiations"),
"make the current crate share its generic instantiations"),
chalk: bool = (false, parse_bool, [TRACKED],
"enable the experimental Chalk-based trait solving engine"),
"enable the experimental Chalk-based trait solving engine"),
cross_lang_lto: CrossLangLto = (CrossLangLto::Disabled, parse_cross_lang_lto, [TRACKED],
"generate build artifacts that are compatible with linker-based LTO."),
"generate build artifacts that are compatible with linker-based LTO."),
no_parallel_llvm: bool = (false, parse_bool, [UNTRACKED],
"don't run LLVM in parallel (while keeping codegen-units and ThinLTO)"),
"don't run LLVM in parallel (while keeping codegen-units and ThinLTO)"),
no_leak_check: bool = (false, parse_bool, [UNTRACKED],
"disables the 'leak check' for subtyping; unsound, but useful for tests"),
crate_attr: Vec<String> = (Vec::new(), parse_string_push, [TRACKED],
"inject the given attribute in the crate"),
self_profile: bool = (false, parse_bool, [UNTRACKED],
"run the self profiler"),
"run the self profiler"),
profile_json: bool = (false, parse_bool, [UNTRACKED],
"output a json file with profiler results"),
"output a json file with profiler results"),
emit_stack_sizes: bool = (false, parse_bool, [UNTRACKED],
"emits a section containing stack size metadata"),
"emits a section containing stack size metadata"),
plt: Option<bool> = (None, parse_opt_bool, [TRACKED],
"whether to use the PLT when calling into shared libraries;
only has effect for PIC code on systems with ELF binaries
@ -1409,6 +1406,7 @@ pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
let atomic_cas = sess.target.target.options.atomic_cas;
let mut ret = FxHashSet::default();
ret.reserve(6); // the minimum number of insertions
// Target bindings.
ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os))));
if let Some(ref fam) = sess.target.target.options.target_family {
@ -1455,7 +1453,7 @@ pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
if sess.opts.crate_types.contains(&CrateType::ProcMacro) {
ret.insert((Symbol::intern("proc_macro"), None));
}
return ret;
ret
}
pub fn build_configuration(sess: &Session, mut user_cfg: ast::CrateConfig) -> ast::CrateConfig {
@ -1471,15 +1469,12 @@ pub fn build_configuration(sess: &Session, mut user_cfg: ast::CrateConfig) -> as
}
pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
let target = match Target::search(&opts.target_triple) {
Ok(t) => t,
Err(e) => {
sp.struct_fatal(&format!("Error loading target specification: {}", e))
.help("Use `--print target-list` for a list of built-in targets")
.emit();
FatalError.raise();
}
};
let target = Target::search(&opts.target_triple).unwrap_or_else(|e| {
sp.struct_fatal(&format!("Error loading target specification: {}", e))
.help("Use `--print target-list` for a list of built-in targets")
.emit();
FatalError.raise();
});
let (isize_ty, usize_ty) = match &target.target_pointer_width[..] {
"16" => (ast::IntTy::I16, ast::UintTy::U16),
@ -1502,7 +1497,6 @@ pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum OptionStability {
Stable,
Unstable,
}
@ -1845,18 +1839,17 @@ pub fn build_session_options_and_crate_config(
};
let edition = match matches.opt_str("edition") {
Some(arg) => match Edition::from_str(&arg){
Ok(edition) => edition,
Err(_) => early_error(
Some(arg) => Edition::from_str(&arg).unwrap_or_else(|_|
early_error(
ErrorOutputType::default(),
&format!(
"argument for --edition must be one of: \
{}. (instead was `{}`)",
{}. (instead was `{}`)",
EDITION_NAME_LIST,
arg
),
),
}
),
None => DEFAULT_EDITION,
};
@ -1865,7 +1858,7 @@ pub fn build_session_options_and_crate_config(
ErrorOutputType::default(),
&format!(
"Edition {} is unstable and only \
available for nightly builds of rustc.",
available for nightly builds of rustc.",
edition,
)
)
@ -1925,9 +1918,8 @@ pub fn build_session_options_and_crate_config(
for output_type in list.split(',') {
let mut parts = output_type.splitn(2, '=');
let shorthand = parts.next().unwrap();
let output_type = match OutputType::from_shorthand(shorthand) {
Some(output_type) => output_type,
None => early_error(
let output_type = OutputType::from_shorthand(shorthand).unwrap_or_else(||
early_error(
error_format,
&format!(
"unknown emission type: `{}` - expected one of: {}",
@ -1935,7 +1927,7 @@ pub fn build_session_options_and_crate_config(
OutputType::shorthands_display(),
),
),
};
);
let path = parts.next().map(PathBuf::from);
output_types.insert(output_type, path);
}
@ -2063,12 +2055,8 @@ pub fn build_session_options_and_crate_config(
let target_triple = if let Some(target) = matches.opt_str("target") {
if target.ends_with(".json") {
let path = Path::new(&target);
match TargetTriple::from_path(&path) {
Ok(triple) => triple,
Err(_) => {
early_error(error_format, &format!("target file {:?} does not exist", path))
}
}
TargetTriple::from_path(&path).unwrap_or_else(|_|
early_error(error_format, &format!("target file {:?} does not exist", path)))
} else {
TargetTriple::TargetTriple(target)
}
@ -2169,7 +2157,7 @@ pub fn build_session_options_and_crate_config(
let mut name_parts = name.splitn(2, ':');
let name = name_parts.next().unwrap();
let new_name = name_parts.next();
(name.to_string(), new_name.map(|n| n.to_string()), kind)
(name.to_owned(), new_name.map(|n| n.to_owned()), kind)
})
.collect();
@ -2223,10 +2211,8 @@ pub fn build_session_options_and_crate_config(
let mut externs: BTreeMap<_, BTreeSet<_>> = BTreeMap::new();
for arg in &matches.opt_strs("extern") {
let mut parts = arg.splitn(2, '=');
let name = match parts.next() {
Some(s) => s,
None => early_error(error_format, "--extern value must not be empty"),
};
let name = parts.next().unwrap_or_else(||
early_error(error_format, "--extern value must not be empty"));
let location = parts.next().map(|s| s.to_string());
if location.is_none() && !is_unstable_enabled {
early_error(
@ -2237,7 +2223,7 @@ pub fn build_session_options_and_crate_config(
};
externs
.entry(name.to_string())
.entry(name.to_owned())
.or_default()
.insert(location);
}
@ -2308,9 +2294,7 @@ pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateTy
"cdylib" => CrateType::Cdylib,
"bin" => CrateType::Executable,
"proc-macro" => CrateType::ProcMacro,
_ => {
return Err(format!("unknown crate type: `{}`", part));
}
_ => return Err(format!("unknown crate type: `{}`", part))
};
if !crate_types.contains(&new_part) {
crate_types.push(new_part)

View file

@ -41,7 +41,7 @@ impl<'a> FileSearch<'a> {
F: FnMut(&Path, PathKind)
{
let mut visited_dirs = FxHashSet::default();
visited_dirs.reserve(self.search_paths.paths.len() + 1);
for (path, kind) in self.search_paths.iter(self.kind) {
f(path, kind);
visited_dirs.insert(path.to_path_buf());
@ -160,7 +160,7 @@ pub fn get_or_default_sysroot() -> PathBuf {
match env::current_exe() {
Ok(exe) => {
match canonicalize(Some(exe)) {
Some(mut p) => { p.pop(); p.pop(); return p; },
Some(mut p) => { p.pop(); p.pop(); p },
None => bug!("can't determine value for sysroot")
}
}
@ -175,18 +175,9 @@ fn find_libdir(sysroot: &Path) -> Cow<'static, str> {
// to lib64/lib32. This would be more foolproof by basing the sysroot off
// of the directory where librustc is located, rather than where the rustc
// binary is.
//If --libdir is set during configuration to the value other than
// If --libdir is set during configuration to the value other than
// "lib" (i.e. non-default), this value is used (see issue #16552).
match option_env!("CFG_LIBDIR_RELATIVE") {
Some(libdir) if libdir != "lib" => return libdir.into(),
_ => if sysroot.join(PRIMARY_LIB_DIR).join(RUST_LIB_DIR).exists() {
return PRIMARY_LIB_DIR.into();
} else {
return SECONDARY_LIB_DIR.into();
}
}
#[cfg(target_pointer_width = "64")]
const PRIMARY_LIB_DIR: &'static str = "lib64";
@ -194,6 +185,15 @@ fn find_libdir(sysroot: &Path) -> Cow<'static, str> {
const PRIMARY_LIB_DIR: &'static str = "lib32";
const SECONDARY_LIB_DIR: &'static str = "lib";
match option_env!("CFG_LIBDIR_RELATIVE") {
Some(libdir) if libdir != "lib" => libdir.into(),
_ => if sysroot.join(PRIMARY_LIB_DIR).join(RUST_LIB_DIR).exists() {
PRIMARY_LIB_DIR.into()
} else {
SECONDARY_LIB_DIR.into()
}
}
}
// The name of rustc's own place to organize libraries.

View file

@ -703,8 +703,8 @@ impl Session {
match self.opts.maybe_sysroot {
Some(ref sysroot) => sysroot,
None => self.default_sysroot
.as_ref()
.expect("missing sysroot and default_sysroot in Session"),
.as_ref()
.expect("missing sysroot and default_sysroot in Session"),
}
}
pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
@ -727,14 +727,8 @@ impl Session {
pub fn set_incr_session_load_dep_graph(&self, load: bool) {
let mut incr_comp_session = self.incr_comp_session.borrow_mut();
match *incr_comp_session {
IncrCompSession::Active {
ref mut load_dep_graph,
..
} => {
*load_dep_graph = load;
}
_ => {}
if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
*load_dep_graph = load;
}
}
@ -872,9 +866,9 @@ impl Session {
/// This expends fuel if applicable, and records fuel if applicable.
pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
let mut ret = true;
match self.optimization_fuel_crate {
Some(ref c) if c == crate_name => {
assert!(self.query_threads() == 1);
if let Some(ref c) = self.optimization_fuel_crate {
if c == crate_name {
assert_eq!(self.query_threads(), 1);
let fuel = self.optimization_fuel_limit.get();
ret = fuel != 0;
if fuel == 0 && !self.out_of_fuel.get() {
@ -884,14 +878,12 @@ impl Session {
self.optimization_fuel_limit.set(fuel - 1);
}
}
_ => {}
}
match self.print_fuel_crate {
Some(ref c) if c == crate_name => {
assert!(self.query_threads() == 1);
if let Some(ref c) = self.print_fuel_crate {
if c == crate_name {
assert_eq!(self.query_threads(), 1);
self.print_fuel.set(self.print_fuel.get() + 1);
}
_ => {}
}
ret
}
@ -1108,14 +1100,11 @@ pub fn build_session_(
source_map: Lrc<source_map::SourceMap>,
) -> Session {
let host_triple = TargetTriple::from_triple(config::host_triple());
let host = match Target::search(&host_triple) {
Ok(t) => t,
Err(e) => {
span_diagnostic
.fatal(&format!("Error loading host specification: {}", e))
.raise();
}
};
let host = Target::search(&host_triple).unwrap_or_else(|e|
span_diagnostic
.fatal(&format!("Error loading host specification: {}", e))
.raise()
);
let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
let p_s = parse::ParseSess::with_span_handler(span_diagnostic, source_map);
@ -1135,12 +1124,11 @@ pub fn build_session_(
let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
let print_fuel = LockCell::new(0);
let working_dir = match env::current_dir() {
Ok(dir) => dir,
Err(e) => p_s.span_diagnostic
let working_dir = env::current_dir().unwrap_or_else(|e|
p_s.span_diagnostic
.fatal(&format!("Current directory is invalid: {}", e))
.raise(),
};
.raise()
);
let working_dir = file_path_mapping.map_prefix(working_dir);
let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {

View file

@ -14,7 +14,7 @@ use session::{early_error, config};
#[derive(Clone, Debug)]
pub struct SearchPaths {
paths: Vec<(PathKind, PathBuf)>,
crate paths: Vec<(PathKind, PathBuf)>,
}
pub struct Iter<'a> {

View file

@ -1657,7 +1657,7 @@ pub fn build_output_filenames(
.crate_name
.clone()
.or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
.unwrap_or_else(|| input.filestem());
.unwrap_or_else(|| input.filestem().to_owned());
OutputFilenames {
out_directory: dirpath,