5 //! This API is completely unstable and subject to change.
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
9 #![feature(box_syntax)]
10 #![cfg_attr(unix, feature(libc))]
12 #![feature(rustc_diagnostic_macros)]
13 #![feature(set_stdio)]
15 #![feature(integer_atomics)]
17 #![recursion_limit="256"]
20 pub extern crate getopts;
21 extern crate graphviz;
22 extern crate env_logger;
25 extern crate rustc_rayon as rayon;
27 extern crate rustc_allocator;
28 extern crate rustc_target;
29 extern crate rustc_borrowck;
30 extern crate rustc_data_structures;
31 extern crate rustc_errors as errors;
32 extern crate rustc_passes;
33 extern crate rustc_lint;
34 extern crate rustc_plugin;
35 extern crate rustc_privacy;
36 extern crate rustc_incremental;
37 extern crate rustc_metadata;
38 extern crate rustc_mir;
39 extern crate rustc_resolve;
40 extern crate rustc_save_analysis;
41 extern crate rustc_traits;
42 extern crate rustc_codegen_utils;
43 extern crate rustc_typeck;
44 extern crate rustc_interface;
45 extern crate scoped_tls;
46 extern crate serialize;
47 extern crate smallvec;
51 extern crate syntax_ext;
52 extern crate syntax_pos;
54 use driver::CompileController;
55 use pretty::{PpMode, UserIdentifiedItem};
57 use rustc_save_analysis as save;
58 use rustc_save_analysis::DumpHandler;
59 use rustc_data_structures::sync::{self, Lrc, Ordering::SeqCst};
60 use rustc_data_structures::OnDrop;
61 use rustc::session::{self, config, Session, build_session, CompileResult, DiagnosticOutput};
62 use rustc::session::CompileIncomplete;
63 use rustc::session::config::{Input, PrintRequest, ErrorOutputType};
64 use rustc::session::config::nightly_options;
65 use rustc::session::{early_error, early_warn};
66 use rustc::lint::Lint;
68 use rustc_metadata::locator;
69 use rustc_metadata::cstore::CStore;
70 use rustc::util::common::{time, ErrorReported};
71 use rustc_codegen_utils::codegen_backend::CodegenBackend;
72 use rustc_interface::util::{self, get_codegen_sysroot};
74 use serialize::json::ToJson;
79 use std::default::Default;
81 use std::error::Error;
82 use std::ffi::OsString;
83 use std::fmt::{self, Display};
84 use std::io::{self, Read, Write};
86 use std::path::PathBuf;
87 use std::process::{self, Command, Stdio};
92 use syntax::source_map::{SourceMap, FileLoader, RealFileLoader};
93 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
94 use syntax::parse::{self, PResult};
95 use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
103 /// Exit status code used for successful compilation and help output.
104 pub const EXIT_SUCCESS: isize = 0;
106 /// Exit status code used for compilation failures and invalid flags.
107 pub const EXIT_FAILURE: isize = 1;
109 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
112 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
114 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
116 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
118 pub fn abort_on_err<T>(result: Result<T, CompileIncomplete>, sess: &Session) -> T {
120 Err(CompileIncomplete::Errored(ErrorReported)) => {
121 sess.abort_if_errors();
122 panic!("error reported but abort_if_errors didn't abort???");
124 Err(CompileIncomplete::Stopped) => {
125 sess.fatal("compilation terminated");
131 pub fn run<F>(run_compiler: F) -> isize
132 where F: FnOnce() -> (CompileResult, Option<Session>) + Send + 'static
134 let result = monitor(move || {
135 syntax::with_globals(|| {
136 let (result, session) = run_compiler();
137 if let Err(CompileIncomplete::Errored(_)) = result {
140 sess.abort_if_errors();
141 panic!("error reported but abort_if_errors didn't abort???");
145 errors::emitter::EmitterWriter::stderr(
146 errors::ColorConfig::Auto,
151 let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
152 handler.emit(&MultiSpan::new(),
153 "aborting due to previous error(s)",
154 errors::Level::Fatal);
155 panic::resume_unwind(Box::new(errors::FatalErrorMarker));
163 Ok(()) => EXIT_SUCCESS,
164 Err(_) => EXIT_FAILURE,
168 // Parse args and run the compiler. This is the primary entry point for rustc.
169 // See comments on CompilerCalls below for details about the callbacks argument.
170 // The FileLoader provides a way to load files from sources other than the file system.
171 pub fn run_compiler<'a>(args: &[String],
172 callbacks: Box<dyn CompilerCalls<'a> + sync::Send + 'a>,
173 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
174 emitter_dest: Option<Box<dyn Write + Send>>)
175 -> (CompileResult, Option<Session>)
177 let matches = match handle_options(args) {
178 Some(matches) => matches,
179 None => return (Ok(()), None),
182 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
184 driver::spawn_thread_pool(sopts, |sopts| {
185 run_compiler_with_pool(matches, sopts, cfg, callbacks, file_loader, emitter_dest)
189 fn run_compiler_with_pool<'a>(
190 matches: getopts::Matches,
191 sopts: config::Options,
192 cfg: ast::CrateConfig,
193 mut callbacks: Box<dyn CompilerCalls<'a> + sync::Send + 'a>,
194 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
195 emitter_dest: Option<Box<dyn Write + Send>>
196 ) -> (CompileResult, Option<Session>) {
197 macro_rules! do_or_return {($expr: expr, $sess: expr) => {
199 Compilation::Stop => return (Ok(()), $sess),
200 Compilation::Continue => {}
204 let descriptions = diagnostics_registry();
206 do_or_return!(callbacks.early_callback(&matches,
213 let (odir, ofile) = make_output(&matches);
214 let (input, input_file_path, input_err) = match make_input(&matches.free) {
215 Some((input, input_file_path, input_err)) => {
216 let (input, input_file_path) = callbacks.some_input(input, input_file_path);
217 (input, input_file_path, input_err)
219 None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) {
220 Some((input, input_file_path)) => (input, input_file_path, None),
221 None => return (Ok(()), None),
225 let loader = file_loader.unwrap_or(box RealFileLoader);
226 let source_map = Lrc::new(SourceMap::with_file_loader(loader, sopts.file_path_mapping()));
227 let mut sess = session::build_session_with_source_map(
229 input_file_path.clone(),
232 emitter_dest.map(|e| DiagnosticOutput::Raw(e)).unwrap_or(DiagnosticOutput::Default),
236 if let Some(err) = input_err {
237 // Immediately stop compilation if there was an issue reading
238 // the input (for example if the input stream is not UTF-8).
239 sess.err(&err.to_string());
240 return (Err(CompileIncomplete::Stopped), Some(sess));
243 let codegen_backend = util::get_codegen_backend(&sess);
245 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
247 let mut cfg = config::build_configuration(&sess, cfg);
248 util::add_configuration(&mut cfg, &sess, &*codegen_backend);
249 sess.parse_sess.config = cfg;
252 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
254 let cstore = CStore::new(codegen_backend.metadata_loader());
256 do_or_return!(callbacks.late_callback(&*codegen_backend,
262 &ofile), Some(sess));
264 let _sess_abort_error = OnDrop(|| sess.diagnostic().print_error_count());
266 let control = callbacks.build_controller(&sess, &matches);
268 driver::compile_input(codegen_backend,
283 pub fn set_sigpipe_handler() {
285 // Set the SIGPIPE signal handler, so that an EPIPE
286 // will cause rustc to terminate, as expected.
287 assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
292 pub fn set_sigpipe_handler() {}
294 // Extract output directory and file from matches.
295 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
296 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
297 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
301 // Extract input (string or file and optional path) from matches.
302 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
303 if free_matches.len() == 1 {
304 let ifile = &free_matches[0];
306 let mut src = String::new();
307 let err = if io::stdin().read_to_string(&mut src).is_err() {
308 Some(io::Error::new(io::ErrorKind::InvalidData,
309 "couldn't read from stdin, as it did not contain valid UTF-8"))
313 Some((Input::Str { name: FileName::anon_source_code(&src), input: src },
316 Some((Input::File(PathBuf::from(ifile)),
317 Some(PathBuf::from(ifile)), None))
324 fn parse_pretty(sess: &Session,
325 matches: &getopts::Matches)
326 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
327 let pretty = if sess.opts.debugging_opts.unstable_options {
328 matches.opt_default("pretty", "normal").map(|a| {
329 // stable pretty-print variants only
330 pretty::parse_pretty(sess, &a, false)
336 if pretty.is_none() {
337 sess.opts.debugging_opts.unpretty.as_ref().map(|a| {
338 // extended with unstable pretty-print variants
339 pretty::parse_pretty(sess, &a, true)
346 // Whether to stop or continue compilation.
347 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
348 pub enum Compilation {
354 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
356 Compilation::Stop => Compilation::Stop,
357 Compilation::Continue => next(),
362 /// A trait for customizing the compilation process. Offers a number of hooks for
363 /// executing custom code or customizing input.
364 pub trait CompilerCalls<'a> {
365 /// Hook for a callback early in the process of handling arguments. This will
366 /// be called straight after options have been parsed but before anything
367 /// else (e.g., selecting input and output).
368 fn early_callback(&mut self,
369 _: &getopts::Matches,
371 _: &ast::CrateConfig,
372 _: &errors::registry::Registry,
375 Compilation::Continue
378 /// Hook for a callback late in the process of handling arguments. This will
379 /// be called just before actual compilation starts (and before build_controller
380 /// is called), after all arguments etc. have been completely handled.
381 fn late_callback(&mut self,
382 _: &dyn CodegenBackend,
383 _: &getopts::Matches,
390 Compilation::Continue
393 /// Called after we extract the input from the arguments. Gives the implementer
394 /// an opportunity to change the inputs or to add some custom input handling.
395 /// The default behaviour is to simply pass through the inputs.
396 fn some_input(&mut self,
398 input_path: Option<PathBuf>)
399 -> (Input, Option<PathBuf>) {
403 /// Called after we extract the input from the arguments if there is no valid
404 /// input. Gives the implementer an opportunity to supply alternate input (by
405 /// returning a Some value) or to add custom behaviour for this error such as
406 /// emitting error messages. Returning None will cause compilation to stop
408 fn no_input(&mut self,
409 _: &getopts::Matches,
411 _: &ast::CrateConfig,
414 _: &errors::registry::Registry)
415 -> Option<(Input, Option<PathBuf>)> {
419 // Create a CompilController struct for controlling the behaviour of
425 ) -> CompileController<'a>;
428 /// CompilerCalls instance for a regular rustc build.
429 #[derive(Copy, Clone)]
430 pub struct RustcDefaultCalls;
432 // FIXME remove these and use winapi 0.3 instead
433 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
435 fn stdout_isatty() -> bool {
436 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
440 fn stdout_isatty() -> bool {
443 type HANDLE = *mut u8;
444 type LPDWORD = *mut u32;
445 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
447 fn GetStdHandle(which: DWORD) -> HANDLE;
448 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
451 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
453 GetConsoleMode(handle, &mut out) != 0
457 fn handle_explain(code: &str,
458 output: ErrorOutputType) {
459 let descriptions = rustc_interface::util::diagnostics_registry();
460 let normalised = if code.starts_with("E") {
463 format!("E{0:0>4}", code)
465 match descriptions.find_description(&normalised) {
466 Some(ref description) => {
467 let mut is_in_code_block = false;
468 let mut text = String::new();
470 // Slice off the leading newline and print.
471 for line in description[1..].lines() {
472 let indent_level = line.find(|c: char| !c.is_whitespace())
473 .unwrap_or_else(|| line.len());
474 let dedented_line = &line[indent_level..];
475 if dedented_line.starts_with("```") {
476 is_in_code_block = !is_in_code_block;
477 text.push_str(&line[..(indent_level+3)]);
478 } else if is_in_code_block && dedented_line.starts_with("# ") {
487 show_content_with_pager(&text);
493 early_error(output, &format!("no extended information for {}", code));
498 fn show_content_with_pager(content: &String) {
499 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
500 OsString::from("more.com")
502 OsString::from("less")
505 let mut fallback_to_println = false;
507 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
509 if let Some(pipe) = pager.stdin.as_mut() {
510 if pipe.write_all(content.as_bytes()).is_err() {
511 fallback_to_println = true;
515 if pager.wait().is_err() {
516 fallback_to_println = true;
520 fallback_to_println = true;
524 // If pager fails for whatever reason, we should still print the content
525 // to standard output
526 if fallback_to_println {
527 print!("{}", content);
531 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
532 fn early_callback(&mut self,
533 matches: &getopts::Matches,
535 _: &ast::CrateConfig,
536 _: &errors::registry::Registry,
537 output: ErrorOutputType)
539 if let Some(ref code) = matches.opt_str("explain") {
540 handle_explain(code, output);
541 return Compilation::Stop;
544 Compilation::Continue
547 fn no_input(&mut self,
548 matches: &getopts::Matches,
549 sopts: &config::Options,
550 cfg: &ast::CrateConfig,
551 odir: &Option<PathBuf>,
552 ofile: &Option<PathBuf>,
553 descriptions: &errors::registry::Registry)
554 -> Option<(Input, Option<PathBuf>)> {
555 match matches.free.len() {
557 let mut sess = build_session(sopts.clone(),
559 descriptions.clone());
560 if sopts.describe_lints {
561 let mut ls = lint::LintStore::new();
562 rustc_lint::register_builtins(&mut ls, Some(&sess));
563 describe_lints(&sess, &ls, false);
566 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
567 let mut cfg = config::build_configuration(&sess, cfg.clone());
568 let codegen_backend = util::get_codegen_backend(&sess);
569 util::add_configuration(&mut cfg, &sess, &*codegen_backend);
570 sess.parse_sess.config = cfg;
571 let should_stop = RustcDefaultCalls::print_crate_info(
579 if should_stop == Compilation::Stop {
582 early_error(sopts.error_format, "no input filename given");
584 1 => panic!("make_input should have provided valid inputs"),
589 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
597 fn late_callback(&mut self,
598 codegen_backend: &dyn CodegenBackend,
599 matches: &getopts::Matches,
603 odir: &Option<PathBuf>,
604 ofile: &Option<PathBuf>)
606 RustcDefaultCalls::print_crate_info(codegen_backend, sess, Some(input), odir, ofile)
607 .and_then(|| RustcDefaultCalls::list_metadata(sess, cstore, matches, input))
610 fn build_controller(self: Box<Self>,
612 matches: &getopts::Matches)
613 -> CompileController<'a> {
614 let mut control = CompileController::basic();
616 control.keep_ast = sess.opts.debugging_opts.keep_ast;
617 control.continue_parse_after_error = sess.opts.debugging_opts.continue_parse_after_error;
619 if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
620 if ppm.needs_ast_map(&opt_uii) {
621 control.after_hir_lowering.stop = Compilation::Stop;
623 control.after_parse.callback = box move |state| {
624 let mut krate = state.krate.take().unwrap();
625 pretty::visit_crate(state.session, &mut krate, ppm);
626 state.krate = Some(krate);
628 control.after_hir_lowering.callback = box move |state| {
629 pretty::print_after_hir_lowering(state.session,
630 state.cstore.unwrap(),
631 state.hir_map.unwrap(),
632 state.resolutions.unwrap(),
634 &state.expanded_crate.take().unwrap(),
635 state.crate_name.unwrap(),
637 state.output_filenames.unwrap(),
642 control.after_parse.stop = Compilation::Stop;
644 control.after_parse.callback = box move |state| {
645 let mut krate = state.krate.take().unwrap();
646 pretty::visit_crate(state.session, &mut krate, ppm);
647 pretty::print_after_parsing(state.session,
658 if sess.opts.debugging_opts.parse_only ||
659 sess.opts.debugging_opts.show_span.is_some() ||
660 sess.opts.debugging_opts.ast_json_noexpand {
661 control.after_parse.stop = Compilation::Stop;
664 if sess.opts.debugging_opts.no_analysis ||
665 sess.opts.debugging_opts.ast_json {
666 control.after_hir_lowering.stop = Compilation::Stop;
669 if sess.opts.debugging_opts.save_analysis {
670 enable_save_analysis(&mut control);
673 if sess.print_fuel_crate.is_some() {
674 let old_callback = control.compilation_done.callback;
675 control.compilation_done.callback = box move |state| {
677 let sess = state.session;
678 eprintln!("Fuel used by {}: {}",
679 sess.print_fuel_crate.as_ref().unwrap(),
680 sess.print_fuel.load(SeqCst));
687 pub fn enable_save_analysis(control: &mut CompileController) {
688 control.keep_ast = true;
689 control.after_analysis.callback = box |state| {
690 time(state.session, "save analysis", || {
691 save::process_crate(state.tcx.unwrap(),
692 state.expanded_crate.unwrap(),
693 state.crate_name.unwrap(),
696 DumpHandler::new(state.out_dir,
697 state.crate_name.unwrap()))
700 control.after_analysis.run_callback_on_error = true;
703 impl RustcDefaultCalls {
704 pub fn list_metadata(sess: &Session,
706 matches: &getopts::Matches,
709 let r = matches.opt_strs("Z");
710 if r.iter().any(|s| *s == "ls") {
712 &Input::File(ref ifile) => {
713 let path = &(*ifile);
714 let mut v = Vec::new();
715 locator::list_file_metadata(&sess.target.target,
717 &*cstore.metadata_loader,
720 println!("{}", String::from_utf8(v).unwrap());
722 &Input::Str { .. } => {
723 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
726 return Compilation::Stop;
729 Compilation::Continue
733 fn print_crate_info(codegen_backend: &dyn CodegenBackend,
735 input: Option<&Input>,
736 odir: &Option<PathBuf>,
737 ofile: &Option<PathBuf>)
739 use rustc::session::config::PrintRequest::*;
740 // PrintRequest::NativeStaticLibs is special - printed during linking
741 // (empty iterator returns true)
742 if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
743 return Compilation::Continue;
746 let attrs = match input {
749 let result = parse_crate_attrs(sess, input);
751 Ok(attrs) => Some(attrs),
752 Err(mut parse_error) => {
754 return Compilation::Stop;
759 for req in &sess.opts.prints {
762 let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
764 println!("{}", targets.join("\n"));
766 Sysroot => println!("{}", sess.sysroot.display()),
767 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
768 FileNames | CrateName => {
769 let input = input.unwrap_or_else(||
770 early_error(ErrorOutputType::default(), "no input file provided"));
771 let attrs = attrs.as_ref().unwrap();
772 let t_outputs = rustc_interface::util::build_output_filenames(
779 let id = rustc_codegen_utils::link::find_crate_name(Some(sess), attrs, input);
780 if *req == PrintRequest::CrateName {
784 let crate_types = rustc_interface::util::collect_crate_types(sess, attrs);
785 for &style in &crate_types {
786 let fname = rustc_codegen_utils::link::filename_for_input(
792 println!("{}", fname.file_name().unwrap().to_string_lossy());
796 let allow_unstable_cfg = UnstableFeatures::from_environment()
799 let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| {
800 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
801 ident: ast::Path::from_ident(ast::Ident::with_empty_ctxt(name)),
802 node: ast::MetaItemKind::Word,
806 // Note that crt-static is a specially recognized cfg
807 // directive that's printed out here as part of
808 // rust-lang/rust#37406, but in general the
809 // `target_feature` cfg is gated under
810 // rust-lang/rust#29717. For now this is just
811 // specifically allowing the crt-static cfg and that's
812 // it, this is intended to get into Cargo and then go
813 // through to build scripts.
814 let value = value.as_ref().map(|s| s.as_str());
815 let value = value.as_ref().map(|s| s.as_ref());
816 if name != "target_feature" || value != Some("crt-static") {
817 if !allow_unstable_cfg && gated_cfg.is_some() {
822 if let Some(value) = value {
823 Some(format!("{}=\"{}\"", name, value))
825 Some(name.to_string())
827 }).collect::<Vec<String>>();
834 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
835 codegen_backend.print(*req, sess);
837 // Any output here interferes with Cargo's parsing of other printed output
838 PrintRequest::NativeStaticLibs => {}
841 return Compilation::Stop;
845 /// Returns a version string such as "0.12.0-dev".
846 fn release_str() -> Option<&'static str> {
847 option_env!("CFG_RELEASE")
850 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
851 fn commit_hash_str() -> Option<&'static str> {
852 option_env!("CFG_VER_HASH")
855 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
856 fn commit_date_str() -> Option<&'static str> {
857 option_env!("CFG_VER_DATE")
860 /// Prints version information
861 pub fn version(binary: &str, matches: &getopts::Matches) {
862 let verbose = matches.opt_present("verbose");
864 println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
867 fn unw(x: Option<&str>) -> &str {
868 x.unwrap_or("unknown")
870 println!("binary: {}", binary);
871 println!("commit-hash: {}", unw(commit_hash_str()));
872 println!("commit-date: {}", unw(commit_date_str()));
873 println!("host: {}", config::host_triple());
874 println!("release: {}", unw(release_str()));
875 get_codegen_sysroot("llvm")().print_version();
879 fn usage(verbose: bool, include_unstable_options: bool) {
880 let groups = if verbose {
881 config::rustc_optgroups()
883 config::rustc_short_optgroups()
885 let mut options = getopts::Options::new();
886 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
887 (option.apply)(&mut options);
889 let message = "Usage: rustc [OPTIONS] INPUT";
890 let nightly_help = if nightly_options::is_nightly_build() {
891 "\n -Z help Print internal options for debugging rustc"
895 let verbose_help = if verbose {
898 "\n --help -v Print the full set of options rustc accepts"
900 println!("{}\nAdditional help:
901 -C help Print codegen options
903 Print 'lint' options and default settings{}{}\n",
904 options.usage(message),
909 fn print_wall_help() {
911 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
912 default. Use `rustc -W help` to see all available lints. It's more common to put
913 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
914 the command line flag directly.
918 fn describe_lints(sess: &Session, lint_store: &lint::LintStore, loaded_plugins: bool) {
920 Available lint options:
921 -W <foo> Warn about <foo>
925 -F <foo> Forbid <foo> \
926 (deny <foo> and all attempts to override)
930 fn sort_lints(sess: &Session, lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
931 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
932 // The sort doesn't case-fold but it's doubtful we care.
933 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess), x.name));
937 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
938 -> Vec<(&'static str, Vec<lint::LintId>)> {
939 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
940 lints.sort_by_key(|l| l.0);
944 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
947 .partition(|&(_, p)| p);
948 let plugin = sort_lints(sess, plugin);
949 let builtin = sort_lints(sess, builtin);
951 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
954 .partition(|&(.., p)| p);
955 let plugin_groups = sort_lint_groups(plugin_groups);
956 let builtin_groups = sort_lint_groups(builtin_groups);
958 let max_name_len = plugin.iter()
960 .map(|&s| s.name.chars().count())
963 let padded = |x: &str| {
964 let mut s = " ".repeat(max_name_len - x.chars().count());
969 println!("Lint checks provided by rustc:\n");
970 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
971 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
973 let print_lints = |lints: Vec<&Lint>| {
975 let name = lint.name_lower().replace("_", "-");
976 println!(" {} {:7.7} {}",
978 lint.default_level.as_str(),
984 print_lints(builtin);
986 let max_name_len = max("warnings".len(),
988 .chain(&builtin_groups)
989 .map(|&(s, _)| s.chars().count())
993 let padded = |x: &str| {
994 let mut s = " ".repeat(max_name_len - x.chars().count());
999 println!("Lint groups provided by rustc:\n");
1000 println!(" {} {}", padded("name"), "sub-lints");
1001 println!(" {} {}", padded("----"), "---------");
1002 println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
1004 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
1005 for (name, to) in lints {
1006 let name = name.to_lowercase().replace("_", "-");
1007 let desc = to.into_iter()
1008 .map(|x| x.to_string().replace("_", "-"))
1009 .collect::<Vec<String>>()
1011 println!(" {} {}", padded(&name), desc);
1016 print_lint_groups(builtin_groups);
1018 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
1019 (false, 0, _) | (false, _, 0) => {
1020 println!("Compiler plugins can provide additional lints and lint groups. To see a \
1021 listing of these, re-run `rustc -W help` with a crate filename.");
1023 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
1024 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
1027 println!("Lint checks provided by plugins loaded by this crate:\n");
1028 print_lints(plugin);
1031 println!("Lint groups provided by plugins loaded by this crate:\n");
1032 print_lint_groups(plugin_groups);
1038 fn describe_debug_flags() {
1039 println!("\nAvailable debug options:\n");
1040 print_flag_list("-Z", config::DB_OPTIONS);
1043 fn describe_codegen_flags() {
1044 println!("\nAvailable codegen options:\n");
1045 print_flag_list("-C", config::CG_OPTIONS);
1048 fn print_flag_list<T>(cmdline_opt: &str,
1049 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
1050 let max_len = flag_list.iter()
1051 .map(|&(name, _, opt_type_desc, _)| {
1052 let extra_len = match opt_type_desc {
1056 name.chars().count() + extra_len
1061 for &(name, _, opt_type_desc, desc) in flag_list {
1062 let (width, extra) = match opt_type_desc {
1063 Some(..) => (max_len - 4, "=val"),
1064 None => (max_len, ""),
1066 println!(" {} {:>width$}{} -- {}",
1068 name.replace("_", "-"),
1075 /// Process command line options. Emits messages as appropriate. If compilation
1076 /// should continue, returns a getopts::Matches object parsed from args,
1077 /// otherwise returns `None`.
1079 /// The compiler's handling of options is a little complicated as it ties into
1080 /// our stability story, and it's even *more* complicated by historical
1081 /// accidents. The current intention of each compiler option is to have one of
1084 /// 1. An option is stable and can be used everywhere.
1085 /// 2. An option is unstable, but was historically allowed on the stable
1087 /// 3. An option is unstable, and can only be used on nightly.
1089 /// Like unstable library and language features, however, unstable options have
1090 /// always required a form of "opt in" to indicate that you're using them. This
1091 /// provides the easy ability to scan a code base to check to see if anything
1092 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1094 /// All options behind `-Z` are considered unstable by default. Other top-level
1095 /// options can also be considered unstable, and they were unlocked through the
1096 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1097 /// instability in both cases, though.
1099 /// So with all that in mind, the comments below have some more detail about the
1100 /// contortions done here to get things to work out correctly.
1101 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
1102 // Throw away the first argument, the name of the binary
1103 let args = &args[1..];
1105 if args.is_empty() {
1106 // user did not write `-v` nor `-Z unstable-options`, so do not
1107 // include that extra information.
1108 usage(false, false);
1112 // Parse with *all* options defined in the compiler, we don't worry about
1113 // option stability here we just want to parse as much as possible.
1114 let mut options = getopts::Options::new();
1115 for option in config::rustc_optgroups() {
1116 (option.apply)(&mut options);
1118 let matches = options.parse(args).unwrap_or_else(|f|
1119 early_error(ErrorOutputType::default(), &f.to_string()));
1121 // For all options we just parsed, we check a few aspects:
1123 // * If the option is stable, we're all good
1124 // * If the option wasn't passed, we're all good
1125 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1126 // ourselves), then we require the `-Z unstable-options` flag to unlock
1127 // this option that was passed.
1128 // * If we're a nightly compiler, then unstable options are now unlocked, so
1129 // we're good to go.
1130 // * Otherwise, if we're a truly unstable option then we generate an error
1131 // (unstable option being used on stable)
1132 // * If we're a historically stable-but-should-be-unstable option then we
1133 // emit a warning that we're going to turn this into an error soon.
1134 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1136 if matches.opt_present("h") || matches.opt_present("help") {
1137 // Only show unstable options in --help if we *really* accept unstable
1138 // options, which catches the case where we got `-Z unstable-options` on
1139 // the stable channel of Rust which was accidentally allowed
1141 usage(matches.opt_present("verbose"),
1142 nightly_options::is_unstable_enabled(&matches));
1146 // Handle the special case of -Wall.
1147 let wall = matches.opt_strs("W");
1148 if wall.iter().any(|x| *x == "all") {
1153 // Don't handle -W help here, because we might first load plugins.
1154 let r = matches.opt_strs("Z");
1155 if r.iter().any(|x| *x == "help") {
1156 describe_debug_flags();
1160 let cg_flags = matches.opt_strs("C");
1162 if cg_flags.iter().any(|x| *x == "help") {
1163 describe_codegen_flags();
1167 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1168 early_warn(ErrorOutputType::default(),
1169 "the --no-stack-check flag is deprecated and does nothing");
1172 if cg_flags.iter().any(|x| *x == "passes=list") {
1173 get_codegen_sysroot("llvm")().print_passes();
1177 if matches.opt_present("version") {
1178 version("rustc", &matches);
1185 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1187 Input::File(ref ifile) => {
1188 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1190 Input::Str { ref name, ref input } => {
1191 parse::parse_crate_attrs_from_source_str(name.clone(),
1198 // Temporarily have stack size set to 32MB to deal with various crates with long method
1199 // chains or deep syntax trees.
1200 // FIXME(oli-obk): get https://github.com/rust-lang/rust/pull/55617 the finish line
1201 const STACK_SIZE: usize = 32 * 1024 * 1024; // 32MB
1203 /// Runs `f` in a suitable thread for running `rustc`; returns a `Result` with either the return
1204 /// value of `f` or -- if a panic occurs -- the panic value.
1206 /// This version applies the given name to the thread. This is used by rustdoc to ensure consistent
1207 /// doctest output across platforms and executions.
1208 pub fn in_named_rustc_thread<F, R>(name: String, f: F) -> Result<R, Box<dyn Any + Send>>
1209 where F: FnOnce() -> R + Send + 'static,
1212 // We need a thread for soundness of thread local storage in rustc. For debugging purposes
1213 // we allow an escape hatch where everything runs on the main thread.
1214 if env::var_os("RUSTC_UNSTABLE_NO_MAIN_THREAD").is_none() {
1215 let mut cfg = thread::Builder::new().name(name);
1217 // If the env is trying to override the stack size then *don't* set it explicitly.
1218 // The libstd thread impl will fetch the `RUST_MIN_STACK` env var itself.
1219 if env::var_os("RUST_MIN_STACK").is_none() {
1220 cfg = cfg.stack_size(STACK_SIZE);
1223 let thread = cfg.spawn(f);
1224 thread.unwrap().join()
1226 let f = panic::AssertUnwindSafe(f);
1227 panic::catch_unwind(f)
1231 /// Runs `f` in a suitable thread for running `rustc`; returns a
1232 /// `Result` with either the return value of `f` or -- if a panic
1233 /// occurs -- the panic value.
1234 pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<dyn Any + Send>>
1235 where F: FnOnce() -> R + Send + 'static,
1238 in_named_rustc_thread("rustc".to_string(), f)
1241 /// Gets a list of extra command-line flags provided by the user, as strings.
1243 /// This function is used during ICEs to show more information useful for
1244 /// debugging, since some ICEs only happens with non-default compiler flags
1245 /// (and the users don't always report them).
1246 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1247 let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1249 // Avoid printing help because of empty args. This can suggest the compiler
1250 // itself is not the program root (consider RLS).
1255 let matches = if let Some(matches) = handle_options(&args) {
1261 let mut result = Vec::new();
1262 let mut excluded_cargo_defaults = false;
1263 for flag in ICE_REPORT_COMPILER_FLAGS {
1264 let prefix = if flag.len() == 1 { "-" } else { "--" };
1266 for content in &matches.opt_strs(flag) {
1267 // Split always returns the first element
1268 let name = if let Some(first) = content.split('=').next() {
1274 let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) {
1280 if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
1281 result.push(format!("{}{} {}", prefix, flag, content));
1283 excluded_cargo_defaults = true;
1288 if !result.is_empty() {
1289 Some((result, excluded_cargo_defaults))
1296 pub struct CompilationFailure;
1298 impl Error for CompilationFailure {}
1300 impl Display for CompilationFailure {
1301 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1302 write!(f, "compilation had errors")
1306 /// Runs a procedure which will detect panics in the compiler and print nicer
1307 /// error messages rather than just failing the test.
1309 /// The diagnostic emitter yielded to the procedure should be used for reporting
1310 /// errors of the compiler.
1311 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) -> Result<(), CompilationFailure> {
1312 in_rustc_thread(move || {
1314 }).map_err(|value| {
1315 if value.is::<errors::FatalErrorMarker>() {
1318 // Thread panicked without emitting a fatal diagnostic
1322 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
1326 let handler = errors::Handler::with_emitter(true, false, emitter);
1328 // a .span_bug or .bug call has already printed what
1329 // it wants to print.
1330 if !value.is::<errors::ExplicitBug>() {
1331 handler.emit(&MultiSpan::new(),
1333 errors::Level::Bug);
1336 let mut xs: Vec<Cow<'static, str>> = vec![
1337 "the compiler unexpectedly panicked. this is a bug.".into(),
1338 format!("we would appreciate a bug report: {}", BUG_REPORT_URL).into(),
1339 format!("rustc {} running on {}",
1340 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1341 config::host_triple()).into(),
1344 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1345 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1347 if excluded_cargo_defaults {
1348 xs.push("some of the compiler flags provided by cargo are hidden".into());
1353 handler.emit(&MultiSpan::new(),
1355 errors::Level::Note);
1358 panic::resume_unwind(Box::new(errors::FatalErrorMarker));
1363 pub fn diagnostics_registry() -> errors::registry::Registry {
1364 use errors::registry::Registry;
1366 let mut all_errors = Vec::new();
1367 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1368 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1369 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1370 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1371 // FIXME: need to figure out a way to get these back in here
1372 // all_errors.extend_from_slice(get_codegen_backend(sess).diagnostics());
1373 all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1374 all_errors.extend_from_slice(&rustc_passes::DIAGNOSTICS);
1375 all_errors.extend_from_slice(&rustc_plugin::DIAGNOSTICS);
1376 all_errors.extend_from_slice(&rustc_mir::DIAGNOSTICS);
1377 all_errors.extend_from_slice(&syntax::DIAGNOSTICS);
1379 Registry::new(&all_errors)
1382 /// This allows tools to enable rust logging without having to magically match rustc's
1383 /// log crate version
1384 pub fn init_rustc_env_logger() {
1389 init_rustc_env_logger();
1390 let result = run(|| {
1391 let args = env::args_os().enumerate()
1392 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1393 early_error(ErrorOutputType::default(),
1394 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1396 .collect::<Vec<_>>();
1398 Box::new(RustcDefaultCalls),
1402 process::exit(result as i32);