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_log::stdout_isatty;
29 use rustc_metadata::locator;
30 use rustc_save_analysis as save;
31 use rustc_save_analysis::DumpHandler;
32 use rustc_serialize::json::ToJson;
33 use rustc_session::config::{nightly_options, CG_OPTIONS, DB_OPTIONS};
34 use rustc_session::config::{ErrorOutputType, Input, OutputType, PrintRequest, TrimmedDefPaths};
35 use rustc_session::cstore::MetadataLoader;
36 use rustc_session::getopts;
37 use rustc_session::lint::{Lint, LintId};
38 use rustc_session::{config, DiagnosticOutput, Session};
39 use rustc_session::{early_error, early_error_no_abort, early_warn};
40 use rustc_span::source_map::{FileLoader, FileName};
41 use rustc_span::symbol::sym;
45 use std::default::Default;
47 use std::ffi::OsString;
49 use std::io::{self, Read, Write};
50 use std::lazy::SyncLazy;
51 use std::panic::{self, catch_unwind};
52 use std::path::PathBuf;
53 use std::process::{self, Command, Stdio};
55 use std::time::Instant;
60 /// Exit status code used for successful compilation and help output.
61 pub const EXIT_SUCCESS: i32 = 0;
63 /// Exit status code used for compilation failures and invalid flags.
64 pub const EXIT_FAILURE: i32 = 1;
66 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
67 ?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
69 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["-Z", "-C", "--crate-type"];
71 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
73 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
75 pub fn abort_on_err<T>(result: Result<T, ErrorReported>, sess: &Session) -> T {
78 sess.abort_if_errors();
79 panic!("error reported but abort_if_errors didn't abort???");
86 /// Called before creating the compiler instance
87 fn config(&mut self, _config: &mut interface::Config) {}
88 /// Called after parsing. Return value instructs the compiler whether to
89 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
90 fn after_parsing<'tcx>(
92 _compiler: &interface::Compiler,
93 _queries: &'tcx Queries<'tcx>,
97 /// Called after expansion. Return value instructs the compiler whether to
98 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
99 fn after_expansion<'tcx>(
101 _compiler: &interface::Compiler,
102 _queries: &'tcx Queries<'tcx>,
104 Compilation::Continue
106 /// Called after analysis. Return value instructs the compiler whether to
107 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
108 fn after_analysis<'tcx>(
110 _compiler: &interface::Compiler,
111 _queries: &'tcx Queries<'tcx>,
113 Compilation::Continue
118 pub struct TimePassesCallbacks {
122 impl Callbacks for TimePassesCallbacks {
123 fn config(&mut self, config: &mut interface::Config) {
124 // If a --prints=... option has been given, we don't print the "total"
125 // time because it will mess up the --prints output. See #64339.
126 self.time_passes = config.opts.prints.is_empty()
127 && (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time);
128 config.opts.trimmed_def_paths = TrimmedDefPaths::GoodPath;
132 pub fn diagnostics_registry() -> Registry {
133 Registry::new(rustc_error_codes::DIAGNOSTICS)
136 /// This is the primary entry point for rustc.
137 pub struct RunCompiler<'a, 'b> {
138 at_args: &'a [String],
139 callbacks: &'b mut (dyn Callbacks + Send),
140 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
141 emitter: Option<Box<dyn Write + Send>>,
142 make_codegen_backend:
143 Option<Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>>,
146 impl<'a, 'b> RunCompiler<'a, 'b> {
147 pub fn new(at_args: &'a [String], callbacks: &'b mut (dyn Callbacks + Send)) -> Self {
148 Self { at_args, callbacks, file_loader: None, emitter: None, make_codegen_backend: None }
151 /// Set a custom codegen backend.
154 pub fn set_make_codegen_backend(
156 make_codegen_backend: Option<
157 Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
160 self.make_codegen_backend = make_codegen_backend;
164 /// Emit diagnostics to the specified location.
167 pub fn set_emitter(&mut self, emitter: Option<Box<dyn Write + Send>>) -> &mut Self {
168 self.emitter = emitter;
172 /// Load files from sources other than the file system.
175 pub fn set_file_loader(
177 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
179 self.file_loader = file_loader;
183 /// Parse args and run the compiler.
184 pub fn run(self) -> interface::Result<()> {
190 self.make_codegen_backend,
196 callbacks: &mut (dyn Callbacks + Send),
197 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
198 emitter: Option<Box<dyn Write + Send>>,
199 make_codegen_backend: Option<
200 Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
202 ) -> interface::Result<()> {
203 let args = args::arg_expand_all(at_args);
205 let diagnostic_output = emitter.map_or(DiagnosticOutput::Default, DiagnosticOutput::Raw);
206 let matches = match handle_options(&args) {
207 Some(matches) => matches,
208 None => return Ok(()),
211 let sopts = config::build_session_options(&matches);
213 if let Some(ref code) = matches.opt_str("explain") {
214 handle_explain(diagnostics_registry(), code, sopts.error_format);
218 let cfg = interface::parse_cfgspecs(matches.opt_strs("cfg"));
219 let (odir, ofile) = make_output(&matches);
220 let mut config = interface::Config {
223 input: Input::File(PathBuf::new()),
230 lint_caps: Default::default(),
231 parse_sess_created: None,
232 register_lints: None,
233 override_queries: None,
234 make_codegen_backend,
235 registry: diagnostics_registry(),
238 match make_input(config.opts.error_format, &matches.free) {
239 Err(ErrorReported) => return Err(ErrorReported),
240 Ok(Some((input, input_file_path))) => {
241 config.input = input;
242 config.input_path = input_file_path;
244 callbacks.config(&mut config);
246 Ok(None) => match matches.free.len() {
248 callbacks.config(&mut config);
249 interface::run_compiler(config, |compiler| {
250 let sopts = &compiler.session().opts;
251 if sopts.describe_lints {
252 let mut lint_store = rustc_lint::new_lint_store(
253 sopts.debugging_opts.no_interleave_lints,
254 compiler.session().unstable_options(),
256 let registered_lints =
257 if let Some(register_lints) = compiler.register_lints() {
258 register_lints(compiler.session(), &mut lint_store);
263 describe_lints(compiler.session(), &lint_store, registered_lints);
266 let should_stop = print_crate_info(
267 &***compiler.codegen_backend(),
270 compiler.output_dir(),
271 compiler.output_file(),
272 compiler.temps_dir(),
275 if should_stop == Compilation::Stop {
278 early_error(sopts.error_format, "no input filename given")
282 1 => panic!("make_input should have provided valid inputs"),
284 config.opts.error_format,
286 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
287 matches.free[0], matches.free[1],
293 interface::run_compiler(config, |compiler| {
294 let sess = compiler.session();
295 let should_stop = print_crate_info(
296 &***compiler.codegen_backend(),
298 Some(compiler.input()),
299 compiler.output_dir(),
300 compiler.output_file(),
301 compiler.temps_dir(),
304 list_metadata(sess, &*compiler.codegen_backend().metadata_loader(), compiler.input())
306 .and_then(|| try_process_rlink(sess, compiler));
308 if should_stop == Compilation::Stop {
309 return sess.compile_status();
312 let linker = compiler.enter(|queries| {
313 let early_exit = || sess.compile_status().map(|_| None);
316 if let Some(ppm) = &sess.opts.pretty {
317 if ppm.needs_ast_map() {
318 let expanded_crate = queries.expansion()?.peek().0.clone();
319 queries.global_ctxt()?.peek_mut().enter(|tcx| {
320 pretty::print_after_hir_lowering(
325 compiler.output_file().as_ref().map(|p| &**p),
330 let krate = queries.parse()?.take();
331 pretty::print_after_parsing(
336 compiler.output_file().as_ref().map(|p| &**p),
339 trace!("finished pretty-printing");
343 if callbacks.after_parsing(compiler, queries) == Compilation::Stop {
347 if sess.opts.debugging_opts.parse_only
348 || sess.opts.debugging_opts.show_span.is_some()
349 || sess.opts.debugging_opts.ast_json_noexpand
355 let (_, lint_store) = &*queries.register_plugins()?.peek();
357 // Lint plugins are registered; now we can process command line flags.
358 if sess.opts.describe_lints {
359 describe_lints(sess, lint_store, true);
364 queries.expansion()?;
365 if callbacks.after_expansion(compiler, queries) == Compilation::Stop {
369 queries.prepare_outputs()?;
371 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
372 && sess.opts.output_types.len() == 1
377 queries.global_ctxt()?;
379 if sess.opts.debugging_opts.no_analysis || sess.opts.debugging_opts.ast_json {
383 queries.global_ctxt()?.peek_mut().enter(|tcx| {
384 let result = tcx.analysis(());
385 if sess.opts.debugging_opts.save_analysis {
386 let crate_name = queries.crate_name()?.peek().clone();
387 sess.time("save_analysis", || {
394 compiler.output_dir().as_ref().map(|p| &**p),
403 if callbacks.after_analysis(compiler, queries) == Compilation::Stop {
407 queries.ongoing_codegen()?;
409 if sess.opts.debugging_opts.print_type_sizes {
410 sess.code_stats.print_type_sizes();
413 let linker = queries.linker()?;
417 if let Some(linker) = linker {
418 let _timer = sess.timer("link");
422 if sess.opts.debugging_opts.perf_stats {
423 sess.print_perf_stats();
426 if sess.opts.debugging_opts.print_fuel.is_some() {
428 "Fuel used by {}: {}",
429 sess.opts.debugging_opts.print_fuel.as_ref().unwrap(),
430 sess.print_fuel.load(SeqCst)
439 pub fn set_sigpipe_handler() {
441 // Set the SIGPIPE signal handler, so that an EPIPE
442 // will cause rustc to terminate, as expected.
443 assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
448 pub fn set_sigpipe_handler() {}
450 // Extract output directory and file from matches.
451 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
452 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
453 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
457 // Extract input (string or file and optional path) from matches.
459 error_format: ErrorOutputType,
460 free_matches: &[String],
461 ) -> Result<Option<(Input, Option<PathBuf>)>, ErrorReported> {
462 if free_matches.len() == 1 {
463 let ifile = &free_matches[0];
465 let mut src = String::new();
466 if io::stdin().read_to_string(&mut src).is_err() {
467 // Immediately stop compilation if there was an issue reading
468 // the input (for example if the input stream is not UTF-8).
469 early_error_no_abort(
471 "couldn't read from stdin, as it did not contain valid UTF-8",
473 return Err(ErrorReported);
475 if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
476 let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
477 "when UNSTABLE_RUSTDOC_TEST_PATH is set \
478 UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
480 let line = isize::from_str_radix(&line, 10)
481 .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
482 let file_name = FileName::doc_test_source_code(PathBuf::from(path), line);
483 Ok(Some((Input::Str { name: file_name, input: src }, None)))
485 Ok(Some((Input::Str { name: FileName::anon_source_code(&src), input: src }, None)))
488 Ok(Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)))))
495 /// Whether to stop or continue compilation.
496 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
497 pub enum Compilation {
503 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
505 Compilation::Stop => Compilation::Stop,
506 Compilation::Continue => next(),
511 fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
512 let upper_cased_code = code.to_ascii_uppercase();
513 let normalised = if upper_cased_code.starts_with('E') {
516 format!("E{0:0>4}", code)
518 match registry.try_find_description(&normalised) {
519 Ok(Some(description)) => {
520 let mut is_in_code_block = false;
521 let mut text = String::new();
522 // Slice off the leading newline and print.
523 for line in description.lines() {
525 line.find(|c: char| !c.is_whitespace()).unwrap_or_else(|| line.len());
526 let dedented_line = &line[indent_level..];
527 if dedented_line.starts_with("```") {
528 is_in_code_block = !is_in_code_block;
529 text.push_str(&line[..(indent_level + 3)]);
530 } else if is_in_code_block && dedented_line.starts_with("# ") {
538 show_content_with_pager(&text);
544 early_error(output, &format!("no extended information for {}", code));
546 Err(InvalidErrorCode) => {
547 early_error(output, &format!("{} is not a valid error code", code));
552 fn show_content_with_pager(content: &str) {
553 let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
554 if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
557 let mut fallback_to_println = false;
559 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
561 if let Some(pipe) = pager.stdin.as_mut() {
562 if pipe.write_all(content.as_bytes()).is_err() {
563 fallback_to_println = true;
567 if pager.wait().is_err() {
568 fallback_to_println = true;
572 fallback_to_println = true;
576 // If pager fails for whatever reason, we should still print the content
577 // to standard output
578 if fallback_to_println {
579 print!("{}", content);
583 pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation {
584 if sess.opts.debugging_opts.link_only {
585 if let Input::File(file) = compiler.input() {
586 // FIXME: #![crate_type] and #![crate_name] support not implemented yet
587 sess.init_crate_types(collect_crate_types(sess, &[]));
588 let outputs = compiler.build_output_filenames(sess, &[]);
589 let rlink_data = fs::read(file).unwrap_or_else(|err| {
590 sess.fatal(&format!("failed to read rlink file: {}", err));
592 let mut decoder = rustc_serialize::opaque::Decoder::new(&rlink_data, 0);
593 let codegen_results: CodegenResults = rustc_serialize::Decodable::decode(&mut decoder);
594 let result = compiler.codegen_backend().link(sess, codegen_results, &outputs);
595 abort_on_err(result, sess);
597 sess.fatal("rlink must be a file")
601 Compilation::Continue
605 pub fn list_metadata(
607 metadata_loader: &dyn MetadataLoader,
610 if sess.opts.debugging_opts.ls {
612 Input::File(ref ifile) => {
613 let path = &(*ifile);
614 let mut v = Vec::new();
615 locator::list_file_metadata(&sess.target, path, metadata_loader, &mut v).unwrap();
616 println!("{}", String::from_utf8(v).unwrap());
618 Input::Str { .. } => {
619 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
622 return Compilation::Stop;
625 Compilation::Continue
629 codegen_backend: &dyn CodegenBackend,
631 input: Option<&Input>,
632 odir: &Option<PathBuf>,
633 ofile: &Option<PathBuf>,
634 temps_dir: &Option<PathBuf>,
636 use rustc_session::config::PrintRequest::*;
637 // NativeStaticLibs and LinkArgs are special - printed during linking
638 // (empty iterator returns true)
639 if sess.opts.prints.iter().all(|&p| p == NativeStaticLibs || p == LinkArgs) {
640 return Compilation::Continue;
643 let attrs = match input {
646 let result = parse_crate_attrs(sess, input);
648 Ok(attrs) => Some(attrs),
649 Err(mut parse_error) => {
651 return Compilation::Stop;
656 for req in &sess.opts.prints {
659 let mut targets = rustc_target::spec::TARGETS.iter().copied().collect::<Vec<_>>();
660 targets.sort_unstable();
661 println!("{}", targets.join("\n"));
663 Sysroot => println!("{}", sess.sysroot.display()),
664 TargetLibdir => println!("{}", sess.target_tlib_path.dir.display()),
665 TargetSpec => println!("{}", sess.target.to_json().pretty()),
666 FileNames | CrateName => {
667 let input = input.unwrap_or_else(|| {
668 early_error(ErrorOutputType::default(), "no input file provided")
670 let attrs = attrs.as_ref().unwrap();
671 let t_outputs = rustc_interface::util::build_output_filenames(
672 input, odir, ofile, temps_dir, attrs, sess,
674 let id = rustc_session::output::find_crate_name(sess, attrs, input);
675 if *req == PrintRequest::CrateName {
679 let crate_types = collect_crate_types(sess, attrs);
680 for &style in &crate_types {
682 rustc_session::output::filename_for_input(sess, style, &id, &t_outputs);
683 println!("{}", fname.file_name().unwrap().to_string_lossy());
691 .filter_map(|&(name, value)| {
692 // Note that crt-static is a specially recognized cfg
693 // directive that's printed out here as part of
694 // rust-lang/rust#37406, but in general the
695 // `target_feature` cfg is gated under
696 // rust-lang/rust#29717. For now this is just
697 // specifically allowing the crt-static cfg and that's
698 // it, this is intended to get into Cargo and then go
699 // through to build scripts.
700 if (name != sym::target_feature || value != Some(sym::crt_dash_static))
701 && !sess.is_nightly_build()
702 && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
707 if let Some(value) = value {
708 Some(format!("{}=\"{}\"", name, value))
710 Some(name.to_string())
713 .collect::<Vec<String>>();
724 | StackProtectorStrategies
725 | TargetFeatures => {
726 codegen_backend.print(*req, sess);
728 // Any output here interferes with Cargo's parsing of other printed output
729 NativeStaticLibs => {}
736 /// Prints version information
737 pub fn version(binary: &str, matches: &getopts::Matches) {
738 let verbose = matches.opt_present("verbose");
740 println!("{} {}", binary, util::version_str().unwrap_or("unknown version"));
743 fn unw(x: Option<&str>) -> &str {
744 x.unwrap_or("unknown")
746 println!("binary: {}", binary);
747 println!("commit-hash: {}", unw(util::commit_hash_str()));
748 println!("commit-date: {}", unw(util::commit_date_str()));
749 println!("host: {}", config::host_triple());
750 println!("release: {}", unw(util::release_str()));
752 let debug_flags = matches.opt_strs("Z");
753 let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
754 get_codegen_backend(&None, backend_name).print_version();
758 fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
759 let groups = if verbose { config::rustc_optgroups() } else { config::rustc_short_optgroups() };
760 let mut options = getopts::Options::new();
761 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
762 (option.apply)(&mut options);
764 let message = "Usage: rustc [OPTIONS] INPUT";
765 let nightly_help = if nightly_build {
766 "\n -Z help Print unstable compiler options"
770 let verbose_help = if verbose {
773 "\n --help -v Print the full set of options rustc accepts"
775 let at_path = if verbose {
776 " @path Read newline separated options from `path`\n"
781 "{options}{at_path}\nAdditional help:
782 -C help Print codegen options
784 Print 'lint' options and default settings{nightly}{verbose}\n",
785 options = options.usage(message),
787 nightly = nightly_help,
788 verbose = verbose_help
792 fn print_wall_help() {
795 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
796 default. Use `rustc -W help` to see all available lints. It's more common to put
797 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
798 the command line flag directly.
803 /// Write to stdout lint command options, together with a list of all available lints
804 pub fn describe_lints(sess: &Session, lint_store: &LintStore, loaded_plugins: bool) {
807 Available lint options:
808 -W <foo> Warn about <foo>
812 -F <foo> Forbid <foo> \
813 (deny <foo> and all attempts to override)
818 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
819 // The sort doesn't case-fold but it's doubtful we care.
820 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
825 lints: Vec<(&'static str, Vec<LintId>, bool)>,
826 ) -> Vec<(&'static str, Vec<LintId>)> {
827 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
828 lints.sort_by_key(|l| l.0);
832 let (plugin, builtin): (Vec<_>, _) =
833 lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_plugin);
834 let plugin = sort_lints(sess, plugin);
835 let builtin = sort_lints(sess, builtin);
837 let (plugin_groups, builtin_groups): (Vec<_>, _) =
838 lint_store.get_lint_groups().partition(|&(.., p)| p);
839 let plugin_groups = sort_lint_groups(plugin_groups);
840 let builtin_groups = sort_lint_groups(builtin_groups);
843 plugin.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
844 let padded = |x: &str| {
845 let mut s = " ".repeat(max_name_len - x.chars().count());
850 println!("Lint checks provided by rustc:\n");
851 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
852 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
854 let print_lints = |lints: Vec<&Lint>| {
856 let name = lint.name_lower().replace('_', "-");
860 lint.default_level(sess.edition()).as_str(),
867 print_lints(builtin);
869 let max_name_len = max(
873 .chain(&builtin_groups)
874 .map(|&(s, _)| s.chars().count())
879 let padded = |x: &str| {
880 let mut s = " ".repeat(max_name_len - x.chars().count());
885 println!("Lint groups provided by rustc:\n");
886 println!(" {} sub-lints", padded("name"));
887 println!(" {} ---------", padded("----"));
888 println!(" {} all lints that are set to issue warnings", padded("warnings"));
890 let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>| {
891 for (name, to) in lints {
892 let name = name.to_lowercase().replace('_', "-");
895 .map(|x| x.to_string().replace('_', "-"))
896 .collect::<Vec<String>>()
898 println!(" {} {}", padded(&name), desc);
903 print_lint_groups(builtin_groups);
905 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
906 (false, 0, _) | (false, _, 0) => {
907 println!("Lint tools like Clippy can provide additional lints and lint groups.");
909 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
910 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
913 println!("Lint checks provided by plugins loaded by this crate:\n");
917 println!("Lint groups provided by plugins loaded by this crate:\n");
918 print_lint_groups(plugin_groups);
924 fn describe_debug_flags() {
925 println!("\nAvailable options:\n");
926 print_flag_list("-Z", config::DB_OPTIONS);
929 fn describe_codegen_flags() {
930 println!("\nAvailable codegen options:\n");
931 print_flag_list("-C", config::CG_OPTIONS);
934 fn print_flag_list<T>(
936 flag_list: &[(&'static str, T, &'static str, &'static str)],
938 let max_len = flag_list.iter().map(|&(name, _, _, _)| name.chars().count()).max().unwrap_or(0);
940 for &(name, _, _, desc) in flag_list {
942 " {} {:>width$}=val -- {}",
944 name.replace('_', "-"),
951 /// Process command line options. Emits messages as appropriate. If compilation
952 /// should continue, returns a getopts::Matches object parsed from args,
953 /// otherwise returns `None`.
955 /// The compiler's handling of options is a little complicated as it ties into
956 /// our stability story. The current intention of each compiler option is to
957 /// have one of two modes:
959 /// 1. An option is stable and can be used everywhere.
960 /// 2. An option is unstable, and can only be used on nightly.
962 /// Like unstable library and language features, however, unstable options have
963 /// always required a form of "opt in" to indicate that you're using them. This
964 /// provides the easy ability to scan a code base to check to see if anything
965 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
967 /// All options behind `-Z` are considered unstable by default. Other top-level
968 /// options can also be considered unstable, and they were unlocked through the
969 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
970 /// instability in both cases, though.
972 /// So with all that in mind, the comments below have some more detail about the
973 /// contortions done here to get things to work out correctly.
974 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
975 // Throw away the first argument, the name of the binary
976 let args = &args[1..];
979 // user did not write `-v` nor `-Z unstable-options`, so do not
980 // include that extra information.
982 rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build();
983 usage(false, false, nightly_build);
987 // Parse with *all* options defined in the compiler, we don't worry about
988 // option stability here we just want to parse as much as possible.
989 let mut options = getopts::Options::new();
990 for option in config::rustc_optgroups() {
991 (option.apply)(&mut options);
993 let matches = options.parse(args).unwrap_or_else(|e| {
995 getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
997 .map(|&(name, ..)| ('C', name))
998 .chain(DB_OPTIONS.iter().map(|&(name, ..)| ('Z', name)))
999 .find(|&(_, name)| *opt == name.replace('_', "-"))
1000 .map(|(flag, _)| format!("{}. Did you mean `-{} {}`?", e, flag, opt)),
1003 early_error(ErrorOutputType::default(), &msg.unwrap_or_else(|| e.to_string()));
1006 // For all options we just parsed, we check a few aspects:
1008 // * If the option is stable, we're all good
1009 // * If the option wasn't passed, we're all good
1010 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1011 // ourselves), then we require the `-Z unstable-options` flag to unlock
1012 // this option that was passed.
1013 // * If we're a nightly compiler, then unstable options are now unlocked, so
1014 // we're good to go.
1015 // * Otherwise, if we're an unstable option then we generate an error
1016 // (unstable option being used on stable)
1017 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1019 if matches.opt_present("h") || matches.opt_present("help") {
1020 // Only show unstable options in --help if we accept unstable options.
1021 let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1022 let nightly_build = nightly_options::match_is_nightly_build(&matches);
1023 usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1027 // Handle the special case of -Wall.
1028 let wall = matches.opt_strs("W");
1029 if wall.iter().any(|x| *x == "all") {
1031 rustc_errors::FatalError.raise();
1034 // Don't handle -W help here, because we might first load plugins.
1035 let debug_flags = matches.opt_strs("Z");
1036 if debug_flags.iter().any(|x| *x == "help") {
1037 describe_debug_flags();
1041 let cg_flags = matches.opt_strs("C");
1043 if cg_flags.iter().any(|x| *x == "help") {
1044 describe_codegen_flags();
1048 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1050 ErrorOutputType::default(),
1051 "the --no-stack-check flag is deprecated and does nothing",
1055 if cg_flags.iter().any(|x| *x == "passes=list") {
1056 let backend_name = debug_flags.iter().find_map(|x| {
1057 if x.starts_with("codegen-backend=") {
1058 Some(&x["codegen-backends=".len()..])
1063 get_codegen_backend(&None, backend_name).print_passes();
1067 if matches.opt_present("version") {
1068 version("rustc", &matches);
1075 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1077 Input::File(ifile) => rustc_parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess),
1078 Input::Str { name, input } => rustc_parse::parse_crate_attrs_from_source_str(
1086 /// Gets a list of extra command-line flags provided by the user, as strings.
1088 /// This function is used during ICEs to show more information useful for
1089 /// debugging, since some ICEs only happens with non-default compiler flags
1090 /// (and the users don't always report them).
1091 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1092 let mut args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).peekable();
1094 let mut result = Vec::new();
1095 let mut excluded_cargo_defaults = false;
1096 while let Some(arg) = args.next() {
1097 if let Some(a) = ICE_REPORT_COMPILER_FLAGS.iter().find(|a| arg.starts_with(*a)) {
1098 let content = if arg.len() == a.len() {
1100 Some(arg) => arg.to_string(),
1103 } else if arg.get(a.len()..a.len() + 1) == Some("=") {
1104 arg[a.len() + 1..].to_string()
1106 arg[a.len()..].to_string()
1108 if ICE_REPORT_COMPILER_FLAGS_EXCLUDE.iter().any(|exc| content.starts_with(exc)) {
1109 excluded_cargo_defaults = true;
1111 result.push(a.to_string());
1112 match ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.iter().find(|s| content.starts_with(*s))
1114 Some(s) => result.push(s.to_string()),
1115 None => result.push(content),
1121 if !result.is_empty() { Some((result, excluded_cargo_defaults)) } else { None }
1124 /// Runs a closure and catches unwinds triggered by fatal errors.
1126 /// The compiler currently unwinds with a special sentinel value to abort
1127 /// compilation on fatal errors. This function catches that sentinel and turns
1128 /// the panic into a `Result` instead.
1129 pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
1130 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1131 if value.is::<rustc_errors::FatalErrorMarker>() {
1134 panic::resume_unwind(value);
1139 /// Variant of `catch_fatal_errors` for the `interface::Result` return type
1140 /// that also computes the exit code.
1141 pub fn catch_with_exit_code(f: impl FnOnce() -> interface::Result<()>) -> i32 {
1142 let result = catch_fatal_errors(f).and_then(|result| result);
1144 Ok(()) => EXIT_SUCCESS,
1145 Err(_) => EXIT_FAILURE,
1149 static DEFAULT_HOOK: SyncLazy<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> =
1151 let hook = panic::take_hook();
1152 panic::set_hook(Box::new(|info| {
1153 // Invoke the default handler, which prints the actual panic message and optionally a backtrace
1154 (*DEFAULT_HOOK)(info);
1156 // Separate the output with an empty line
1159 // Print the ICE message
1160 report_ice(info, BUG_REPORT_URL);
1165 /// Prints the ICE message, including query stack, but without backtrace.
1167 /// The message will point the user at `bug_report_url` to report the ICE.
1169 /// When `install_ice_hook` is called, this function will be called as the panic
1171 pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
1172 let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
1173 rustc_errors::ColorConfig::Auto,
1180 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1182 // a .span_bug or .bug call has already printed what
1183 // it wants to print.
1184 if !info.payload().is::<rustc_errors::ExplicitBug>() {
1185 let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
1186 handler.emit_diagnostic(&d);
1189 let mut xs: Vec<Cow<'static, str>> = vec![
1190 "the compiler unexpectedly panicked. this is a bug.".into(),
1191 format!("we would appreciate a bug report: {}", bug_report_url).into(),
1193 "rustc {} running on {}",
1194 util::version_str().unwrap_or("unknown_version"),
1195 config::host_triple()
1200 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1201 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1203 if excluded_cargo_defaults {
1204 xs.push("some of the compiler flags provided by cargo are hidden".into());
1209 handler.note_without_error(note);
1212 // If backtraces are enabled, also print the query stack
1213 let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
1215 let num_frames = if backtrace { None } else { Some(2) };
1217 interface::try_print_query_stack(&handler, num_frames);
1221 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1222 // Trigger a debugger if we crashed during bootstrap
1223 winapi::um::debugapi::DebugBreak();
1228 /// Installs a panic hook that will print the ICE message on unexpected panics.
1230 /// A custom rustc driver can skip calling this to set up a custom ICE hook.
1231 pub fn install_ice_hook() {
1232 // If the user has not explicitly overriden "RUST_BACKTRACE", then produce
1233 // full backtraces. When a compiler ICE happens, we want to gather
1234 // as much information as possible to present in the issue opened
1235 // by the user. Compiler developers and other rustc users can
1236 // opt in to less-verbose backtraces by manually setting "RUST_BACKTRACE"
1237 // (e.g. `RUST_BACKTRACE=1`)
1238 if std::env::var("RUST_BACKTRACE").is_err() {
1239 std::env::set_var("RUST_BACKTRACE", "full");
1241 SyncLazy::force(&DEFAULT_HOOK);
1244 /// This allows tools to enable rust logging without having to magically match rustc's
1245 /// tracing crate version.
1246 pub fn init_rustc_env_logger() {
1247 if let Err(error) = rustc_log::init_rustc_env_logger() {
1248 early_error(ErrorOutputType::default(), &error.to_string());
1252 /// This allows tools to enable rust logging without having to magically match rustc's
1253 /// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to choose an env var
1254 /// other than `RUSTC_LOG`.
1255 pub fn init_env_logger(env: &str) {
1256 if let Err(error) = rustc_log::init_env_logger(env) {
1257 early_error(ErrorOutputType::default(), &error.to_string());
1261 #[cfg(all(unix, any(target_env = "gnu", target_os = "macos")))]
1262 mod signal_handler {
1264 fn backtrace_symbols_fd(
1265 buffer: *const *mut libc::c_void,
1271 extern "C" fn print_stack_trace(_: libc::c_int) {
1272 const MAX_FRAMES: usize = 256;
1273 static mut STACK_TRACE: [*mut libc::c_void; MAX_FRAMES] =
1274 [std::ptr::null_mut(); MAX_FRAMES];
1276 let depth = libc::backtrace(STACK_TRACE.as_mut_ptr(), MAX_FRAMES as i32);
1280 backtrace_symbols_fd(STACK_TRACE.as_ptr(), depth, 2);
1284 // When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
1285 // process, print a stack trace and then exit.
1286 pub(super) fn install() {
1288 const ALT_STACK_SIZE: usize = libc::MINSIGSTKSZ + 64 * 1024;
1289 let mut alt_stack: libc::stack_t = std::mem::zeroed();
1291 std::alloc::alloc(std::alloc::Layout::from_size_align(ALT_STACK_SIZE, 1).unwrap())
1292 as *mut libc::c_void;
1293 alt_stack.ss_size = ALT_STACK_SIZE;
1294 libc::sigaltstack(&alt_stack, std::ptr::null_mut());
1296 let mut sa: libc::sigaction = std::mem::zeroed();
1297 sa.sa_sigaction = print_stack_trace as libc::sighandler_t;
1298 sa.sa_flags = libc::SA_NODEFER | libc::SA_RESETHAND | libc::SA_ONSTACK;
1299 libc::sigemptyset(&mut sa.sa_mask);
1300 libc::sigaction(libc::SIGSEGV, &sa, std::ptr::null_mut());
1305 #[cfg(not(all(unix, any(target_env = "gnu", target_os = "macos"))))]
1306 mod signal_handler {
1307 pub(super) fn install() {}
1310 pub fn main() -> ! {
1311 let start_time = Instant::now();
1312 let start_rss = get_resident_set_size();
1313 init_rustc_env_logger();
1314 signal_handler::install();
1315 let mut callbacks = TimePassesCallbacks::default();
1317 let exit_code = catch_with_exit_code(|| {
1318 let args = env::args_os()
1321 arg.into_string().unwrap_or_else(|arg| {
1323 ErrorOutputType::default(),
1324 &format!("argument {} is not valid Unicode: {:?}", i, arg),
1328 .collect::<Vec<_>>();
1329 RunCompiler::new(&args, &mut callbacks).run()
1332 if callbacks.time_passes {
1333 let end_rss = get_resident_set_size();
1334 print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss);
1337 process::exit(exit_code)