From 64d98f8ee037282c35007b64c2649055c56af1db Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Wed, 17 Apr 2024 14:19:03 +0200 Subject: Merging upstream version 1.68.2+dfsg1. Signed-off-by: Daniel Baumann --- compiler/rustc_driver/README.md | 2 +- compiler/rustc_driver/src/args.rs | 6 +- compiler/rustc_driver/src/lib.rs | 192 +++++++++++++++--------------------- compiler/rustc_driver/src/pretty.rs | 51 ++++------ 4 files changed, 100 insertions(+), 151 deletions(-) (limited to 'compiler/rustc_driver') diff --git a/compiler/rustc_driver/README.md b/compiler/rustc_driver/README.md index 37dc7f6ba..6d7fba36f 100644 --- a/compiler/rustc_driver/README.md +++ b/compiler/rustc_driver/README.md @@ -1,5 +1,5 @@ The `driver` crate is effectively the "main" function for the rust -compiler. It orchestrates the compilation process and "knits together" +compiler. It orchestrates the compilation process and "knits together" the code from the other crates within rustc. This crate itself does not contain any of the "main logic" of the compiler (though it does have some code related to pretty printing or other minor compiler diff --git a/compiler/rustc_driver/src/args.rs b/compiler/rustc_driver/src/args.rs index 01338359f..42c97cc6a 100644 --- a/compiler/rustc_driver/src/args.rs +++ b/compiler/rustc_driver/src/args.rs @@ -25,7 +25,7 @@ pub fn arg_expand_all(at_args: &[String]) -> Vec { Ok(arg) => args.extend(arg), Err(err) => rustc_session::early_error( rustc_session::config::ErrorOutputType::default(), - &format!("Failed to load argument file: {}", err), + &format!("Failed to load argument file: {err}"), ), } } @@ -42,8 +42,8 @@ impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::Utf8Error(None) => write!(fmt, "Utf8 error"), - Error::Utf8Error(Some(path)) => write!(fmt, "Utf8 error in {}", path), - Error::IOError(path, err) => write!(fmt, "IO Error: {}: {}", path, err), + Error::Utf8Error(Some(path)) => write!(fmt, "Utf8 error in {path}"), + Error::IOError(path, err) => write!(fmt, "IO Error: {path}: {err}"), } } } diff --git a/compiler/rustc_driver/src/lib.rs b/compiler/rustc_driver/src/lib.rs index f06ca5a07..f50ad0137 100644 --- a/compiler/rustc_driver/src/lib.rs +++ b/compiler/rustc_driver/src/lib.rs @@ -45,7 +45,6 @@ use rustc_target::json::ToJson; use std::borrow::Cow; use std::cmp::max; -use std::default::Default; use std::env; use std::ffi::OsString; use std::fs; @@ -220,7 +219,6 @@ fn run_compiler( crate_cfg: cfg, crate_check_cfg: check_cfg, input: Input::File(PathBuf::new()), - input_path: None, output_file: ofile, output_dir: odir, file_loader, @@ -232,11 +230,14 @@ fn run_compiler( registry: diagnostics_registry(), }; + if !tracing::dispatcher::has_been_set() { + init_rustc_env_logger_with_backtrace_option(&config.opts.unstable_opts.log_backtrace); + } + match make_input(config.opts.error_format, &matches.free) { Err(reported) => return Err(reported), - Ok(Some((input, input_file_path))) => { + Ok(Some(input)) => { config.input = input; - config.input_path = input_file_path; callbacks.config(&mut config); } @@ -258,14 +259,8 @@ fn run_compiler( describe_lints(compiler.session(), &lint_store, registered_lints); return; } - let should_stop = print_crate_info( - &***compiler.codegen_backend(), - compiler.session(), - None, - compiler.output_dir(), - compiler.output_file(), - compiler.temps_dir(), - ); + let should_stop = + print_crate_info(&***compiler.codegen_backend(), compiler.session(), false); if should_stop == Compilation::Stop { return; @@ -287,18 +282,9 @@ fn run_compiler( interface::run_compiler(config, |compiler| { let sess = compiler.session(); - let should_stop = print_crate_info( - &***compiler.codegen_backend(), - sess, - Some(compiler.input()), - compiler.output_dir(), - compiler.output_file(), - compiler.temps_dir(), - ) - .and_then(|| { - list_metadata(sess, &*compiler.codegen_backend().metadata_loader(), compiler.input()) - }) - .and_then(|| try_process_rlink(sess, compiler)); + let should_stop = print_crate_info(&***compiler.codegen_backend(), sess, true) + .and_then(|| list_metadata(sess, &*compiler.codegen_backend().metadata_loader())) + .and_then(|| try_process_rlink(sess, compiler)); if should_stop == Compilation::Stop { return sess.compile_status(); @@ -310,26 +296,14 @@ fn run_compiler( if let Some(ppm) = &sess.opts.pretty { if ppm.needs_ast_map() { - let expanded_crate = queries.expansion()?.peek().0.clone(); - queries.global_ctxt()?.peek_mut().enter(|tcx| { - pretty::print_after_hir_lowering( - tcx, - compiler.input(), - &*expanded_crate, - *ppm, - compiler.output_file().as_deref(), - ); + let expanded_crate = queries.expansion()?.borrow().0.clone(); + queries.global_ctxt()?.enter(|tcx| { + pretty::print_after_hir_lowering(tcx, &*expanded_crate, *ppm); Ok(()) })?; } else { - let krate = queries.parse()?.take(); - pretty::print_after_parsing( - sess, - compiler.input(), - &krate, - *ppm, - compiler.output_file().as_deref(), - ); + let krate = queries.parse()?.steal(); + pretty::print_after_parsing(sess, &krate, *ppm); } trace!("finished pretty-printing"); return early_exit(); @@ -344,7 +318,8 @@ fn run_compiler( } { - let (_, lint_store) = &*queries.register_plugins()?.peek(); + let plugins = queries.register_plugins()?; + let (_, lint_store) = &*plugins.borrow(); // Lint plugins are registered; now we can process command line flags. if sess.opts.describe_lints { @@ -353,26 +328,22 @@ fn run_compiler( } } - queries.expansion()?; + queries.global_ctxt()?; if callbacks.after_expansion(compiler, queries) == Compilation::Stop { return early_exit(); } - queries.prepare_outputs()?; - if sess.opts.output_types.contains_key(&OutputType::DepInfo) && sess.opts.output_types.len() == 1 { return early_exit(); } - queries.global_ctxt()?; - if sess.opts.unstable_opts.no_analysis { return early_exit(); } - queries.global_ctxt()?.peek_mut().enter(|tcx| { + queries.global_ctxt()?.enter(|tcx| { let result = tcx.analysis(()); if sess.opts.unstable_opts.save_analysis { let crate_name = tcx.crate_name(LOCAL_CRATE); @@ -380,9 +351,9 @@ fn run_compiler( save::process_crate( tcx, crate_name, - compiler.input(), + &sess.io.input, None, - DumpHandler::new(compiler.output_dir().as_deref(), crate_name), + DumpHandler::new(sess.io.output_dir.as_deref(), crate_name), ) }); } @@ -435,7 +406,7 @@ fn make_output(matches: &getopts::Matches) -> (Option, Option) fn make_input( error_format: ErrorOutputType, free_matches: &[String], -) -> Result)>, ErrorGuaranteed> { +) -> Result, ErrorGuaranteed> { if free_matches.len() == 1 { let ifile = &free_matches[0]; if ifile == "-" { @@ -457,12 +428,12 @@ fn make_input( let line = isize::from_str_radix(&line, 10) .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number"); let file_name = FileName::doc_test_source_code(PathBuf::from(path), line); - Ok(Some((Input::Str { name: file_name, input: src }, None))) + Ok(Some(Input::Str { name: file_name, input: src })) } else { - Ok(Some((Input::Str { name: FileName::anon_source_code(&src), input: src }, None))) + Ok(Some(Input::Str { name: FileName::anon_source_code(&src), input: src })) } } else { - Ok(Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile))))) + Ok(Some(Input::File(PathBuf::from(ifile)))) } } else { Ok(None) @@ -487,11 +458,8 @@ impl Compilation { fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) { let upper_cased_code = code.to_ascii_uppercase(); - let normalised = if upper_cased_code.starts_with('E') { - upper_cased_code - } else { - format!("E{0:0>4}", code) - }; + let normalised = + if upper_cased_code.starts_with('E') { upper_cased_code } else { format!("E{code:0>4}") }; match registry.try_find_description(&normalised) { Ok(Some(description)) => { let mut is_in_code_block = false; @@ -514,14 +482,14 @@ fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) { if io::stdout().is_terminal() { show_content_with_pager(&text); } else { - print!("{}", text); + print!("{text}"); } } Ok(None) => { - early_error(output, &format!("no extended information for {}", code)); + early_error(output, &format!("no extended information for {code}")); } Err(InvalidErrorCode) => { - early_error(output, &format!("{} is not a valid error code", code)); + early_error(output, &format!("{code} is not a valid error code")); } } } @@ -553,13 +521,13 @@ fn show_content_with_pager(content: &str) { // If pager fails for whatever reason, we should still print the content // to standard output if fallback_to_println { - print!("{}", content); + print!("{content}"); } } pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation { if sess.opts.unstable_opts.link_only { - if let Input::File(file) = compiler.input() { + if let Input::File(file) = &sess.io.input { // FIXME: #![crate_type] and #![crate_name] support not implemented yet sess.init_crate_types(collect_crate_types(sess, &[])); let outputs = compiler.build_output_filenames(sess, &[]); @@ -600,13 +568,9 @@ pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Comp } } -pub fn list_metadata( - sess: &Session, - metadata_loader: &dyn MetadataLoader, - input: &Input, -) -> Compilation { +pub fn list_metadata(sess: &Session, metadata_loader: &dyn MetadataLoader) -> Compilation { if sess.opts.unstable_opts.ls { - match *input { + match sess.io.input { Input::File(ref ifile) => { let path = &(*ifile); let mut v = Vec::new(); @@ -626,10 +590,7 @@ pub fn list_metadata( fn print_crate_info( codegen_backend: &dyn CodegenBackend, sess: &Session, - input: Option<&Input>, - odir: &Option, - ofile: &Option, - temps_dir: &Option, + parse_attrs: bool, ) -> Compilation { use rustc_session::config::PrintRequest::*; // NativeStaticLibs and LinkArgs are special - printed during linking @@ -638,23 +599,22 @@ fn print_crate_info( return Compilation::Continue; } - let attrs = match input { - None => None, - Some(input) => { - let result = parse_crate_attrs(sess, input); - match result { - Ok(attrs) => Some(attrs), - Err(mut parse_error) => { - parse_error.emit(); - return Compilation::Stop; - } + let attrs = if parse_attrs { + let result = parse_crate_attrs(sess); + match result { + Ok(attrs) => Some(attrs), + Err(mut parse_error) => { + parse_error.emit(); + return Compilation::Stop; } } + } else { + None }; for req in &sess.opts.prints { match *req { TargetList => { - let mut targets = rustc_target::spec::TARGETS.iter().copied().collect::>(); + let mut targets = rustc_target::spec::TARGETS.to_vec(); targets.sort_unstable(); println!("{}", targets.join("\n")); } @@ -664,16 +624,11 @@ fn print_crate_info( println!("{}", serde_json::to_string_pretty(&sess.target.to_json()).unwrap()); } FileNames | CrateName => { - let input = input.unwrap_or_else(|| { - early_error(ErrorOutputType::default(), "no input file provided") - }); let attrs = attrs.as_ref().unwrap(); - let t_outputs = rustc_interface::util::build_output_filenames( - input, odir, ofile, temps_dir, attrs, sess, - ); - let id = rustc_session::output::find_crate_name(sess, attrs, input); + let t_outputs = rustc_interface::util::build_output_filenames(attrs, sess); + let id = rustc_session::output::find_crate_name(sess, attrs); if *req == PrintRequest::CrateName { - println!("{}", id); + println!("{id}"); continue; } let crate_types = collect_crate_types(sess, attrs); @@ -705,7 +660,7 @@ fn print_crate_info( } if let Some(value) = value { - Some(format!("{}=\"{}\"", name, value)) + Some(format!("{name}=\"{value}\"")) } else { Some(name.to_string()) } @@ -714,7 +669,7 @@ fn print_crate_info( cfgs.sort(); for cfg in cfgs { - println!("{}", cfg); + println!("{cfg}"); } } CallingConventions => { @@ -740,7 +695,7 @@ fn print_crate_info( let stable = sess.target.options.supported_split_debuginfo.contains(split); let unstable_ok = sess.unstable_options(); if stable || unstable_ok { - println!("{}", split); + println!("{split}"); } } } @@ -777,14 +732,14 @@ pub fn version_at_macro_invocation( ) { let verbose = matches.opt_present("verbose"); - println!("{} {}", binary, version); + println!("{binary} {version}"); if verbose { - println!("binary: {}", binary); - println!("commit-hash: {}", commit_hash); - println!("commit-date: {}", commit_date); + println!("binary: {binary}"); + println!("commit-hash: {commit_hash}"); + println!("commit-date: {commit_date}"); println!("host: {}", config::host_triple()); - println!("release: {}", release); + println!("release: {release}"); let debug_flags = matches.opt_strs("Z"); let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend=")); @@ -1038,7 +993,7 @@ pub fn handle_options(args: &[String]) -> Option { .map(|&(name, ..)| ('C', name)) .chain(Z_OPTIONS.iter().map(|&(name, ..)| ('Z', name))) .find(|&(_, name)| *opt == name.replace('_', "-")) - .map(|(flag, _)| format!("{}. Did you mean `-{} {}`?", e, flag, opt)), + .map(|(flag, _)| format!("{e}. Did you mean `-{flag} {opt}`?")), _ => None, }; early_error(ErrorOutputType::default(), &msg.unwrap_or_else(|| e.to_string())); @@ -1107,8 +1062,8 @@ pub fn handle_options(args: &[String]) -> Option { Some(matches) } -fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::AttrVec> { - match input { +fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> { + match &sess.io.input { Input::File(ifile) => rustc_parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess), Input::Str { name, input } => rustc_parse::parse_crate_attrs_from_source_str( name.clone(), @@ -1149,7 +1104,7 @@ fn extra_compiler_flags() -> Option<(Vec, bool)> { } else { result.push(a.to_string()); match ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.iter().find(|s| option == **s) { - Some(s) => result.push(format!("{}=[REDACTED]", s)), + Some(s) => result.push(format!("{s}=[REDACTED]")), None => result.push(content), } } @@ -1200,10 +1155,13 @@ static DEFAULT_HOOK: LazyLock) + Sync + Send + }; // Invoke the default handler, which prints the actual panic message and optionally a backtrace - (*DEFAULT_HOOK)(info); + // Don't do this for delayed bugs, which already emit their own more useful backtrace. + if !info.payload().is::() { + (*DEFAULT_HOOK)(info); - // Separate the output with an empty line - eprintln!(); + // Separate the output with an empty line + eprintln!(); + } // Print the ICE message report_ice(info, BUG_REPORT_URL); @@ -1235,14 +1193,16 @@ pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) { // a .span_bug or .bug call has already printed what // it wants to print. - if !info.payload().is::() { + if !info.payload().is::() + && !info.payload().is::() + { let mut d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic"); handler.emit_diagnostic(&mut d); } let mut xs: Vec> = vec![ "the compiler unexpectedly panicked. this is a bug.".into(), - format!("we would appreciate a bug report: {}", bug_report_url).into(), + format!("we would appreciate a bug report: {bug_report_url}").into(), format!( "rustc {} running on {}", util::version_str!().unwrap_or("unknown_version"), @@ -1298,7 +1258,14 @@ pub fn install_ice_hook() { /// This allows tools to enable rust logging without having to magically match rustc's /// tracing crate version. pub fn init_rustc_env_logger() { - if let Err(error) = rustc_log::init_rustc_env_logger() { + init_rustc_env_logger_with_backtrace_option(&None); +} + +/// This allows tools to enable rust logging without having to magically match rustc's +/// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to +/// choose a target module you wish to show backtraces along with its logging. +pub fn init_rustc_env_logger_with_backtrace_option(backtrace_target: &Option) { + if let Err(error) = rustc_log::init_rustc_env_logger_with_backtrace_option(backtrace_target) { early_error(ErrorOutputType::default(), &error.to_string()); } } @@ -1364,7 +1331,6 @@ mod signal_handler { pub fn main() -> ! { let start_time = Instant::now(); let start_rss = get_resident_set_size(); - init_rustc_env_logger(); signal_handler::install(); let mut callbacks = TimePassesCallbacks::default(); install_ice_hook(); @@ -1375,7 +1341,7 @@ pub fn main() -> ! { arg.into_string().unwrap_or_else(|arg| { early_error( ErrorOutputType::default(), - &format!("argument {} is not valid Unicode: {:?}", i, arg), + &format!("argument {i} is not valid Unicode: {arg:?}"), ) }) }) diff --git a/compiler/rustc_driver/src/pretty.rs b/compiler/rustc_driver/src/pretty.rs index f9b1316d2..ae3ac8625 100644 --- a/compiler/rustc_driver/src/pretty.rs +++ b/compiler/rustc_driver/src/pretty.rs @@ -9,14 +9,13 @@ use rustc_hir_pretty as pprust_hir; use rustc_middle::hir::map as hir_map; use rustc_middle::mir::{write_mir_graphviz, write_mir_pretty}; use rustc_middle::ty::{self, TyCtxt}; -use rustc_session::config::{Input, PpAstTreeMode, PpHirMode, PpMode, PpSourceMode}; +use rustc_session::config::{PpAstTreeMode, PpHirMode, PpMode, PpSourceMode}; use rustc_session::Session; use rustc_span::symbol::Ident; use rustc_span::FileName; use std::cell::Cell; use std::fmt::Write; -use std::path::Path; pub use self::PpMode::*; pub use self::PpSourceMode::*; @@ -345,8 +344,8 @@ impl<'tcx> pprust_hir::PpAnn for TypedAnnotation<'tcx> { } } -fn get_source(input: &Input, sess: &Session) -> (String, FileName) { - let src_name = input.source_name(); +fn get_source(sess: &Session) -> (String, FileName) { + let src_name = sess.io.input.source_name(); let src = String::clone( sess.source_map() .get_source_file(&src_name) @@ -358,9 +357,9 @@ fn get_source(input: &Input, sess: &Session) -> (String, FileName) { (src, src_name) } -fn write_or_print(out: &str, ofile: Option<&Path>, sess: &Session) { - match ofile { - None => print!("{}", out), +fn write_or_print(out: &str, sess: &Session) { + match &sess.io.output_file { + None => print!("{out}"), Some(p) => { if let Err(e) = std::fs::write(p, out) { sess.emit_fatal(UnprettyDumpFail { @@ -372,14 +371,8 @@ fn write_or_print(out: &str, ofile: Option<&Path>, sess: &Session) { } } -pub fn print_after_parsing( - sess: &Session, - input: &Input, - krate: &ast::Crate, - ppm: PpMode, - ofile: Option<&Path>, -) { - let (src, src_name) = get_source(input, sess); +pub fn print_after_parsing(sess: &Session, krate: &ast::Crate, ppm: PpMode) { + let (src, src_name) = get_source(sess); let out = match ppm { Source(s) => { @@ -402,27 +395,21 @@ pub fn print_after_parsing( } AstTree(PpAstTreeMode::Normal) => { debug!("pretty printing AST tree"); - format!("{:#?}", krate) + format!("{krate:#?}") } _ => unreachable!(), }; - write_or_print(&out, ofile, sess); + write_or_print(&out, sess); } -pub fn print_after_hir_lowering<'tcx>( - tcx: TyCtxt<'tcx>, - input: &Input, - krate: &ast::Crate, - ppm: PpMode, - ofile: Option<&Path>, -) { +pub fn print_after_hir_lowering<'tcx>(tcx: TyCtxt<'tcx>, krate: &ast::Crate, ppm: PpMode) { if ppm.needs_analysis() { - abort_on_err(print_with_analysis(tcx, ppm, ofile), tcx.sess); + abort_on_err(print_with_analysis(tcx, ppm), tcx.sess); return; } - let (src, src_name) = get_source(input, tcx.sess); + let (src, src_name) = get_source(tcx.sess); let out = match ppm { Source(s) => { @@ -446,7 +433,7 @@ pub fn print_after_hir_lowering<'tcx>( AstTree(PpAstTreeMode::Expanded) => { debug!("pretty-printing expanded AST"); - format!("{:#?}", krate) + format!("{krate:#?}") } Hir(s) => call_with_pp_support_hir(&s, tcx, move |annotation, hir_map| { @@ -474,18 +461,14 @@ pub fn print_after_hir_lowering<'tcx>( _ => unreachable!(), }; - write_or_print(&out, ofile, tcx.sess); + write_or_print(&out, tcx.sess); } // In an ideal world, this would be a public function called by the driver after // analysis is performed. However, we want to call `phase_3_run_analysis_passes` // with a different callback than the standard driver, so that isn't easy. // Instead, we call that function ourselves. -fn print_with_analysis( - tcx: TyCtxt<'_>, - ppm: PpMode, - ofile: Option<&Path>, -) -> Result<(), ErrorGuaranteed> { +fn print_with_analysis(tcx: TyCtxt<'_>, ppm: PpMode) -> Result<(), ErrorGuaranteed> { tcx.analysis(())?; let out = match ppm { Mir => { @@ -518,7 +501,7 @@ fn print_with_analysis( _ => unreachable!(), }; - write_or_print(&out, ofile, tcx.sess); + write_or_print(&out, tcx.sess); Ok(()) } -- cgit v1.2.3