5 //! This API is completely unstable and subject to change.
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
10 #![recursion_limit = "256"]
11 #![cfg_attr(not(bootstrap), allow(rustc::potential_query_instability))]
16 pub extern crate rustc_plugin_impl as plugin;
19 use rustc_codegen_ssa::{traits::CodegenBackend, CodegenResults};
20 use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
21 use rustc_data_structures::sync::SeqCst;
22 use rustc_errors::registry::{InvalidErrorCode, Registry};
23 use rustc_errors::{ErrorReported, PResult};
24 use rustc_feature::find_gated_cfg;
25 use rustc_interface::util::{self, collect_crate_types, get_codegen_backend};
26 use rustc_interface::{interface, Queries};
27 use rustc_lint::LintStore;
28 use rustc_metadata::locator;
29 use rustc_save_analysis as save;
30 use rustc_save_analysis::DumpHandler;
31 use rustc_serialize::json::{self, ToJson};
32 use rustc_session::config::{nightly_options, CG_OPTIONS, DB_OPTIONS};
33 use rustc_session::config::{ErrorOutputType, Input, OutputType, PrintRequest, TrimmedDefPaths};
34 use rustc_session::cstore::MetadataLoader;
35 use rustc_session::getopts;
36 use rustc_session::lint::{Lint, LintId};
37 use rustc_session::{config, DiagnosticOutput, Session};
38 use rustc_session::{early_error, early_error_no_abort, early_warn};
39 use rustc_span::source_map::{FileLoader, FileName};
40 use rustc_span::symbol::sym;
44 use std::default::Default;
46 use std::ffi::OsString;
48 use std::io::{self, Read, Write};
49 use std::lazy::SyncLazy;
50 use std::panic::{self, catch_unwind};
51 use std::path::PathBuf;
52 use std::process::{self, Command, Stdio};
54 use std::time::Instant;
59 /// Exit status code used for successful compilation and help output.
60 pub const EXIT_SUCCESS: i32 = 0;
62 /// Exit status code used for compilation failures and invalid flags.
63 pub const EXIT_FAILURE: i32 = 1;
65 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
66 ?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
68 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
70 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
72 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
74 pub fn abort_on_err<T>(result: Result<T, ErrorReported>, sess: &Session) -> T {
77 sess.abort_if_errors();
78 panic!("error reported but abort_if_errors didn't abort???");
85 /// Called before creating the compiler instance
86 fn config(&mut self, _config: &mut interface::Config) {}
87 /// Called after parsing. Return value instructs the compiler whether to
88 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
89 fn after_parsing<'tcx>(
91 _compiler: &interface::Compiler,
92 _queries: &'tcx Queries<'tcx>,
96 /// Called after expansion. Return value instructs the compiler whether to
97 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
98 fn after_expansion<'tcx>(
100 _compiler: &interface::Compiler,
101 _queries: &'tcx Queries<'tcx>,
103 Compilation::Continue
105 /// Called after analysis. Return value instructs the compiler whether to
106 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
107 fn after_analysis<'tcx>(
109 _compiler: &interface::Compiler,
110 _queries: &'tcx Queries<'tcx>,
112 Compilation::Continue
117 pub struct TimePassesCallbacks {
121 impl Callbacks for TimePassesCallbacks {
122 fn config(&mut self, config: &mut interface::Config) {
123 // If a --prints=... option has been given, we don't print the "total"
124 // time because it will mess up the --prints output. See #64339.
125 self.time_passes = config.opts.prints.is_empty()
126 && (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time);
127 config.opts.trimmed_def_paths = TrimmedDefPaths::GoodPath;
131 pub fn diagnostics_registry() -> Registry {
132 Registry::new(rustc_error_codes::DIAGNOSTICS)
135 /// This is the primary entry point for rustc.
136 pub struct RunCompiler<'a, 'b> {
137 at_args: &'a [String],
138 callbacks: &'b mut (dyn Callbacks + Send),
139 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
140 emitter: Option<Box<dyn Write + Send>>,
141 make_codegen_backend:
142 Option<Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>>,
145 impl<'a, 'b> RunCompiler<'a, 'b> {
146 pub fn new(at_args: &'a [String], callbacks: &'b mut (dyn Callbacks + Send)) -> Self {
147 Self { at_args, callbacks, file_loader: None, emitter: None, make_codegen_backend: None }
150 /// Set a custom codegen backend.
153 pub fn set_make_codegen_backend(
155 make_codegen_backend: Option<
156 Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
159 self.make_codegen_backend = make_codegen_backend;
163 /// Emit diagnostics to the specified location.
166 pub fn set_emitter(&mut self, emitter: Option<Box<dyn Write + Send>>) -> &mut Self {
167 self.emitter = emitter;
171 /// Load files from sources other than the file system.
174 pub fn set_file_loader(
176 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
178 self.file_loader = file_loader;
182 /// Parse args and run the compiler.
183 pub fn run(self) -> interface::Result<()> {
189 self.make_codegen_backend,
195 callbacks: &mut (dyn Callbacks + Send),
196 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
197 emitter: Option<Box<dyn Write + Send>>,
198 make_codegen_backend: Option<
199 Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
201 ) -> interface::Result<()> {
202 let args = args::arg_expand_all(at_args);
204 let diagnostic_output = emitter.map_or(DiagnosticOutput::Default, DiagnosticOutput::Raw);
205 let matches = match handle_options(&args) {
206 Some(matches) => matches,
207 None => return Ok(()),
210 let sopts = config::build_session_options(&matches);
212 if let Some(ref code) = matches.opt_str("explain") {
213 handle_explain(diagnostics_registry(), code, sopts.error_format);
217 let cfg = interface::parse_cfgspecs(matches.opt_strs("cfg"));
218 let (odir, ofile) = make_output(&matches);
219 let mut config = interface::Config {
222 input: Input::File(PathBuf::new()),
229 lint_caps: Default::default(),
230 parse_sess_created: None,
231 register_lints: None,
232 override_queries: None,
233 make_codegen_backend,
234 registry: diagnostics_registry(),
237 match make_input(config.opts.error_format, &matches.free) {
238 Err(ErrorReported) => return Err(ErrorReported),
239 Ok(Some((input, input_file_path))) => {
240 config.input = input;
241 config.input_path = input_file_path;
243 callbacks.config(&mut config);
245 Ok(None) => match matches.free.len() {
247 callbacks.config(&mut config);
248 interface::run_compiler(config, |compiler| {
249 let sopts = &compiler.session().opts;
250 if sopts.describe_lints {
251 let mut lint_store = rustc_lint::new_lint_store(
252 sopts.debugging_opts.no_interleave_lints,
253 compiler.session().unstable_options(),
255 let registered_lints =
256 if let Some(register_lints) = compiler.register_lints() {
257 register_lints(compiler.session(), &mut lint_store);
262 describe_lints(compiler.session(), &lint_store, registered_lints);
265 let should_stop = RustcDefaultCalls::print_crate_info(
266 &***compiler.codegen_backend(),
269 compiler.output_dir(),
270 compiler.output_file(),
273 if should_stop == Compilation::Stop {
276 early_error(sopts.error_format, "no input filename given")
280 1 => panic!("make_input should have provided valid inputs"),
282 config.opts.error_format,
284 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
285 matches.free[0], matches.free[1],
291 interface::run_compiler(config, |compiler| {
292 let sess = compiler.session();
293 let should_stop = RustcDefaultCalls::print_crate_info(
294 &***compiler.codegen_backend(),
296 Some(compiler.input()),
297 compiler.output_dir(),
298 compiler.output_file(),
301 RustcDefaultCalls::list_metadata(
303 &*compiler.codegen_backend().metadata_loader(),
307 .and_then(|| RustcDefaultCalls::try_process_rlink(sess, compiler));
309 if should_stop == Compilation::Stop {
310 return sess.compile_status();
313 let linker = compiler.enter(|queries| {
314 let early_exit = || sess.compile_status().map(|_| None);
317 if let Some(ppm) = &sess.opts.pretty {
318 if ppm.needs_ast_map() {
319 let expanded_crate = queries.expansion()?.peek().0.clone();
320 queries.global_ctxt()?.peek_mut().enter(|tcx| {
321 pretty::print_after_hir_lowering(
326 compiler.output_file().as_ref().map(|p| &**p),
331 let krate = queries.parse()?.take();
332 pretty::print_after_parsing(
337 compiler.output_file().as_ref().map(|p| &**p),
340 trace!("finished pretty-printing");
344 if callbacks.after_parsing(compiler, queries) == Compilation::Stop {
348 if sess.opts.debugging_opts.parse_only
349 || sess.opts.debugging_opts.show_span.is_some()
350 || sess.opts.debugging_opts.ast_json_noexpand
356 let (_, lint_store) = &*queries.register_plugins()?.peek();
358 // Lint plugins are registered; now we can process command line flags.
359 if sess.opts.describe_lints {
360 describe_lints(sess, lint_store, true);
365 queries.expansion()?;
366 if callbacks.after_expansion(compiler, queries) == Compilation::Stop {
370 queries.prepare_outputs()?;
372 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
373 && sess.opts.output_types.len() == 1
378 queries.global_ctxt()?;
380 if sess.opts.debugging_opts.no_analysis || sess.opts.debugging_opts.ast_json {
384 queries.global_ctxt()?.peek_mut().enter(|tcx| {
385 let result = tcx.analysis(());
386 if sess.opts.debugging_opts.save_analysis {
387 let crate_name = queries.crate_name()?.peek().clone();
388 sess.time("save_analysis", || {
395 compiler.output_dir().as_ref().map(|p| &**p),
404 if callbacks.after_analysis(compiler, queries) == Compilation::Stop {
408 queries.ongoing_codegen()?;
410 if sess.opts.debugging_opts.print_type_sizes {
411 sess.code_stats.print_type_sizes();
414 let linker = queries.linker()?;
418 if let Some(linker) = linker {
419 let _timer = sess.timer("link");
423 if sess.opts.debugging_opts.perf_stats {
424 sess.print_perf_stats();
427 if sess.opts.debugging_opts.print_fuel.is_some() {
429 "Fuel used by {}: {}",
430 sess.opts.debugging_opts.print_fuel.as_ref().unwrap(),
431 sess.print_fuel.load(SeqCst)
440 pub fn set_sigpipe_handler() {
442 // Set the SIGPIPE signal handler, so that an EPIPE
443 // will cause rustc to terminate, as expected.
444 assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
449 pub fn set_sigpipe_handler() {}
451 // Extract output directory and file from matches.
452 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
453 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
454 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
458 // Extract input (string or file and optional path) from matches.
460 error_format: ErrorOutputType,
461 free_matches: &[String],
462 ) -> Result<Option<(Input, Option<PathBuf>)>, ErrorReported> {
463 if free_matches.len() == 1 {
464 let ifile = &free_matches[0];
466 let mut src = String::new();
467 if io::stdin().read_to_string(&mut src).is_err() {
468 // Immediately stop compilation if there was an issue reading
469 // the input (for example if the input stream is not UTF-8).
470 early_error_no_abort(
472 "couldn't read from stdin, as it did not contain valid UTF-8",
474 return Err(ErrorReported);
476 if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
477 let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
478 "when UNSTABLE_RUSTDOC_TEST_PATH is set \
479 UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
481 let line = isize::from_str_radix(&line, 10)
482 .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
483 let file_name = FileName::doc_test_source_code(PathBuf::from(path), line);
484 Ok(Some((Input::Str { name: file_name, input: src }, None)))
486 Ok(Some((Input::Str { name: FileName::anon_source_code(&src), input: src }, None)))
489 Ok(Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)))))
496 /// Whether to stop or continue compilation.
497 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
498 pub enum Compilation {
504 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
506 Compilation::Stop => Compilation::Stop,
507 Compilation::Continue => next(),
512 /// CompilerCalls instance for a regular rustc build.
513 #[derive(Copy, Clone)]
514 pub struct RustcDefaultCalls;
516 fn stdout_isatty() -> bool {
517 atty::is(atty::Stream::Stdout)
520 fn stderr_isatty() -> bool {
521 atty::is(atty::Stream::Stderr)
524 fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
525 let upper_cased_code = code.to_ascii_uppercase();
526 let normalised = if upper_cased_code.starts_with('E') {
529 format!("E{0:0>4}", code)
531 match registry.try_find_description(&normalised) {
532 Ok(Some(description)) => {
533 let mut is_in_code_block = false;
534 let mut text = String::new();
535 // Slice off the leading newline and print.
536 for line in description.lines() {
538 line.find(|c: char| !c.is_whitespace()).unwrap_or_else(|| line.len());
539 let dedented_line = &line[indent_level..];
540 if dedented_line.starts_with("```") {
541 is_in_code_block = !is_in_code_block;
542 text.push_str(&line[..(indent_level + 3)]);
543 } else if is_in_code_block && dedented_line.starts_with("# ") {
551 show_content_with_pager(&text);
557 early_error(output, &format!("no extended information for {}", code));
559 Err(InvalidErrorCode) => {
560 early_error(output, &format!("{} is not a valid error code", code));
565 fn show_content_with_pager(content: &str) {
566 let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
567 if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
570 let mut fallback_to_println = false;
572 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
574 if let Some(pipe) = pager.stdin.as_mut() {
575 if pipe.write_all(content.as_bytes()).is_err() {
576 fallback_to_println = true;
580 if pager.wait().is_err() {
581 fallback_to_println = true;
585 fallback_to_println = true;
589 // If pager fails for whatever reason, we should still print the content
590 // to standard output
591 if fallback_to_println {
592 print!("{}", content);
596 impl RustcDefaultCalls {
597 pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation {
598 if sess.opts.debugging_opts.link_only {
599 if let Input::File(file) = compiler.input() {
600 // FIXME: #![crate_type] and #![crate_name] support not implemented yet
601 sess.init_crate_types(collect_crate_types(sess, &[]));
602 let outputs = compiler.build_output_filenames(sess, &[]);
603 let rlink_data = fs::read_to_string(file).unwrap_or_else(|err| {
604 sess.fatal(&format!("failed to read rlink file: {}", err));
606 let codegen_results: CodegenResults =
607 json::decode(&rlink_data).unwrap_or_else(|err| {
608 sess.fatal(&format!("failed to decode rlink: {}", err));
610 let result = compiler.codegen_backend().link(sess, codegen_results, &outputs);
611 abort_on_err(result, sess);
613 sess.fatal("rlink must be a file")
617 Compilation::Continue
621 pub fn list_metadata(
623 metadata_loader: &dyn MetadataLoader,
626 if sess.opts.debugging_opts.ls {
628 Input::File(ref ifile) => {
629 let path = &(*ifile);
630 let mut v = Vec::new();
631 locator::list_file_metadata(&sess.target, path, metadata_loader, &mut v)
633 println!("{}", String::from_utf8(v).unwrap());
635 Input::Str { .. } => {
636 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
639 return Compilation::Stop;
642 Compilation::Continue
646 codegen_backend: &dyn CodegenBackend,
648 input: Option<&Input>,
649 odir: &Option<PathBuf>,
650 ofile: &Option<PathBuf>,
652 use rustc_session::config::PrintRequest::*;
653 // PrintRequest::NativeStaticLibs is special - printed during linking
654 // (empty iterator returns true)
655 if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
656 return Compilation::Continue;
659 let attrs = match input {
662 let result = parse_crate_attrs(sess, input);
664 Ok(attrs) => Some(attrs),
665 Err(mut parse_error) => {
667 return Compilation::Stop;
672 for req in &sess.opts.prints {
676 rustc_target::spec::TARGETS.iter().copied().collect::<Vec<_>>();
677 targets.sort_unstable();
678 println!("{}", targets.join("\n"));
680 Sysroot => println!("{}", sess.sysroot.display()),
681 TargetLibdir => println!("{}", sess.target_tlib_path.dir.display()),
682 TargetSpec => println!("{}", sess.target.to_json().pretty()),
683 FileNames | CrateName => {
684 let input = input.unwrap_or_else(|| {
685 early_error(ErrorOutputType::default(), "no input file provided")
687 let attrs = attrs.as_ref().unwrap();
688 let t_outputs = rustc_interface::util::build_output_filenames(
689 input, odir, ofile, attrs, sess,
691 let id = rustc_session::output::find_crate_name(sess, attrs, input);
692 if *req == PrintRequest::CrateName {
696 let crate_types = collect_crate_types(sess, attrs);
697 for &style in &crate_types {
699 rustc_session::output::filename_for_input(sess, style, &id, &t_outputs);
700 println!("{}", fname.file_name().unwrap().to_string_lossy());
708 .filter_map(|&(name, value)| {
709 // Note that crt-static is a specially recognized cfg
710 // directive that's printed out here as part of
711 // rust-lang/rust#37406, but in general the
712 // `target_feature` cfg is gated under
713 // rust-lang/rust#29717. For now this is just
714 // specifically allowing the crt-static cfg and that's
715 // it, this is intended to get into Cargo and then go
716 // through to build scripts.
717 if (name != sym::target_feature || value != Some(sym::crt_dash_static))
718 && !sess.is_nightly_build()
719 && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
724 if let Some(value) = value {
725 Some(format!("{}=\"{}\"", name, value))
727 Some(name.to_string())
730 .collect::<Vec<String>>();
737 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
738 codegen_backend.print(*req, sess);
740 // Any output here interferes with Cargo's parsing of other printed output
741 PrintRequest::NativeStaticLibs => {}
748 /// Prints version information
749 pub fn version(binary: &str, matches: &getopts::Matches) {
750 let verbose = matches.opt_present("verbose");
752 println!("{} {}", binary, util::version_str().unwrap_or("unknown version"));
755 fn unw(x: Option<&str>) -> &str {
756 x.unwrap_or("unknown")
758 println!("binary: {}", binary);
759 println!("commit-hash: {}", unw(util::commit_hash_str()));
760 println!("commit-date: {}", unw(util::commit_date_str()));
761 println!("host: {}", config::host_triple());
762 println!("release: {}", unw(util::release_str()));
764 let debug_flags = matches.opt_strs("Z");
765 let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
766 get_codegen_backend(&None, backend_name).print_version();
770 fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
771 let groups = if verbose { config::rustc_optgroups() } else { config::rustc_short_optgroups() };
772 let mut options = getopts::Options::new();
773 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
774 (option.apply)(&mut options);
776 let message = "Usage: rustc [OPTIONS] INPUT";
777 let nightly_help = if nightly_build {
778 "\n -Z help Print unstable compiler options"
782 let verbose_help = if verbose {
785 "\n --help -v Print the full set of options rustc accepts"
787 let at_path = if verbose {
788 " @path Read newline separated options from `path`\n"
793 "{options}{at_path}\nAdditional help:
794 -C help Print codegen options
796 Print 'lint' options and default settings{nightly}{verbose}\n",
797 options = options.usage(message),
799 nightly = nightly_help,
800 verbose = verbose_help
804 fn print_wall_help() {
807 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
808 default. Use `rustc -W help` to see all available lints. It's more common to put
809 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
810 the command line flag directly.
815 /// Write to stdout lint command options, together with a list of all available lints
816 pub fn describe_lints(sess: &Session, lint_store: &LintStore, loaded_plugins: bool) {
819 Available lint options:
820 -W <foo> Warn about <foo>
824 -F <foo> Forbid <foo> \
825 (deny <foo> and all attempts to override)
830 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
831 // The sort doesn't case-fold but it's doubtful we care.
832 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
837 lints: Vec<(&'static str, Vec<LintId>, bool)>,
838 ) -> Vec<(&'static str, Vec<LintId>)> {
839 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
840 lints.sort_by_key(|l| l.0);
844 let (plugin, builtin): (Vec<_>, _) =
845 lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_plugin);
846 let plugin = sort_lints(sess, plugin);
847 let builtin = sort_lints(sess, builtin);
849 let (plugin_groups, builtin_groups): (Vec<_>, _) =
850 lint_store.get_lint_groups().partition(|&(.., p)| p);
851 let plugin_groups = sort_lint_groups(plugin_groups);
852 let builtin_groups = sort_lint_groups(builtin_groups);
855 plugin.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
856 let padded = |x: &str| {
857 let mut s = " ".repeat(max_name_len - x.chars().count());
862 println!("Lint checks provided by rustc:\n");
863 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
864 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
866 let print_lints = |lints: Vec<&Lint>| {
868 let name = lint.name_lower().replace("_", "-");
872 lint.default_level(sess.edition()).as_str(),
879 print_lints(builtin);
881 let max_name_len = max(
885 .chain(&builtin_groups)
886 .map(|&(s, _)| s.chars().count())
891 let padded = |x: &str| {
892 let mut s = " ".repeat(max_name_len - x.chars().count());
897 println!("Lint groups provided by rustc:\n");
898 println!(" {} sub-lints", padded("name"));
899 println!(" {} ---------", padded("----"));
900 println!(" {} all lints that are set to issue warnings", padded("warnings"));
902 let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>| {
903 for (name, to) in lints {
904 let name = name.to_lowercase().replace("_", "-");
907 .map(|x| x.to_string().replace("_", "-"))
908 .collect::<Vec<String>>()
910 println!(" {} {}", padded(&name), desc);
915 print_lint_groups(builtin_groups);
917 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
918 (false, 0, _) | (false, _, 0) => {
919 println!("Lint tools like Clippy can provide additional lints and lint groups.");
921 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
922 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
925 println!("Lint checks provided by plugins loaded by this crate:\n");
929 println!("Lint groups provided by plugins loaded by this crate:\n");
930 print_lint_groups(plugin_groups);
936 fn describe_debug_flags() {
937 println!("\nAvailable options:\n");
938 print_flag_list("-Z", config::DB_OPTIONS);
941 fn describe_codegen_flags() {
942 println!("\nAvailable codegen options:\n");
943 print_flag_list("-C", config::CG_OPTIONS);
946 fn print_flag_list<T>(
948 flag_list: &[(&'static str, T, &'static str, &'static str)],
950 let max_len = flag_list.iter().map(|&(name, _, _, _)| name.chars().count()).max().unwrap_or(0);
952 for &(name, _, _, desc) in flag_list {
954 " {} {:>width$}=val -- {}",
956 name.replace("_", "-"),
963 /// Process command line options. Emits messages as appropriate. If compilation
964 /// should continue, returns a getopts::Matches object parsed from args,
965 /// otherwise returns `None`.
967 /// The compiler's handling of options is a little complicated as it ties into
968 /// our stability story. The current intention of each compiler option is to
969 /// have one of two modes:
971 /// 1. An option is stable and can be used everywhere.
972 /// 2. An option is unstable, and can only be used on nightly.
974 /// Like unstable library and language features, however, unstable options have
975 /// always required a form of "opt in" to indicate that you're using them. This
976 /// provides the easy ability to scan a code base to check to see if anything
977 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
979 /// All options behind `-Z` are considered unstable by default. Other top-level
980 /// options can also be considered unstable, and they were unlocked through the
981 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
982 /// instability in both cases, though.
984 /// So with all that in mind, the comments below have some more detail about the
985 /// contortions done here to get things to work out correctly.
986 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
987 // Throw away the first argument, the name of the binary
988 let args = &args[1..];
991 // user did not write `-v` nor `-Z unstable-options`, so do not
992 // include that extra information.
994 rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build();
995 usage(false, false, nightly_build);
999 // Parse with *all* options defined in the compiler, we don't worry about
1000 // option stability here we just want to parse as much as possible.
1001 let mut options = getopts::Options::new();
1002 for option in config::rustc_optgroups() {
1003 (option.apply)(&mut options);
1005 let matches = options.parse(args).unwrap_or_else(|e| {
1007 getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1009 .map(|&(name, ..)| ('C', name))
1010 .chain(DB_OPTIONS.iter().map(|&(name, ..)| ('Z', name)))
1011 .find(|&(_, name)| *opt == name.replace("_", "-"))
1012 .map(|(flag, _)| format!("{}. Did you mean `-{} {}`?", e, flag, opt)),
1015 early_error(ErrorOutputType::default(), &msg.unwrap_or_else(|| e.to_string()));
1018 // For all options we just parsed, we check a few aspects:
1020 // * If the option is stable, we're all good
1021 // * If the option wasn't passed, we're all good
1022 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1023 // ourselves), then we require the `-Z unstable-options` flag to unlock
1024 // this option that was passed.
1025 // * If we're a nightly compiler, then unstable options are now unlocked, so
1026 // we're good to go.
1027 // * Otherwise, if we're an unstable option then we generate an error
1028 // (unstable option being used on stable)
1029 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1031 if matches.opt_present("h") || matches.opt_present("help") {
1032 // Only show unstable options in --help if we accept unstable options.
1033 let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1034 let nightly_build = nightly_options::match_is_nightly_build(&matches);
1035 usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1039 // Handle the special case of -Wall.
1040 let wall = matches.opt_strs("W");
1041 if wall.iter().any(|x| *x == "all") {
1046 // Don't handle -W help here, because we might first load plugins.
1047 let debug_flags = matches.opt_strs("Z");
1048 if debug_flags.iter().any(|x| *x == "help") {
1049 describe_debug_flags();
1053 let cg_flags = matches.opt_strs("C");
1055 if cg_flags.iter().any(|x| *x == "help") {
1056 describe_codegen_flags();
1060 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1062 ErrorOutputType::default(),
1063 "the --no-stack-check flag is deprecated and does nothing",
1067 if cg_flags.iter().any(|x| *x == "passes=list") {
1068 let backend_name = debug_flags.iter().find_map(|x| {
1069 if x.starts_with("codegen-backend=") {
1070 Some(&x["codegen-backends=".len()..])
1075 get_codegen_backend(&None, backend_name).print_passes();
1079 if matches.opt_present("version") {
1080 version("rustc", &matches);
1087 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1089 Input::File(ifile) => rustc_parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess),
1090 Input::Str { name, input } => rustc_parse::parse_crate_attrs_from_source_str(
1098 /// Gets a list of extra command-line flags provided by the user, as strings.
1100 /// This function is used during ICEs to show more information useful for
1101 /// debugging, since some ICEs only happens with non-default compiler flags
1102 /// (and the users don't always report them).
1103 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1104 let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1106 // Avoid printing help because of empty args. This can suggest the compiler
1107 // itself is not the program root (consider RLS).
1112 let matches = handle_options(&args)?;
1113 let mut result = Vec::new();
1114 let mut excluded_cargo_defaults = false;
1115 for flag in ICE_REPORT_COMPILER_FLAGS {
1116 let prefix = if flag.len() == 1 { "-" } else { "--" };
1118 for content in &matches.opt_strs(flag) {
1119 // Split always returns the first element
1120 let name = if let Some(first) = content.split('=').next() { first } else { &content };
1123 if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) { name } else { content };
1125 if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
1126 result.push(format!("{}{} {}", prefix, flag, content));
1128 excluded_cargo_defaults = true;
1133 if !result.is_empty() { Some((result, excluded_cargo_defaults)) } else { None }
1136 /// Runs a closure and catches unwinds triggered by fatal errors.
1138 /// The compiler currently unwinds with a special sentinel value to abort
1139 /// compilation on fatal errors. This function catches that sentinel and turns
1140 /// the panic into a `Result` instead.
1141 pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
1142 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1143 if value.is::<rustc_errors::FatalErrorMarker>() {
1146 panic::resume_unwind(value);
1151 /// Variant of `catch_fatal_errors` for the `interface::Result` return type
1152 /// that also computes the exit code.
1153 pub fn catch_with_exit_code(f: impl FnOnce() -> interface::Result<()>) -> i32 {
1154 let result = catch_fatal_errors(f).and_then(|result| result);
1156 Ok(()) => EXIT_SUCCESS,
1157 Err(_) => EXIT_FAILURE,
1161 static DEFAULT_HOOK: SyncLazy<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> =
1163 let hook = panic::take_hook();
1164 panic::set_hook(Box::new(|info| {
1165 // Invoke the default handler, which prints the actual panic message and optionally a backtrace
1166 (*DEFAULT_HOOK)(info);
1168 // Separate the output with an empty line
1171 // Print the ICE message
1172 report_ice(info, BUG_REPORT_URL);
1177 /// Prints the ICE message, including query stack, but without backtrace.
1179 /// The message will point the user at `bug_report_url` to report the ICE.
1181 /// When `install_ice_hook` is called, this function will be called as the panic
1183 pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
1184 let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
1185 rustc_errors::ColorConfig::Auto,
1192 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1194 // a .span_bug or .bug call has already printed what
1195 // it wants to print.
1196 if !info.payload().is::<rustc_errors::ExplicitBug>() {
1197 let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
1198 handler.emit_diagnostic(&d);
1201 let mut xs: Vec<Cow<'static, str>> = vec![
1202 "the compiler unexpectedly panicked. this is a bug.".into(),
1203 format!("we would appreciate a bug report: {}", bug_report_url).into(),
1205 "rustc {} running on {}",
1206 util::version_str().unwrap_or("unknown_version"),
1207 config::host_triple()
1212 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1213 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1215 if excluded_cargo_defaults {
1216 xs.push("some of the compiler flags provided by cargo are hidden".into());
1221 handler.note_without_error(note);
1224 // If backtraces are enabled, also print the query stack
1225 let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
1227 let num_frames = if backtrace { None } else { Some(2) };
1229 interface::try_print_query_stack(&handler, num_frames);
1233 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1234 // Trigger a debugger if we crashed during bootstrap
1235 winapi::um::debugapi::DebugBreak();
1240 /// Installs a panic hook that will print the ICE message on unexpected panics.
1242 /// A custom rustc driver can skip calling this to set up a custom ICE hook.
1243 pub fn install_ice_hook() {
1244 SyncLazy::force(&DEFAULT_HOOK);
1247 /// This allows tools to enable rust logging without having to magically match rustc's
1248 /// tracing crate version.
1249 pub fn init_rustc_env_logger() {
1250 init_env_logger("RUSTC_LOG")
1253 /// This allows tools to enable rust logging without having to magically match rustc's
1254 /// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to choose an env var
1255 /// other than `RUSTC_LOG`.
1256 pub fn init_env_logger(env: &str) {
1257 use tracing_subscriber::{
1258 filter::{self, EnvFilter, LevelFilter},
1259 layer::SubscriberExt,
1262 let filter = match std::env::var(env) {
1263 Ok(env) => EnvFilter::new(env),
1264 _ => EnvFilter::default().add_directive(filter::Directive::from(LevelFilter::WARN)),
1267 let color_logs = match std::env::var(String::from(env) + "_COLOR") {
1268 Ok(value) => match value.as_ref() {
1271 "auto" => stderr_isatty(),
1273 ErrorOutputType::default(),
1275 "invalid log color value '{}': expected one of always, never, or auto",
1280 Err(std::env::VarError::NotPresent) => stderr_isatty(),
1281 Err(std::env::VarError::NotUnicode(_value)) => early_error(
1282 ErrorOutputType::default(),
1283 "non-Unicode log color value: expected one of always, never, or auto",
1287 let layer = tracing_tree::HierarchicalLayer::default()
1288 .with_writer(io::stderr)
1289 .with_indent_lines(true)
1290 .with_ansi(color_logs)
1292 .with_indent_amount(2);
1293 #[cfg(parallel_compiler)]
1294 let layer = layer.with_thread_ids(true).with_thread_names(true);
1296 let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
1297 tracing::subscriber::set_global_default(subscriber).unwrap();
1300 #[cfg(all(unix, any(target_env = "gnu", target_os = "macos")))]
1301 mod signal_handler {
1303 fn backtrace_symbols_fd(
1304 buffer: *const *mut libc::c_void,
1310 extern "C" fn print_stack_trace(_: libc::c_int) {
1311 const MAX_FRAMES: usize = 256;
1312 static mut STACK_TRACE: [*mut libc::c_void; MAX_FRAMES] =
1313 [std::ptr::null_mut(); MAX_FRAMES];
1315 let depth = libc::backtrace(STACK_TRACE.as_mut_ptr(), MAX_FRAMES as i32);
1319 backtrace_symbols_fd(STACK_TRACE.as_ptr(), depth, 2);
1323 // When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
1324 // process, print a stack trace and then exit.
1325 pub(super) fn install() {
1327 const ALT_STACK_SIZE: usize = libc::MINSIGSTKSZ + 64 * 1024;
1328 let mut alt_stack: libc::stack_t = std::mem::zeroed();
1330 std::alloc::alloc(std::alloc::Layout::from_size_align(ALT_STACK_SIZE, 1).unwrap())
1331 as *mut libc::c_void;
1332 alt_stack.ss_size = ALT_STACK_SIZE;
1333 libc::sigaltstack(&alt_stack, std::ptr::null_mut());
1335 let mut sa: libc::sigaction = std::mem::zeroed();
1336 sa.sa_sigaction = print_stack_trace as libc::sighandler_t;
1337 sa.sa_flags = libc::SA_NODEFER | libc::SA_RESETHAND | libc::SA_ONSTACK;
1338 libc::sigemptyset(&mut sa.sa_mask);
1339 libc::sigaction(libc::SIGSEGV, &sa, std::ptr::null_mut());
1344 #[cfg(not(all(unix, any(target_env = "gnu", target_os = "macos"))))]
1345 mod signal_handler {
1346 pub(super) fn install() {}
1349 pub fn main() -> ! {
1350 let start_time = Instant::now();
1351 let start_rss = get_resident_set_size();
1352 init_rustc_env_logger();
1353 signal_handler::install();
1354 let mut callbacks = TimePassesCallbacks::default();
1356 let exit_code = catch_with_exit_code(|| {
1357 let args = env::args_os()
1360 arg.into_string().unwrap_or_else(|arg| {
1362 ErrorOutputType::default(),
1363 &format!("argument {} is not valid Unicode: {:?}", i, arg),
1367 .collect::<Vec<_>>();
1368 RunCompiler::new(&args, &mut callbacks).run()
1371 if callbacks.time_passes {
1372 let end_rss = get_resident_set_size();
1373 print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss);
1376 process::exit(exit_code)