diff options
| author | Mark Rousskov <mark.simulacrum@gmail.com> | 2019-12-22 17:42:04 -0500 |
|---|---|---|
| committer | Mark Rousskov <mark.simulacrum@gmail.com> | 2019-12-22 17:42:47 -0500 |
| commit | a06baa56b95674fc626b3c3fd680d6a65357fe60 (patch) | |
| tree | cd9d867c2ca3cff5c1d6b3bd73377c44649fb075 /src/librustc_interface | |
| parent | 8eb7c58dbb7b32701af113bc58722d0d1fefb1eb (diff) | |
| download | rust-a06baa56b95674fc626b3c3fd680d6a65357fe60.tar.gz rust-a06baa56b95674fc626b3c3fd680d6a65357fe60.zip | |
Format the world
Diffstat (limited to 'src/librustc_interface')
| -rw-r--r-- | src/librustc_interface/interface.rs | 85 | ||||
| -rw-r--r-- | src/librustc_interface/lib.rs | 5 | ||||
| -rw-r--r-- | src/librustc_interface/passes.rs | 351 | ||||
| -rw-r--r-- | src/librustc_interface/proc_macro_decls.rs | 17 | ||||
| -rw-r--r-- | src/librustc_interface/queries.rs | 102 | ||||
| -rw-r--r-- | src/librustc_interface/tests.rs | 136 | ||||
| -rw-r--r-- | src/librustc_interface/util.rs | 197 |
7 files changed, 410 insertions, 483 deletions
diff --git a/src/librustc_interface/interface.rs b/src/librustc_interface/interface.rs index 2365fc3ee2e..62dd2db7099 100644 --- a/src/librustc_interface/interface.rs +++ b/src/librustc_interface/interface.rs @@ -1,25 +1,25 @@ -use crate::util; pub use crate::passes::BoxedResolver; +use crate::util; use rustc::lint; +use rustc::session::config::{self, ErrorOutputType, Input}; use rustc::session::early_error; -use rustc::session::config::{self, Input, ErrorOutputType}; use rustc::session::{DiagnosticOutput, Session}; +use rustc::ty; use rustc::util::common::ErrorReported; use rustc_codegen_utils::codegen_backend::CodegenBackend; -use rustc_data_structures::OnDrop; +use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::sync::Lrc; -use rustc_data_structures::fx::{FxHashSet, FxHashMap}; +use rustc_data_structures::OnDrop; use rustc_errors::registry::Registry; use rustc_parse::new_parser_from_source_str; -use rustc::ty; use std::path::PathBuf; use std::result; use std::sync::{Arc, Mutex}; use syntax::ast::{self, MetaItemKind}; -use syntax::token; -use syntax::source_map::{FileName, FileLoader, SourceMap}; use syntax::sess::ParseSess; +use syntax::source_map::{FileLoader, FileName, SourceMap}; +use syntax::token; use syntax_pos::edition; pub type Result<T> = result::Result<T, ErrorReported>; @@ -65,43 +65,48 @@ impl Compiler { /// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`. pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> { syntax::with_default_globals(move || { - let cfg = cfgspecs.into_iter().map(|s| { - let sess = ParseSess::with_silent_emitter(); - let filename = FileName::cfg_spec_source_code(&s); - let mut parser = new_parser_from_source_str(&sess, filename, s.to_string()); - - macro_rules! error {($reason: expr) => { - early_error(ErrorOutputType::default(), - &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s)); - }} - - match &mut parser.parse_meta_item() { - Ok(meta_item) if parser.token == token::Eof => { - if meta_item.path.segments.len() != 1 { - error!("argument key must be an identifier"); - } - match &meta_item.kind { - MetaItemKind::List(..) => { - error!(r#"expected `key` or `key="value"`"#); - } - MetaItemKind::NameValue(lit) if !lit.kind.is_str() => { - error!("argument value must be a string"); + let cfg = cfgspecs + .into_iter() + .map(|s| { + let sess = ParseSess::with_silent_emitter(); + let filename = FileName::cfg_spec_source_code(&s); + let mut parser = new_parser_from_source_str(&sess, filename, s.to_string()); + + macro_rules! error { + ($reason: expr) => { + early_error( + ErrorOutputType::default(), + &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s), + ); + }; + } + + match &mut parser.parse_meta_item() { + Ok(meta_item) if parser.token == token::Eof => { + if meta_item.path.segments.len() != 1 { + error!("argument key must be an identifier"); } - MetaItemKind::NameValue(..) | MetaItemKind::Word => { - let ident = meta_item.ident().expect("multi-segment cfg key"); - return (ident.name, meta_item.value_str()); + match &meta_item.kind { + MetaItemKind::List(..) => { + error!(r#"expected `key` or `key="value"`"#); + } + MetaItemKind::NameValue(lit) if !lit.kind.is_str() => { + error!("argument value must be a string"); + } + MetaItemKind::NameValue(..) | MetaItemKind::Word => { + let ident = meta_item.ident().expect("multi-segment cfg key"); + return (ident.name, meta_item.value_str()); + } } } + Ok(..) => {} + Err(err) => err.cancel(), } - Ok(..) => {} - Err(err) => err.cancel(), - } - - error!(r#"expected `key` or `key="value"`"#); - }).collect::<ast::CrateConfig>(); - cfg.into_iter().map(|(a, b)| { - (a.to_string(), b.map(|b| b.to_string())) - }).collect() + + error!(r#"expected `key` or `key="value"`"#); + }) + .collect::<ast::CrateConfig>(); + cfg.into_iter().map(|(a, b)| (a.to_string(), b.map(|b| b.to_string()))).collect() }) } diff --git a/src/librustc_interface/lib.rs b/src/librustc_interface/lib.rs index 9bb18788171..3d796619788 100644 --- a/src/librustc_interface/lib.rs +++ b/src/librustc_interface/lib.rs @@ -6,17 +6,16 @@ #![feature(generator_trait)] #![feature(generators)] #![cfg_attr(unix, feature(libc))] - -#![recursion_limit="256"] +#![recursion_limit = "256"] #[cfg(unix)] extern crate libc; pub mod interface; mod passes; +mod proc_macro_decls; mod queries; pub mod util; -mod proc_macro_decls; pub use interface::{run_compiler, Config}; pub use queries::Queries; diff --git a/src/librustc_interface/passes.rs b/src/librustc_interface/passes.rs index e1c4c86d9d6..9d0ec585c20 100644 --- a/src/librustc_interface/passes.rs +++ b/src/librustc_interface/passes.rs @@ -1,29 +1,29 @@ use crate::interface::{Compiler, Result}; -use crate::util; use crate::proc_macro_decls; +use crate::util; -use log::{info, warn, log_enabled}; +use log::{info, log_enabled, warn}; use rustc::arena::Arena; use rustc::dep_graph::DepGraph; use rustc::hir; -use rustc::hir::lowering::lower_crate; use rustc::hir::def_id::{CrateNum, LOCAL_CRATE}; +use rustc::hir::lowering::lower_crate; use rustc::lint; -use rustc::middle::{self, reachable, resolve_lifetime, stability}; use rustc::middle::cstore::{CrateStore, MetadataLoader, MetadataLoaderDyn}; -use rustc::ty::{self, AllArenas, ResolverOutputs, TyCtxt, GlobalCtxt}; -use rustc::ty::steal::Steal; -use rustc::traits; -use rustc::util::common::{time, ErrorReported}; -use rustc::session::Session; +use rustc::middle::{self, reachable, resolve_lifetime, stability}; use rustc::session::config::{self, CrateType, Input, OutputFilenames, OutputType}; use rustc::session::config::{PpMode, PpSourceMode}; use rustc::session::search_paths::PathKind; +use rustc::session::Session; +use rustc::traits; +use rustc::ty::steal::Steal; +use rustc::ty::{self, AllArenas, GlobalCtxt, ResolverOutputs, TyCtxt}; +use rustc::util::common::{time, ErrorReported}; use rustc_codegen_ssa::back::link::emit_metadata; use rustc_codegen_utils::codegen_backend::CodegenBackend; use rustc_codegen_utils::link::filename_for_metadata; +use rustc_data_structures::sync::{par_iter, Lrc, Once, ParallelIterator, WorkerLocal}; use rustc_data_structures::{box_region_allow_access, declare_box_region_type, parallel}; -use rustc_data_structures::sync::{Lrc, Once, ParallelIterator, par_iter, WorkerLocal}; use rustc_errors::PResult; use rustc_incremental; use rustc_mir as mir; @@ -34,29 +34,28 @@ use rustc_privacy; use rustc_resolve::{Resolver, ResolverArenas}; use rustc_traits; use rustc_typeck as typeck; -use syntax::{self, ast, visit}; use syntax::early_buffered_lints::BufferedEarlyLint; -use syntax_expand::base::ExtCtxt; use syntax::mut_visit::MutVisitor; -use syntax::util::node_count::NodeCounter; use syntax::symbol::Symbol; -use syntax_pos::FileName; +use syntax::util::node_count::NodeCounter; +use syntax::{self, ast, visit}; +use syntax_expand::base::ExtCtxt; use syntax_ext; +use syntax_pos::FileName; use rustc_serialize::json; use tempfile::Builder as TempFileBuilder; -use std::{env, fs, iter, mem}; use std::any::Any; +use std::cell::RefCell; use std::ffi::OsString; use std::io::{self, Write}; use std::path::PathBuf; -use std::cell::RefCell; use std::rc::Rc; +use std::{env, fs, iter, mem}; pub fn parse<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> { - sess.diagnostic() - .set_continue_after_error(sess.opts.debugging_opts.continue_parse_after_error); + sess.diagnostic().set_continue_after_error(sess.opts.debugging_opts.continue_parse_after_error); let krate = time(sess, "parsing", || { let _prof_timer = sess.prof.generic_activity("parse_crate"); @@ -75,10 +74,7 @@ pub fn parse<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> { } if sess.opts.debugging_opts.input_stats { - println!( - "Lines of code: {}", - sess.source_map().count_lines() - ); + println!("Lines of code: {}", sess.source_map().count_lines()); println!("Pre-expansion node count: {}", count_nodes(&krate)); } @@ -169,7 +165,9 @@ pub fn register_plugins<'a>( ) -> Result<(ast::Crate, Lrc<lint::LintStore>)> { krate = time(sess, "attributes injection", || { syntax_ext::cmdline_attrs::inject( - krate, &sess.parse_sess, &sess.opts.debugging_opts.crate_attr + krate, + &sess.parse_sess, + &sess.opts.debugging_opts.crate_attr, ) }); @@ -213,9 +211,8 @@ pub fn register_plugins<'a>( ); register_lints(&sess, &mut lint_store); - let registrars = time(sess, "plugin loading", || { - plugin::load::load_plugins(sess, metadata_loader, &krate) - }); + let registrars = + time(sess, "plugin loading", || plugin::load::load_plugins(sess, metadata_loader, &krate)); time(sess, "plugin registration", || { let mut registry = plugin::Registry { lint_store: &mut lint_store }; for registrar in registrars { @@ -241,16 +238,11 @@ fn configure_and_expand_inner<'a>( &krate, true, None, - rustc_lint::BuiltinCombinedPreExpansionLintPass::new()); + rustc_lint::BuiltinCombinedPreExpansionLintPass::new(), + ); }); - let mut resolver = Resolver::new( - sess, - &krate, - crate_name, - metadata_loader, - &resolver_arenas, - ); + let mut resolver = Resolver::new(sess, &krate, crate_name, metadata_loader, &resolver_arenas); syntax_ext::register_builtin_macros(&mut resolver, sess.edition()); krate = time(sess, "crate injection", || { @@ -297,10 +289,9 @@ fn configure_and_expand_inner<'a>( env::set_var( "PATH", &env::join_paths( - new_path - .iter() - .filter(|p| env::join_paths(iter::once(p)).is_ok()), - ).unwrap(), + new_path.iter().filter(|p| env::join_paths(iter::once(p)).is_ok()), + ) + .unwrap(), ); } @@ -317,9 +308,7 @@ fn configure_and_expand_inner<'a>( let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver); // Expand macros now! - let krate = time(sess, "expand crate", || { - ecx.monotonic_expander().expand_crate(krate) - }); + let krate = time(sess, "expand crate", || ecx.monotonic_expander().expand_crate(krate)); // The rest is error reporting @@ -327,12 +316,8 @@ fn configure_and_expand_inner<'a>( ecx.check_unused_macros(); }); - let mut missing_fragment_specifiers: Vec<_> = ecx.parse_sess - .missing_fragment_specifiers - .borrow() - .iter() - .cloned() - .collect(); + let mut missing_fragment_specifiers: Vec<_> = + ecx.parse_sess.missing_fragment_specifiers.borrow().iter().cloned().collect(); missing_fragment_specifiers.sort(); for span in missing_fragment_specifiers { @@ -374,7 +359,6 @@ fn configure_and_expand_inner<'a>( ast_validation::check_crate(sess, &krate, &mut resolver.lint_buffer()) }); - let crate_types = sess.crate_types.borrow(); let is_proc_macro_crate = crate_types.contains(&config::CrateType::ProcMacro); @@ -385,8 +369,10 @@ fn configure_and_expand_inner<'a>( // However, we do emit a warning, to let such users know that they should // start passing '--crate-type proc-macro' if has_proc_macro_decls && sess.opts.actually_rustdoc && !is_proc_macro_crate { - let mut msg = sess.diagnostic().struct_warn(&"Trying to document proc macro crate \ - without passing '--crate-type proc-macro to rustdoc"); + let mut msg = sess.diagnostic().struct_warn( + &"Trying to document proc macro crate \ + without passing '--crate-type proc-macro to rustdoc", + ); msg.warn("The generated documentation may be incorrect"); msg.emit() @@ -438,7 +424,7 @@ fn configure_and_expand_inner<'a>( // Add all buffered lints from the `ParseSess` to the `Session`. sess.parse_sess.buffered_lints.with_lock(|buffered_lints| { info!("{} parse sess buffered_lints", buffered_lints.len()); - for BufferedEarlyLint{id, span, msg, lint_id} in buffered_lints.drain(..) { + for BufferedEarlyLint { id, span, msg, lint_id } in buffered_lints.drain(..) { resolver.lint_buffer().buffer_lint(lint_id, id, span, &msg); } }); @@ -498,15 +484,17 @@ fn generated_output_paths( match *output_type { // If the filename has been overridden using `-o`, it will not be modified // by appending `.rlib`, `.exe`, etc., so we can skip this transformation. - OutputType::Exe if !exact_name => for crate_type in sess.crate_types.borrow().iter() { - let p = ::rustc_codegen_utils::link::filename_for_input( - sess, - *crate_type, - crate_name, - outputs, - ); - out_filenames.push(p); - }, + OutputType::Exe if !exact_name => { + for crate_type in sess.crate_types.borrow().iter() { + let p = ::rustc_codegen_utils::link::filename_for_input( + sess, + *crate_type, + crate_name, + outputs, + ); + out_filenames.push(p); + } + } OutputType::DepInfo if sess.opts.debugging_opts.dep_info_omit_d_target => { // Don't add the dep-info output when omitting it from dep-info targets } @@ -538,11 +526,7 @@ fn output_contains_path(output_paths: &[PathBuf], input_path: &PathBuf) -> bool return false; } let check = |output_path: &PathBuf| { - if output_path.canonicalize().ok() == input_path { - Some(()) - } else { - None - } + if output_path.canonicalize().ok() == input_path { Some(()) } else { None } }; check_output(output_paths, check).is_some() } @@ -573,7 +557,8 @@ fn write_out_deps( let result = (|| -> io::Result<()> { // Build a list of files used to compile the output and // write Makefile-compatible dependency rules - let mut files: Vec<String> = sess.source_map() + let mut files: Vec<String> = sess + .source_map() .files() .iter() .filter(|fmap| fmap.is_real_file()) @@ -615,17 +600,16 @@ fn write_out_deps( match result { Ok(_) => { if sess.opts.json_artifact_notifications { - sess.parse_sess.span_diagnostic + sess.parse_sess + .span_diagnostic .emit_artifact_notification(&deps_filename, "dep-info"); } - }, - Err(e) => { - sess.fatal(&format!( - "error writing dependencies to `{}`: {}", - deps_filename.display(), - e - )) } + Err(e) => sess.fatal(&format!( + "error writing dependencies to `{}`: {}", + deps_filename.display(), + e + )), } } @@ -634,7 +618,7 @@ pub fn prepare_outputs( compiler: &Compiler, krate: &ast::Crate, boxed_resolver: &Steal<Rc<RefCell<BoxedResolver>>>, - crate_name: &str + crate_name: &str, ) -> Result<OutputFilenames> { // FIXME: rustdoc passes &[] instead of &krate.attrs here let outputs = util::build_output_filenames( @@ -642,16 +626,12 @@ pub fn prepare_outputs( &compiler.output_dir, &compiler.output_file, &krate.attrs, - sess - ); - - let output_paths = generated_output_paths( sess, - &outputs, - compiler.output_file.is_some(), - &crate_name, ); + let output_paths = + generated_output_paths(sess, &outputs, compiler.output_file.is_some(), &crate_name); + // Ensure the source file isn't accidentally overwritten during compilation. if let Some(ref input_path) = compiler.input_path { if sess.opts.will_create_output_file() { @@ -755,9 +735,8 @@ pub fn create_global_ctxt<'tcx>( hir::map::map_crate(sess, &*resolver_outputs.cstore, &hir_forest, defs) }); - let query_result_on_disk_cache = time(sess, "load query result cache", || { - rustc_incremental::load_query_result_cache(sess) - }); + let query_result_on_disk_cache = + time(sess, "load query result cache", || rustc_incremental::load_query_result_cache(sess)); let codegen_backend = compiler.codegen_backend(); let mut local_providers = ty::query::Providers::default(); @@ -772,19 +751,21 @@ pub fn create_global_ctxt<'tcx>( callback(sess, &mut local_providers, &mut extern_providers); } - let gcx = global_ctxt.init_locking(|| TyCtxt::create_global_ctxt( - sess, - lint_store, - local_providers, - extern_providers, - &all_arenas, - arena, - resolver_outputs, - hir_map, - query_result_on_disk_cache, - &crate_name, - &outputs - )); + let gcx = global_ctxt.init_locking(|| { + TyCtxt::create_global_ctxt( + sess, + lint_store, + local_providers, + extern_providers, + &all_arenas, + arena, + resolver_outputs, + hir_map, + query_result_on_disk_cache, + &crate_name, + &outputs, + ) + }); // Do some initialization of the DepGraph that can only be done with the tcx available. ty::tls::enter_global(&gcx, |tcx| { @@ -803,53 +784,57 @@ fn analysis(tcx: TyCtxt<'_>, cnum: CrateNum) -> Result<()> { let mut entry_point = None; time(sess, "misc checking 1", || { - parallel!({ - entry_point = time(sess, "looking for entry point", || { - rustc_passes::entry::find_entry_point(tcx) - }); + parallel!( + { + entry_point = time(sess, "looking for entry point", || { + rustc_passes::entry::find_entry_point(tcx) + }); - time(sess, "looking for plugin registrar", || { - plugin::build::find_plugin_registrar(tcx) - }); + time(sess, "looking for plugin registrar", || { + plugin::build::find_plugin_registrar(tcx) + }); - time(sess, "looking for derive registrar", || { - proc_macro_decls::find(tcx) - }); - }, { - par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| { - let local_def_id = tcx.hir().local_def_id(module); - tcx.ensure().check_mod_loops(local_def_id); - tcx.ensure().check_mod_attrs(local_def_id); - tcx.ensure().check_mod_unstable_api_usage(local_def_id); - tcx.ensure().check_mod_const_bodies(local_def_id); - }); - }); + time(sess, "looking for derive registrar", || proc_macro_decls::find(tcx)); + }, + { + par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| { + let local_def_id = tcx.hir().local_def_id(module); + tcx.ensure().check_mod_loops(local_def_id); + tcx.ensure().check_mod_attrs(local_def_id); + tcx.ensure().check_mod_unstable_api_usage(local_def_id); + tcx.ensure().check_mod_const_bodies(local_def_id); + }); + } + ); }); // passes are timed inside typeck typeck::check_crate(tcx)?; time(sess, "misc checking 2", || { - parallel!({ - time(sess, "match checking", || { - tcx.par_body_owners(|def_id| { - tcx.ensure().check_match(def_id); + parallel!( + { + time(sess, "match checking", || { + tcx.par_body_owners(|def_id| { + tcx.ensure().check_match(def_id); + }); }); - }); - }, { - time(sess, "liveness checking + intrinsic checking", || { - par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| { - // this must run before MIR dump, because - // "not all control paths return a value" is reported here. - // - // maybe move the check to a MIR pass? - let local_def_id = tcx.hir().local_def_id(module); - - tcx.ensure().check_mod_liveness(local_def_id); - tcx.ensure().check_mod_intrinsics(local_def_id); + }, + { + time(sess, "liveness checking + intrinsic checking", || { + par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| { + // this must run before MIR dump, because + // "not all control paths return a value" is reported here. + // + // maybe move the check to a MIR pass? + let local_def_id = tcx.hir().local_def_id(module); + + tcx.ensure().check_mod_liveness(local_def_id); + tcx.ensure().check_mod_intrinsics(local_def_id); + }); }); - }); - }); + } + ); }); time(sess, "MIR borrow checking", || { @@ -878,32 +863,42 @@ fn analysis(tcx: TyCtxt<'_>, cnum: CrateNum) -> Result<()> { } time(sess, "misc checking 3", || { - parallel!({ - time(sess, "privacy access levels", || { - tcx.ensure().privacy_access_levels(LOCAL_CRATE); - }); - parallel!({ - time(sess, "private in public", || { - tcx.ensure().check_private_in_public(LOCAL_CRATE); - }); - }, { - time(sess, "death checking", || rustc_passes::dead::check_crate(tcx)); - }, { - time(sess, "unused lib feature checking", || { - stability::check_unused_or_stable_features(tcx) + parallel!( + { + time(sess, "privacy access levels", || { + tcx.ensure().privacy_access_levels(LOCAL_CRATE); }); - }, { - time(sess, "lint checking", || { - lint::check_crate(tcx, || rustc_lint::BuiltinCombinedLateLintPass::new()); - }); - }); - }, { - time(sess, "privacy checking modules", || { - par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| { - tcx.ensure().check_mod_privacy(tcx.hir().local_def_id(module)); + parallel!( + { + time(sess, "private in public", || { + tcx.ensure().check_private_in_public(LOCAL_CRATE); + }); + }, + { + time(sess, "death checking", || rustc_passes::dead::check_crate(tcx)); + }, + { + time(sess, "unused lib feature checking", || { + stability::check_unused_or_stable_features(tcx) + }); + }, + { + time(sess, "lint checking", || { + lint::check_crate(tcx, || { + rustc_lint::BuiltinCombinedLateLintPass::new() + }); + }); + } + ); + }, + { + time(sess, "privacy checking modules", || { + par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| { + tcx.ensure().check_mod_privacy(tcx.hir().local_def_id(module)); + }); }); - }); - }); + } + ); }); Ok(()) @@ -917,26 +912,27 @@ fn encode_and_write_metadata( enum MetadataKind { None, Uncompressed, - Compressed + Compressed, } - let metadata_kind = tcx.sess.crate_types.borrow().iter().map(|ty| { - match *ty { - CrateType::Executable | - CrateType::Staticlib | - CrateType::Cdylib => MetadataKind::None, + let metadata_kind = tcx + .sess + .crate_types + .borrow() + .iter() + .map(|ty| match *ty { + CrateType::Executable | CrateType::Staticlib | CrateType::Cdylib => MetadataKind::None, CrateType::Rlib => MetadataKind::Uncompressed, - CrateType::Dylib | - CrateType::ProcMacro => MetadataKind::Compressed, - } - }).max().unwrap_or(MetadataKind::None); + CrateType::Dylib | CrateType::ProcMacro => MetadataKind::Compressed, + }) + .max() + .unwrap_or(MetadataKind::None); let metadata = match metadata_kind { MetadataKind::None => middle::cstore::EncodedMetadata::new(), - MetadataKind::Uncompressed | - MetadataKind::Compressed => tcx.encode_metadata(), + MetadataKind::Uncompressed | MetadataKind::Compressed => tcx.encode_metadata(), }; let need_metadata_file = tcx.sess.opts.output_types.contains_key(&OutputType::Metadata); @@ -951,15 +947,15 @@ fn encode_and_write_metadata( let metadata_tmpdir = TempFileBuilder::new() .prefix("rmeta") .tempdir_in(out_filename.parent().unwrap()) - .unwrap_or_else(|err| { - tcx.sess.fatal(&format!("couldn't create a temp dir: {}", err)) - }); + .unwrap_or_else(|err| tcx.sess.fatal(&format!("couldn't create a temp dir: {}", err))); let metadata_filename = emit_metadata(tcx.sess, &metadata, &metadata_tmpdir); if let Err(e) = fs::rename(&metadata_filename, &out_filename) { tcx.sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e)); } if tcx.sess.opts.json_artifact_notifications { - tcx.sess.parse_sess.span_diagnostic + tcx.sess + .parse_sess + .span_diagnostic .emit_artifact_notification(&out_filename, "metadata"); } } @@ -981,9 +977,8 @@ pub fn start_codegen<'tcx>( tcx.print_debug_stats(); } - let (metadata, need_metadata_module) = time(tcx.sess, "metadata encoding and writing", || { - encode_and_write_metadata(tcx, outputs) - }); + let (metadata, need_metadata_module) = + time(tcx.sess, "metadata encoding and writing", || encode_and_write_metadata(tcx, outputs)); let codegen = time(tcx.sess, "codegen", move || { let _prof_timer = tcx.prof.generic_activity("codegen_crate"); diff --git a/src/librustc_interface/proc_macro_decls.rs b/src/librustc_interface/proc_macro_decls.rs index e3def175626..5bf35124a70 100644 --- a/src/librustc_interface/proc_macro_decls.rs +++ b/src/librustc_interface/proc_macro_decls.rs @@ -1,8 +1,8 @@ -use rustc::hir::itemlikevisit::ItemLikeVisitor; -use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use rustc::hir; -use rustc::ty::TyCtxt; +use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; +use rustc::hir::itemlikevisit::ItemLikeVisitor; use rustc::ty::query::Providers; +use rustc::ty::TyCtxt; use syntax::attr; use syntax::symbol::sym; @@ -30,16 +30,11 @@ impl<'v> ItemLikeVisitor<'v> for Finder { } } - fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) { - } + fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {} - fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) { - } + fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {} } pub(crate) fn provide(providers: &mut Providers<'_>) { - *providers = Providers { - proc_macro_decls_static, - ..*providers - }; + *providers = Providers { proc_macro_decls_static, ..*providers }; } diff --git a/src/librustc_interface/queries.rs b/src/librustc_interface/queries.rs index d6de9d5f4e4..4318f99e690 100644 --- a/src/librustc_interface/queries.rs +++ b/src/librustc_interface/queries.rs @@ -1,24 +1,24 @@ use crate::interface::{Compiler, Result}; use crate::passes::{self, BoxedResolver, QueryContext}; -use rustc_incremental::DepGraphFuture; -use rustc_data_structures::sync::{Lrc, Once, WorkerLocal}; -use rustc_codegen_utils::codegen_backend::CodegenBackend; -use rustc::session::config::{OutputFilenames, OutputType}; -use rustc::util::common::{time, ErrorReported}; use rustc::arena::Arena; +use rustc::dep_graph::DepGraph; use rustc::hir; +use rustc::hir::def_id::LOCAL_CRATE; use rustc::lint; -use rustc::session::Session; use rustc::lint::LintStore; -use rustc::hir::def_id::LOCAL_CRATE; +use rustc::session::config::{OutputFilenames, OutputType}; +use rustc::session::Session; use rustc::ty::steal::Steal; -use rustc::ty::{AllArenas, ResolverOutputs, GlobalCtxt}; -use rustc::dep_graph::DepGraph; -use std::cell::{Ref, RefMut, RefCell}; -use std::rc::Rc; +use rustc::ty::{AllArenas, GlobalCtxt, ResolverOutputs}; +use rustc::util::common::{time, ErrorReported}; +use rustc_codegen_utils::codegen_backend::CodegenBackend; +use rustc_data_structures::sync::{Lrc, Once, WorkerLocal}; +use rustc_incremental::DepGraphFuture; use std::any::Any; +use std::cell::{Ref, RefCell, RefMut}; use std::mem; +use std::rc::Rc; use syntax::{self, ast}; /// Represent the result of a query. @@ -39,11 +39,7 @@ impl<T> Query<T> { /// Takes ownership of the query result. Further attempts to take or peek the query /// result will panic unless it is generated by calling the `compute` method. pub fn take(&self) -> T { - self.result - .borrow_mut() - .take() - .expect("missing query result") - .unwrap() + self.result.borrow_mut().take().expect("missing query result").unwrap() } /// Borrows the query result using the RefCell. Panics if the result is stolen. @@ -63,9 +59,7 @@ impl<T> Query<T> { impl<T> Default for Query<T> { fn default() -> Self { - Query { - result: RefCell::new(None), - } + Query { result: RefCell::new(None) } } } @@ -117,20 +111,20 @@ impl<'tcx> Queries<'tcx> { pub fn dep_graph_future(&self) -> Result<&Query<Option<DepGraphFuture>>> { self.dep_graph_future.compute(|| { - Ok(self.session().opts.build_dep_graph().then(|| { - rustc_incremental::load_dep_graph(self.session()) - })) + Ok(self + .session() + .opts + .build_dep_graph() + .then(|| rustc_incremental::load_dep_graph(self.session()))) }) } pub fn parse(&self) -> Result<&Query<ast::Crate>> { self.parse.compute(|| { - passes::parse(self.session(), &self.compiler.input).map_err( - |mut parse_error| { - parse_error.emit(); - ErrorReported - }, - ) + passes::parse(self.session(), &self.compiler.input).map_err(|mut parse_error| { + parse_error.emit(); + ErrorReported + }) }) } @@ -143,10 +137,7 @@ impl<'tcx> Queries<'tcx> { let result = passes::register_plugins( self.session(), &*self.codegen_backend().metadata_loader(), - self.compiler.register_lints - .as_ref() - .map(|p| &**p) - .unwrap_or_else(|| empty), + self.compiler.register_lints.as_ref().map(|p| &**p).unwrap_or_else(|| empty), krate, &crate_name, ); @@ -172,7 +163,7 @@ impl<'tcx> Queries<'tcx> { rustc_codegen_utils::link::find_crate_name( Some(self.session()), &krate.attrs, - &self.compiler.input + &self.compiler.input, ) } }) @@ -180,7 +171,7 @@ impl<'tcx> Queries<'tcx> { } pub fn expansion( - &self + &self, ) -> Result<&Query<(ast::Crate, Steal<Rc<RefCell<BoxedResolver>>>, Lrc<LintStore>)>> { self.expansion.compute(|| { let crate_name = self.crate_name()?.peek().clone(); @@ -191,7 +182,8 @@ impl<'tcx> Queries<'tcx> { self.codegen_backend().metadata_loader(), krate, &crate_name, - ).map(|(krate, resolver)| { + ) + .map(|(krate, resolver)| { (krate, Steal::new(Rc::new(RefCell::new(resolver))), lint_store) }) }) @@ -204,9 +196,12 @@ impl<'tcx> Queries<'tcx> { Some(future) => { let (prev_graph, prev_work_products) = time(self.session(), "blocked while dep-graph loading finishes", || { - future.open().unwrap_or_else(|e| rustc_incremental::LoadResult::Error { - message: format!("could not decode incremental cache: {:?}", e), - }).open(self.session()) + future + .open() + .unwrap_or_else(|e| rustc_incremental::LoadResult::Error { + message: format!("could not decode incremental cache: {:?}", e), + }) + .open(self.session()) }); DepGraph::new(prev_graph, prev_work_products) } @@ -245,7 +240,11 @@ impl<'tcx> Queries<'tcx> { let crate_name = self.crate_name()?; let crate_name = crate_name.peek(); passes::prepare_outputs( - self.session(), self.compiler, &krate, &boxed_resolver, &crate_name + self.session(), + self.compiler, + &krate, + &boxed_resolver, + &crate_name, ) }) } @@ -280,11 +279,7 @@ impl<'tcx> Queries<'tcx> { // Don't do code generation if there were any errors self.session().compile_status()?; - Ok(passes::start_codegen( - &***self.codegen_backend(), - tcx, - &*outputs.peek() - )) + Ok(passes::start_codegen(&***self.codegen_backend(), tcx, &*outputs.peek())) }) }) } @@ -317,18 +312,21 @@ pub struct Linker { impl Linker { pub fn link(self) -> Result<()> { - self.codegen_backend.join_codegen_and_link( - self.ongoing_codegen, - &self.sess, - &self.dep_graph, - &self.prepare_outputs, - ).map_err(|_| ErrorReported) + self.codegen_backend + .join_codegen_and_link( + self.ongoing_codegen, + &self.sess, + &self.dep_graph, + &self.prepare_outputs, + ) + .map_err(|_| ErrorReported) } } impl Compiler { pub fn enter<F, T>(&self, f: F) -> T - where F: for<'tcx> FnOnce(&'tcx Queries<'tcx>) -> T + where + F: for<'tcx> FnOnce(&'tcx Queries<'tcx>) -> T, { let queries = Queries::new(&self); let ret = f(&queries); @@ -354,7 +352,7 @@ impl Compiler { if self.session().opts.output_types.contains_key(&OutputType::DepInfo) && self.session().opts.output_types.len() == 1 { - return Ok(None) + return Ok(None); } queries.global_ctxt()?; diff --git a/src/librustc_interface/tests.rs b/src/librustc_interface/tests.rs index d4b5e833dfb..4ae579cfca2 100644 --- a/src/librustc_interface/tests.rs +++ b/src/librustc_interface/tests.rs @@ -5,20 +5,20 @@ use crate::interface::parse_cfgspecs; use rustc::lint; use rustc::middle::cstore; use rustc::session::config::{build_configuration, build_session_options, to_crate_config}; -use rustc::session::config::{LtoCli, LinkerPluginLto, SwitchWithOptPath, ExternEntry}; +use rustc::session::config::{rustc_optgroups, ErrorOutputType, ExternLocation, Options, Passes}; +use rustc::session::config::{ExternEntry, LinkerPluginLto, LtoCli, SwitchWithOptPath}; use rustc::session::config::{Externs, OutputType, OutputTypes, SymbolManglingVersion}; -use rustc::session::config::{rustc_optgroups, Options, ErrorOutputType, Passes, ExternLocation}; -use rustc::session::{build_session, Session}; use rustc::session::search_paths::SearchPath; +use rustc::session::{build_session, Session}; +use rustc_data_structures::fx::FxHashSet; +use rustc_errors::{emitter::HumanReadableErrorType, registry, ColorConfig}; +use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel}; use std::collections::{BTreeMap, BTreeSet}; use std::iter::FromIterator; use std::path::PathBuf; -use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel}; -use syntax::symbol::sym; -use syntax::edition::{Edition, DEFAULT_EDITION}; use syntax; -use rustc_data_structures::fx::FxHashSet; -use rustc_errors::{ColorConfig, emitter::HumanReadableErrorType, registry}; +use syntax::edition::{Edition, DEFAULT_EDITION}; +use syntax::symbol::sym; type CfgSpecs = FxHashSet<(String, Option<String>)>; @@ -40,8 +40,7 @@ where S: Into<String>, I: IntoIterator<Item = S>, { - let locations: BTreeSet<_> = locations.into_iter().map(|s| s.into()) - .collect(); + let locations: BTreeSet<_> = locations.into_iter().map(|s| s.into()).collect(); ExternEntry { location: ExternLocation::ExactPaths(locations), @@ -95,9 +94,8 @@ fn test_can_print_warnings() { }); syntax::with_default_globals(|| { - let matches = optgroups() - .parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()]) - .unwrap(); + let matches = + optgroups().parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()]).unwrap(); let (sess, _) = mk_session(matches); assert!(sess.diagnostic().can_emit_warnings()); }); @@ -115,10 +113,8 @@ fn test_output_types_tracking_hash_different_paths() { let mut v2 = Options::default(); let mut v3 = Options::default(); - v1.output_types = - OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("./some/thing")))]); - v2.output_types = - OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("/some/thing")))]); + v1.output_types = OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("./some/thing")))]); + v2.output_types = OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("/some/thing")))]); v3.output_types = OutputTypes::new(&[(OutputType::Exe, None)]); assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash()); @@ -159,36 +155,18 @@ fn test_externs_tracking_hash_different_construction_order() { let mut v3 = Options::default(); v1.externs = Externs::new(mk_map(vec![ - ( - String::from("a"), - new_public_extern_entry(vec!["b", "c"]) - ), - ( - String::from("d"), - new_public_extern_entry(vec!["e", "f"]) - ), + (String::from("a"), new_public_extern_entry(vec!["b", "c"])), + (String::from("d"), new_public_extern_entry(vec!["e", "f"])), ])); v2.externs = Externs::new(mk_map(vec![ - ( - String::from("d"), - new_public_extern_entry(vec!["e", "f"]) - ), - ( - String::from("a"), - new_public_extern_entry(vec!["b", "c"]) - ), + (String::from("d"), new_public_extern_entry(vec!["e", "f"])), + (String::from("a"), new_public_extern_entry(vec!["b", "c"])), ])); v3.externs = Externs::new(mk_map(vec![ - ( - String::from("a"), - new_public_extern_entry(vec!["b", "c"]) - ), - ( - String::from("d"), - new_public_extern_entry(vec!["f", "e"]) - ), + (String::from("a"), new_public_extern_entry(vec!["b", "c"])), + (String::from("d"), new_public_extern_entry(vec!["f", "e"])), ])); assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash()); @@ -277,49 +255,29 @@ fn test_search_paths_tracking_hash_different_order() { }; // Reference - v1.search_paths - .push(SearchPath::from_cli_opt("native=abc", JSON)); - v1.search_paths - .push(SearchPath::from_cli_opt("crate=def", JSON)); - v1.search_paths - .push(SearchPath::from_cli_opt("dependency=ghi", JSON)); - v1.search_paths - .push(SearchPath::from_cli_opt("framework=jkl", JSON)); - v1.search_paths - .push(SearchPath::from_cli_opt("all=mno", JSON)); - - v2.search_paths - .push(SearchPath::from_cli_opt("native=abc", JSON)); - v2.search_paths - .push(SearchPath::from_cli_opt("dependency=ghi", JSON)); - v2.search_paths - .push(SearchPath::from_cli_opt("crate=def", JSON)); - v2.search_paths - .push(SearchPath::from_cli_opt("framework=jkl", JSON)); - v2.search_paths - .push(SearchPath::from_cli_opt("all=mno", JSON)); - - v3.search_paths - .push(SearchPath::from_cli_opt("crate=def", JSON)); - v3.search_paths - .push(SearchPath::from_cli_opt("framework=jkl", JSON)); - v3.search_paths - .push(SearchPath::from_cli_opt("native=abc", JSON)); - v3.search_paths - .push(SearchPath::from_cli_opt("dependency=ghi", JSON)); - v3.search_paths - .push(SearchPath::from_cli_opt("all=mno", JSON)); - - v4.search_paths - .push(SearchPath::from_cli_opt("all=mno", JSON)); - v4.search_paths - .push(SearchPath::from_cli_opt("native=abc", JSON)); - v4.search_paths - .push(SearchPath::from_cli_opt("crate=def", JSON)); - v4.search_paths - .push(SearchPath::from_cli_opt("dependency=ghi", JSON)); - v4.search_paths - .push(SearchPath::from_cli_opt("framework=jkl", JSON)); + v1.search_paths.push(SearchPath::from_cli_opt("native=abc", JSON)); + v1.search_paths.push(SearchPath::from_cli_opt("crate=def", JSON)); + v1.search_paths.push(SearchPath::from_cli_opt("dependency=ghi", JSON)); + v1.search_paths.push(SearchPath::from_cli_opt("framework=jkl", JSON)); + v1.search_paths.push(SearchPath::from_cli_opt("all=mno", JSON)); + + v2.search_paths.push(SearchPath::from_cli_opt("native=abc", JSON)); + v2.search_paths.push(SearchPath::from_cli_opt("dependency=ghi", JSON)); + v2.search_paths.push(SearchPath::from_cli_opt("crate=def", JSON)); + v2.search_paths.push(SearchPath::from_cli_opt("framework=jkl", JSON)); + v2.search_paths.push(SearchPath::from_cli_opt("all=mno", JSON)); + + v3.search_paths.push(SearchPath::from_cli_opt("crate=def", JSON)); + v3.search_paths.push(SearchPath::from_cli_opt("framework=jkl", JSON)); + v3.search_paths.push(SearchPath::from_cli_opt("native=abc", JSON)); + v3.search_paths.push(SearchPath::from_cli_opt("dependency=ghi", JSON)); + v3.search_paths.push(SearchPath::from_cli_opt("all=mno", JSON)); + + v4.search_paths.push(SearchPath::from_cli_opt("all=mno", JSON)); + v4.search_paths.push(SearchPath::from_cli_opt("native=abc", JSON)); + v4.search_paths.push(SearchPath::from_cli_opt("crate=def", JSON)); + v4.search_paths.push(SearchPath::from_cli_opt("dependency=ghi", JSON)); + v4.search_paths.push(SearchPath::from_cli_opt("framework=jkl", JSON)); assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash()); assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash()); @@ -363,11 +321,7 @@ fn test_native_libs_tracking_hash_different_values() { // Change new-name v4.libs = vec![ (String::from("a"), None, Some(cstore::NativeStatic)), - ( - String::from("b"), - Some(String::from("X")), - Some(cstore::NativeFramework), - ), + (String::from("b"), Some(String::from("X")), Some(cstore::NativeFramework)), (String::from("c"), None, Some(cstore::NativeUnknown)), ]; @@ -686,9 +640,7 @@ fn test_edition_parsing() { let options = Options::default(); assert!(options.edition == DEFAULT_EDITION); - let matches = optgroups() - .parse(&["--edition=2018".to_string()]) - .unwrap(); + let matches = optgroups().parse(&["--edition=2018".to_string()]).unwrap(); let (sessopts, _) = build_session_options_and_crate_config(matches); assert!(sessopts.edition == Edition::Edition2018) } diff --git a/src/librustc_interface/util.rs b/src/librustc_interface/util.rs index a8800082c9a..1a2958a0a92 100644 --- a/src/librustc_interface/util.rs +++ b/src/librustc_interface/util.rs @@ -1,36 +1,36 @@ use log::info; -use rustc::session::config::{Input, OutputFilenames, ErrorOutputType}; -use rustc::session::{self, config, early_error, filesearch, Session, DiagnosticOutput}; +use rustc::lint; +use rustc::session::config::{ErrorOutputType, Input, OutputFilenames}; use rustc::session::CrateDisambiguator; +use rustc::session::{self, config, early_error, filesearch, DiagnosticOutput, Session}; use rustc::ty; -use rustc::lint; use rustc_codegen_utils::codegen_backend::CodegenBackend; +use rustc_data_structures::fingerprint::Fingerprint; +use rustc_data_structures::fx::{FxHashMap, FxHashSet}; #[cfg(parallel_compiler)] use rustc_data_structures::jobserver; -use rustc_data_structures::sync::{Lock, Lrc}; use rustc_data_structures::stable_hasher::StableHasher; -use rustc_data_structures::fingerprint::Fingerprint; -use rustc_data_structures::fx::{FxHashSet, FxHashMap}; +use rustc_data_structures::sync::{Lock, Lrc}; use rustc_errors::registry::Registry; use rustc_metadata::dynamic_lib::DynamicLibrary; use rustc_resolve::{self, Resolver}; +use smallvec::SmallVec; use std::env; use std::io::{self, Write}; use std::mem; +use std::ops::DerefMut; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, Once}; -use std::ops::DerefMut; -use smallvec::SmallVec; -use syntax::ptr::P; -use syntax::mut_visit::{*, MutVisitor, visit_clobber}; +#[cfg(not(parallel_compiler))] +use std::{panic, thread}; use syntax::ast::{AttrVec, BlockCheckMode}; -use syntax::util::lev_distance::find_best_match_for_name; +use syntax::mut_visit::{visit_clobber, MutVisitor, *}; +use syntax::ptr::P; use syntax::source_map::{FileLoader, RealFileLoader, SourceMap}; -use syntax::symbol::{Symbol, sym}; +use syntax::symbol::{sym, Symbol}; +use syntax::util::lev_distance::find_best_match_for_name; use syntax::{self, ast, attr}; use syntax_pos::edition::Edition; -#[cfg(not(parallel_compiler))] -use std::{thread, panic}; /// Adds `target_feature = "..."` cfgs for a variety of platform /// specific features (SSE, NEON etc.). @@ -44,12 +44,7 @@ pub fn add_configuration( ) { let tf = sym::target_feature; - cfg.extend( - codegen_backend - .target_features(sess) - .into_iter() - .map(|feat| (tf, Some(feat))), - ); + cfg.extend(codegen_backend.target_features(sess).into_iter().map(|feat| (tf, Some(feat)))); if sess.crt_static_feature() { cfg.insert((tf, Some(Symbol::intern("crt-static")))); @@ -66,10 +61,7 @@ pub fn create_session( descriptions: Registry, ) -> (Lrc<Session>, Lrc<Box<dyn CodegenBackend>>, Lrc<SourceMap>) { let loader = file_loader.unwrap_or(box RealFileLoader); - let source_map = Lrc::new(SourceMap::with_file_loader( - loader, - sopts.file_path_mapping(), - )); + let source_map = Lrc::new(SourceMap::with_file_loader(loader, sopts.file_path_mapping())); let mut sess = session::build_session_with_source_map( sopts, input_path, @@ -112,7 +104,9 @@ impl Write for Sink { fn write(&mut self, data: &[u8]) -> io::Result<usize> { Write::write(&mut *self.0.lock().unwrap(), data) } - fn flush(&mut self) -> io::Result<()> { Ok(()) } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } } #[cfg(not(parallel_compiler))] @@ -225,9 +219,12 @@ fn load_backend_from_dylib(path: &Path) -> fn() -> Box<dyn CodegenBackend> { mem::transmute::<*mut u8, _>(f) } Err(e) => { - let err = format!("couldn't load codegen backend as it \ + let err = format!( + "couldn't load codegen backend as it \ doesn't export the `__rustc_codegen_backend` \ - symbol: {:?}", e); + symbol: {:?}", + e + ); early_error(ErrorOutputType::default(), &err); } } @@ -240,12 +237,14 @@ pub fn get_codegen_backend(sess: &Session) -> Box<dyn CodegenBackend> { static mut LOAD: fn() -> Box<dyn CodegenBackend> = || unreachable!(); INIT.call_once(|| { - let codegen_name = sess.opts.debugging_opts.codegen_backend.as_ref() + let codegen_name = sess + .opts + .debugging_opts + .codegen_backend + .as_ref() .unwrap_or(&sess.target.target.options.codegen_backend); let backend = match &codegen_name[..] { - filename if filename.contains(".") => { - load_backend_from_dylib(filename.as_ref()) - } + filename if filename.contains(".") => load_backend_from_dylib(filename.as_ref()), codegen_name => get_builtin_codegen_backend(codegen_name), }; @@ -271,7 +270,8 @@ pub fn rustc_path<'a>() -> Option<&'a Path> { } fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> { - sysroot_candidates().iter() + sysroot_candidates() + .iter() .filter_map(|sysroot| { let candidate = sysroot.join(bin_path).join(if cfg!(target_os = "windows") { "rustc.exe" @@ -303,10 +303,12 @@ fn sysroot_candidates() -> Vec<PathBuf> { sysroot_candidates.push(path.to_owned()); if path.ends_with(target) { - sysroot_candidates.extend(path.parent() // chop off `$target` - .and_then(|p| p.parent()) // chop off `rustlib` - .and_then(|p| p.parent()) // chop off `lib` - .map(|s| s.to_owned())); + sysroot_candidates.extend( + path.parent() // chop off `$target` + .and_then(|p| p.parent()) // chop off `rustlib` + .and_then(|p| p.parent()) // chop off `lib` + .map(|s| s.to_owned()), + ); } } } @@ -315,7 +317,7 @@ fn sysroot_candidates() -> Vec<PathBuf> { #[cfg(unix)] fn current_dll_path() -> Option<PathBuf> { - use std::ffi::{OsStr, CStr}; + use std::ffi::{CStr, OsStr}; use std::os::unix::prelude::*; unsafe { @@ -323,11 +325,11 @@ fn sysroot_candidates() -> Vec<PathBuf> { let mut info = mem::zeroed(); if libc::dladdr(addr, &mut info) == 0 { info!("dladdr failed"); - return None + return None; } if info.dli_fname.is_null() { info!("dladdr returned null pointer"); - return None + return None; } let bytes = CStr::from_ptr(info.dli_fname).to_bytes(); let os = OsStr::from_bytes(bytes); @@ -341,38 +343,33 @@ fn sysroot_candidates() -> Vec<PathBuf> { use std::os::windows::prelude::*; extern "system" { - fn GetModuleHandleExW(dwFlags: u32, - lpModuleName: usize, - phModule: *mut usize) -> i32; - fn GetModuleFileNameW(hModule: usize, - lpFilename: *mut u16, - nSize: u32) -> u32; + fn GetModuleHandleExW(dwFlags: u32, lpModuleName: usize, phModule: *mut usize) -> i32; + fn GetModuleFileNameW(hModule: usize, lpFilename: *mut u16, nSize: u32) -> u32; } const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS: u32 = 0x00000004; unsafe { let mut module = 0; - let r = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, - current_dll_path as usize, - &mut module); + let r = GetModuleHandleExW( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, + current_dll_path as usize, + &mut module, + ); if r == 0 { info!("GetModuleHandleExW failed: {}", io::Error::last_os_error()); - return None + return None; } let mut space = Vec::with_capacity(1024); - let r = GetModuleFileNameW(module, - space.as_mut_ptr(), - space.capacity() as u32); + let r = GetModuleFileNameW(module, space.as_mut_ptr(), space.capacity() as u32); if r == 0 { info!("GetModuleFileNameW failed: {}", io::Error::last_os_error()); - return None + return None; } let r = r as usize; if r >= space.capacity() { - info!("our buffer was too small? {}", - io::Error::last_os_error()); - return None + info!("our buffer was too small? {}", io::Error::last_os_error()); + return None; } space.set_len(r); let os = OsString::from_wide(&space); @@ -420,10 +417,7 @@ pub(crate) fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguat // Also incorporate crate type, so that we don't get symbol conflicts when // linking against a library of the same name, if this is an executable. - let is_exe = session - .crate_types - .borrow() - .contains(&config::CrateType::Executable); + let is_exe = session.crate_types.borrow().contains(&config::CrateType::Executable); hasher.write(if is_exe { b"exe" } else { b"lib" }); CrateDisambiguator::from(hasher.finish::<Fingerprint>()) @@ -443,7 +437,7 @@ pub(crate) fn check_attr_crate_type(attrs: &[ast::Attribute], lint_buffer: &mut let lev_candidate = find_best_match_for_name( CRATE_TYPES.iter().map(|(k, _)| k), &n.as_str(), - None + None, ); if let Some(candidate) = lev_candidate { lint_buffer.buffer_lint_with_diagnostic( @@ -451,19 +445,18 @@ pub(crate) fn check_attr_crate_type(attrs: &[ast::Attribute], lint_buffer: &mut ast::CRATE_NODE_ID, span, "invalid `crate_type` value", - lint::builtin::BuiltinLintDiagnostics:: - UnknownCrateTypes( - span, - "did you mean".to_string(), - format!("\"{}\"", candidate) - ) + lint::builtin::BuiltinLintDiagnostics::UnknownCrateTypes( + span, + "did you mean".to_string(), + format!("\"{}\"", candidate), + ), ); } else { lint_buffer.buffer_lint( lint::builtin::UNKNOWN_CRATE_TYPES, ast::CRATE_NODE_ID, span, - "invalid `crate_type` value" + "invalid `crate_type` value", ); } } @@ -515,9 +508,7 @@ pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<c if base.is_empty() { base.extend(attr_types); if base.is_empty() { - base.push(::rustc_codegen_utils::link::default_output_for_target( - session, - )); + base.push(::rustc_codegen_utils::link::default_output_for_target(session)); } else { base.sort(); base.dedup(); @@ -555,7 +546,8 @@ pub fn build_output_filenames( let dirpath = (*odir).as_ref().cloned().unwrap_or_default(); // If a crate name is present, we use it as the link name - let stem = sess.opts + let stem = sess + .opts .crate_name .clone() .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string())) @@ -571,11 +563,8 @@ pub fn build_output_filenames( } Some(ref out_file) => { - let unnamed_output_types = sess.opts - .output_types - .values() - .filter(|a| a.is_none()) - .count(); + let unnamed_output_types = + sess.opts.output_types.values().filter(|a| a.is_none()).count(); let ofile = if unnamed_output_types > 1 { sess.warn( "due to multiple output types requested, the explicitly specified \ @@ -626,11 +615,7 @@ pub struct ReplaceBodyWithLoop<'a, 'b> { impl<'a, 'b> ReplaceBodyWithLoop<'a, 'b> { pub fn new(resolver: &'a mut Resolver<'b>) -> ReplaceBodyWithLoop<'a, 'b> { - ReplaceBodyWithLoop { - within_static_or_const: false, - nested_blocks: None, - resolver, - } + ReplaceBodyWithLoop { within_static_or_const: false, nested_blocks: None, resolver } } fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R { @@ -647,11 +632,11 @@ impl<'a, 'b> ReplaceBodyWithLoop<'a, 'b> { fn involves_impl_trait(ty: &ast::Ty) -> bool { match ty.kind { ast::TyKind::ImplTrait(..) => true, - ast::TyKind::Slice(ref subty) | - ast::TyKind::Array(ref subty, _) | - ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. }) | - ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. }) | - ast::TyKind::Paren(ref subty) => involves_impl_trait(subty), + ast::TyKind::Slice(ref subty) + | ast::TyKind::Array(ref subty, _) + | ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. }) + | ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. }) + | ast::TyKind::Paren(ref subty) => involves_impl_trait(subty), ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()), ast::TyKind::Path(_, ref path) => path.segments.iter().any(|seg| { match seg.args.as_ref().map(|generic_arg| &**generic_arg) { @@ -661,18 +646,17 @@ impl<'a, 'b> ReplaceBodyWithLoop<'a, 'b> { ast::GenericArg::Type(ty) => Some(ty), _ => None, }); - any_involves_impl_trait(types.into_iter()) || - data.constraints.iter().any(|c| { - match c.kind { + any_involves_impl_trait(types.into_iter()) + || data.constraints.iter().any(|c| match c.kind { ast::AssocTyConstraintKind::Bound { .. } => true, - ast::AssocTyConstraintKind::Equality { ref ty } => - involves_impl_trait(ty), - } - }) - }, + ast::AssocTyConstraintKind::Equality { ref ty } => { + involves_impl_trait(ty) + } + }) + } Some(&ast::GenericArgs::Parenthesized(ref data)) => { - any_involves_impl_trait(data.inputs.iter()) || - ReplaceBodyWithLoop::should_ignore_fn(&data.output) + any_involves_impl_trait(data.inputs.iter()) + || ReplaceBodyWithLoop::should_ignore_fn(&data.output) } } }), @@ -691,8 +675,8 @@ impl<'a, 'b> ReplaceBodyWithLoop<'a, 'b> { } fn is_sig_const(sig: &ast::FnSig) -> bool { - sig.header.constness.node == ast::Constness::Const || - ReplaceBodyWithLoop::should_ignore_fn(&sig.decl.output) + sig.header.constness.node == ast::Constness::Const + || ReplaceBodyWithLoop::should_ignore_fn(&sig.decl.output) } } @@ -724,9 +708,11 @@ impl<'a> MutVisitor for ReplaceBodyWithLoop<'a, '_> { } fn visit_block(&mut self, b: &mut P<ast::Block>) { - fn stmt_to_block(rules: ast::BlockCheckMode, - s: Option<ast::Stmt>, - resolver: &mut Resolver<'_>) -> ast::Block { + fn stmt_to_block( + rules: ast::BlockCheckMode, + s: Option<ast::Stmt>, + resolver: &mut Resolver<'_>, + ) -> ast::Block { ast::Block { stmts: s.into_iter().collect(), rules, @@ -755,7 +741,7 @@ impl<'a> MutVisitor for ReplaceBodyWithLoop<'a, '_> { kind: ast::ExprKind::Loop(P(empty_block), None), id: self.resolver.next_node_id(), span: syntax_pos::DUMMY_SP, - attrs: AttrVec::new(), + attrs: AttrVec::new(), }); let loop_stmt = ast::Stmt { @@ -780,10 +766,7 @@ impl<'a> MutVisitor for ReplaceBodyWithLoop<'a, '_> { stmts.extend(new_blocks.into_iter().map(|b| block_to_stmt(b, self.resolver))); } - let mut new_block = ast::Block { - stmts, - ..b - }; + let mut new_block = ast::Block { stmts, ..b }; if let Some(old_blocks) = self.nested_blocks.as_mut() { //push our fresh block onto the cache and yield an empty block with `loop {}` |
