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;
31 extern crate rustc_data_structures;
32 extern crate rustc_errors as errors;
33 extern crate rustc_passes;
34 extern crate rustc_lint;
35 extern crate rustc_plugin;
36 extern crate rustc_privacy;
37 extern crate rustc_incremental;
38 extern crate rustc_metadata;
39 extern crate rustc_mir;
40 extern crate rustc_resolve;
41 extern crate rustc_save_analysis;
42 extern crate rustc_traits;
43 extern crate rustc_codegen_utils;
44 extern crate rustc_typeck;
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};
62 use rustc::session::CompileIncomplete;
63 use rustc::session::config::{Input, PrintRequest, ErrorOutputType};
64 use rustc::session::config::nightly_options;
65 use rustc::session::filesearch;
66 use rustc::session::{early_error, early_warn};
67 use rustc::lint::Lint;
69 use rustc_metadata::locator;
70 use rustc_metadata::cstore::CStore;
71 use rustc_metadata::dynamic_lib::DynamicLibrary;
72 use rustc::util::common::{time, ErrorReported};
73 use rustc_codegen_utils::codegen_backend::CodegenBackend;
75 use serialize::json::ToJson;
80 use std::default::Default;
81 use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
83 use std::error::Error;
84 use std::ffi::OsString;
85 use std::fmt::{self, Display};
86 use std::io::{self, Read, Write};
89 use std::path::{PathBuf, Path};
90 use std::process::{self, Command, Stdio};
92 use std::sync::atomic::{AtomicBool, Ordering};
93 use std::sync::{Once, ONCE_INIT};
97 use syntax::source_map::{SourceMap, FileLoader, RealFileLoader};
98 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
99 use syntax::parse::{self, PResult};
100 use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
108 mod proc_macro_decls;
110 pub mod target_features {
112 use syntax::symbol::Symbol;
113 use rustc::session::Session;
114 use rustc_codegen_utils::codegen_backend::CodegenBackend;
116 /// Adds `target_feature = "..."` cfgs for a variety of platform
117 /// specific features (SSE, NEON etc.).
119 /// This is performed by checking whether a whitelisted set of
120 /// features is available on the target machine, by querying LLVM.
121 pub fn add_configuration(cfg: &mut ast::CrateConfig,
123 codegen_backend: &dyn CodegenBackend) {
124 let tf = Symbol::intern("target_feature");
126 cfg.extend(codegen_backend.target_features(sess).into_iter().map(|feat| (tf, Some(feat))));
128 if sess.crt_static_feature() {
129 cfg.insert((tf, Some(Symbol::intern("crt-static"))));
134 /// Exit status code used for successful compilation and help output.
135 pub const EXIT_SUCCESS: isize = 0;
137 /// Exit status code used for compilation failures and invalid flags.
138 pub const EXIT_FAILURE: isize = 1;
140 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
143 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
145 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
147 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
149 pub fn abort_on_err<T>(result: Result<T, CompileIncomplete>, sess: &Session) -> T {
151 Err(CompileIncomplete::Errored(ErrorReported)) => {
152 sess.abort_if_errors();
153 panic!("error reported but abort_if_errors didn't abort???");
155 Err(CompileIncomplete::Stopped) => {
156 sess.fatal("compilation terminated");
162 pub fn run<F>(run_compiler: F) -> isize
163 where F: FnOnce() -> (CompileResult, Option<Session>) + Send + 'static
165 let result = monitor(move || {
166 syntax::with_globals(|| {
167 let (result, session) = run_compiler();
168 if let Err(CompileIncomplete::Errored(_)) = result {
171 sess.abort_if_errors();
172 panic!("error reported but abort_if_errors didn't abort???");
176 errors::emitter::EmitterWriter::stderr(
177 errors::ColorConfig::Auto,
182 let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
183 handler.emit(&MultiSpan::new(),
184 "aborting due to previous error(s)",
185 errors::Level::Fatal);
186 panic::resume_unwind(Box::new(errors::FatalErrorMarker));
194 Ok(()) => EXIT_SUCCESS,
195 Err(_) => EXIT_FAILURE,
199 fn load_backend_from_dylib(path: &Path) -> fn() -> Box<dyn CodegenBackend> {
200 let lib = DynamicLibrary::open(Some(path)).unwrap_or_else(|err| {
201 let err = format!("couldn't load codegen backend {:?}: {:?}", path, err);
202 early_error(ErrorOutputType::default(), &err);
205 match lib.symbol("__rustc_codegen_backend") {
208 mem::transmute::<*mut u8, _>(f)
211 let err = format!("couldn't load codegen backend as it \
212 doesn't export the `__rustc_codegen_backend` \
214 early_error(ErrorOutputType::default(), &err);
220 pub fn get_codegen_backend(sess: &Session) -> Box<dyn CodegenBackend> {
221 static INIT: Once = ONCE_INIT;
225 static mut LOAD: fn() -> Box<dyn CodegenBackend> = || unreachable!();
228 let codegen_name = sess.opts.debugging_opts.codegen_backend.as_ref()
229 .unwrap_or(&sess.target.target.options.codegen_backend);
230 let backend = match &codegen_name[..] {
232 rustc_codegen_utils::codegen_backend::MetadataOnlyCodegenBackend::boxed
234 filename if filename.contains(".") => {
235 load_backend_from_dylib(filename.as_ref())
237 codegen_name => get_codegen_sysroot(codegen_name),
244 let backend = unsafe { LOAD() };
249 fn get_codegen_sysroot(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> {
250 // For now we only allow this function to be called once as it'll dlopen a
251 // few things, which seems to work best if we only do that once. In
252 // general this assertion never trips due to the once guard in `get_codegen_backend`,
253 // but there's a few manual calls to this function in this file we protect
255 static LOADED: AtomicBool = AtomicBool::new(false);
256 assert!(!LOADED.fetch_or(true, Ordering::SeqCst),
257 "cannot load the default codegen backend twice");
259 // When we're compiling this library with `--test` it'll run as a binary but
260 // not actually exercise much functionality. As a result most of the logic
261 // here is defunkt (it assumes we're a dynamic library in a sysroot) so
262 // let's just return a dummy creation function which won't be used in
265 return rustc_codegen_utils::codegen_backend::MetadataOnlyCodegenBackend::boxed
268 let target = session::config::host_triple();
269 let mut sysroot_candidates = vec![filesearch::get_or_default_sysroot()];
270 let path = current_dll_path()
271 .and_then(|s| s.canonicalize().ok());
272 if let Some(dll) = path {
273 // use `parent` twice to chop off the file name and then also the
274 // directory containing the dll which should be either `lib` or `bin`.
275 if let Some(path) = dll.parent().and_then(|p| p.parent()) {
276 // The original `path` pointed at the `rustc_driver` crate's dll.
277 // Now that dll should only be in one of two locations. The first is
278 // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The
279 // other is the target's libdir, for example
280 // `$sysroot/lib/rustlib/$target/lib/*.dll`.
282 // We don't know which, so let's assume that if our `path` above
283 // ends in `$target` we *could* be in the target libdir, and always
284 // assume that we may be in the main libdir.
285 sysroot_candidates.push(path.to_owned());
287 if path.ends_with(target) {
288 sysroot_candidates.extend(path.parent() // chop off `$target`
289 .and_then(|p| p.parent()) // chop off `rustlib`
290 .and_then(|p| p.parent()) // chop off `lib`
291 .map(|s| s.to_owned()));
296 let sysroot = sysroot_candidates.iter()
298 let libdir = filesearch::relative_target_lib_path(&sysroot, &target);
299 sysroot.join(libdir).with_file_name(
300 option_env!("CFG_CODEGEN_BACKENDS_DIR").unwrap_or("codegen-backends"))
303 info!("codegen backend candidate: {}", f.display());
307 let sysroot = sysroot.unwrap_or_else(|| {
308 let candidates = sysroot_candidates.iter()
309 .map(|p| p.display().to_string())
312 let err = format!("failed to find a `codegen-backends` folder \
313 in the sysroot candidates:\n* {}", candidates);
314 early_error(ErrorOutputType::default(), &err);
316 info!("probing {} for a codegen backend", sysroot.display());
318 let d = sysroot.read_dir().unwrap_or_else(|e| {
319 let err = format!("failed to load default codegen backend, couldn't \
320 read `{}`: {}", sysroot.display(), e);
321 early_error(ErrorOutputType::default(), &err);
324 let mut file: Option<PathBuf> = None;
326 let expected_name = format!("rustc_codegen_llvm-{}", backend_name);
327 for entry in d.filter_map(|e| e.ok()) {
328 let path = entry.path();
329 let filename = match path.file_name().and_then(|s| s.to_str()) {
333 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
336 let name = &filename[DLL_PREFIX.len() .. filename.len() - DLL_SUFFIX.len()];
337 if name != expected_name {
340 if let Some(ref prev) = file {
341 let err = format!("duplicate codegen backends found\n\
344 ", prev.display(), path.display());
345 early_error(ErrorOutputType::default(), &err);
347 file = Some(path.clone());
351 Some(ref s) => return load_backend_from_dylib(s),
353 let err = format!("failed to load default codegen backend for `{}`, \
354 no appropriate codegen dylib found in `{}`",
355 backend_name, sysroot.display());
356 early_error(ErrorOutputType::default(), &err);
361 fn current_dll_path() -> Option<PathBuf> {
362 use std::ffi::{OsStr, CStr};
363 use std::os::unix::prelude::*;
366 let addr = current_dll_path as usize as *mut _;
367 let mut info = mem::zeroed();
368 if libc::dladdr(addr, &mut info) == 0 {
369 info!("dladdr failed");
372 if info.dli_fname.is_null() {
373 info!("dladdr returned null pointer");
376 let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
377 let os = OsStr::from_bytes(bytes);
378 Some(PathBuf::from(os))
383 fn current_dll_path() -> Option<PathBuf> {
384 use std::ffi::OsString;
385 use std::os::windows::prelude::*;
388 fn GetModuleHandleExW(dwFlags: u32,
390 phModule: *mut usize) -> i32;
391 fn GetModuleFileNameW(hModule: usize,
392 lpFilename: *mut u16,
396 const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS: u32 = 0x00000004;
400 let r = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
401 current_dll_path as usize,
404 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
407 let mut space = Vec::with_capacity(1024);
408 let r = GetModuleFileNameW(module,
410 space.capacity() as u32);
412 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
416 if r >= space.capacity() {
417 info!("our buffer was too small? {}",
418 io::Error::last_os_error());
422 let os = OsString::from_wide(&space);
423 Some(PathBuf::from(os))
428 // Parse args and run the compiler. This is the primary entry point for rustc.
429 // See comments on CompilerCalls below for details about the callbacks argument.
430 // The FileLoader provides a way to load files from sources other than the file system.
431 pub fn run_compiler<'a>(args: &[String],
432 callbacks: Box<dyn CompilerCalls<'a> + sync::Send + 'a>,
433 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
434 emitter_dest: Option<Box<dyn Write + Send>>)
435 -> (CompileResult, Option<Session>)
437 let matches = match handle_options(args) {
438 Some(matches) => matches,
439 None => return (Ok(()), None),
442 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
444 driver::spawn_thread_pool(sopts, |sopts| {
445 run_compiler_with_pool(matches, sopts, cfg, callbacks, file_loader, emitter_dest)
449 fn run_compiler_with_pool<'a>(
450 matches: getopts::Matches,
451 sopts: config::Options,
452 cfg: ast::CrateConfig,
453 mut callbacks: Box<dyn CompilerCalls<'a> + sync::Send + 'a>,
454 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
455 emitter_dest: Option<Box<dyn Write + Send>>
456 ) -> (CompileResult, Option<Session>) {
457 macro_rules! do_or_return {($expr: expr, $sess: expr) => {
459 Compilation::Stop => return (Ok(()), $sess),
460 Compilation::Continue => {}
464 let descriptions = diagnostics_registry();
466 do_or_return!(callbacks.early_callback(&matches,
473 let (odir, ofile) = make_output(&matches);
474 let (input, input_file_path, input_err) = match make_input(&matches.free) {
475 Some((input, input_file_path, input_err)) => {
476 let (input, input_file_path) = callbacks.some_input(input, input_file_path);
477 (input, input_file_path, input_err)
479 None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) {
480 Some((input, input_file_path)) => (input, input_file_path, None),
481 None => return (Ok(()), None),
485 let loader = file_loader.unwrap_or(box RealFileLoader);
486 let source_map = Lrc::new(SourceMap::with_file_loader(loader, sopts.file_path_mapping()));
487 let mut sess = session::build_session_with_source_map(
488 sopts, input_file_path.clone(), descriptions, source_map, emitter_dest,
491 if let Some(err) = input_err {
492 // Immediately stop compilation if there was an issue reading
493 // the input (for example if the input stream is not UTF-8).
494 sess.err(&err.to_string());
495 return (Err(CompileIncomplete::Stopped), Some(sess));
498 let codegen_backend = get_codegen_backend(&sess);
500 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
502 let mut cfg = config::build_configuration(&sess, cfg);
503 target_features::add_configuration(&mut cfg, &sess, &*codegen_backend);
504 sess.parse_sess.config = cfg;
507 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
509 let cstore = CStore::new(codegen_backend.metadata_loader());
511 do_or_return!(callbacks.late_callback(&*codegen_backend,
517 &ofile), Some(sess));
519 let _sess_abort_error = OnDrop(|| sess.diagnostic().print_error_count());
521 let control = callbacks.build_controller(&sess, &matches);
523 driver::compile_input(codegen_backend,
538 pub fn set_sigpipe_handler() {
540 // Set the SIGPIPE signal handler, so that an EPIPE
541 // will cause rustc to terminate, as expected.
542 assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
547 pub fn set_sigpipe_handler() {}
549 // Extract output directory and file from matches.
550 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
551 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
552 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
556 // Extract input (string or file and optional path) from matches.
557 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
558 if free_matches.len() == 1 {
559 let ifile = &free_matches[0];
561 let mut src = String::new();
562 let err = if io::stdin().read_to_string(&mut src).is_err() {
563 Some(io::Error::new(io::ErrorKind::InvalidData,
564 "couldn't read from stdin, as it did not contain valid UTF-8"))
568 Some((Input::Str { name: FileName::anon_source_code(&src), input: src },
571 Some((Input::File(PathBuf::from(ifile)),
572 Some(PathBuf::from(ifile)), None))
579 fn parse_pretty(sess: &Session,
580 matches: &getopts::Matches)
581 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
582 let pretty = if sess.opts.debugging_opts.unstable_options {
583 matches.opt_default("pretty", "normal").map(|a| {
584 // stable pretty-print variants only
585 pretty::parse_pretty(sess, &a, false)
591 if pretty.is_none() {
592 sess.opts.debugging_opts.unpretty.as_ref().map(|a| {
593 // extended with unstable pretty-print variants
594 pretty::parse_pretty(sess, &a, true)
601 // Whether to stop or continue compilation.
602 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
603 pub enum Compilation {
609 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
611 Compilation::Stop => Compilation::Stop,
612 Compilation::Continue => next(),
617 /// A trait for customizing the compilation process. Offers a number of hooks for
618 /// executing custom code or customizing input.
619 pub trait CompilerCalls<'a> {
620 /// Hook for a callback early in the process of handling arguments. This will
621 /// be called straight after options have been parsed but before anything
622 /// else (e.g., selecting input and output).
623 fn early_callback(&mut self,
624 _: &getopts::Matches,
626 _: &ast::CrateConfig,
627 _: &errors::registry::Registry,
630 Compilation::Continue
633 /// Hook for a callback late in the process of handling arguments. This will
634 /// be called just before actual compilation starts (and before build_controller
635 /// is called), after all arguments etc. have been completely handled.
636 fn late_callback(&mut self,
637 _: &dyn CodegenBackend,
638 _: &getopts::Matches,
645 Compilation::Continue
648 /// Called after we extract the input from the arguments. Gives the implementer
649 /// an opportunity to change the inputs or to add some custom input handling.
650 /// The default behaviour is to simply pass through the inputs.
651 fn some_input(&mut self,
653 input_path: Option<PathBuf>)
654 -> (Input, Option<PathBuf>) {
658 /// Called after we extract the input from the arguments if there is no valid
659 /// input. Gives the implementer an opportunity to supply alternate input (by
660 /// returning a Some value) or to add custom behaviour for this error such as
661 /// emitting error messages. Returning None will cause compilation to stop
663 fn no_input(&mut self,
664 _: &getopts::Matches,
666 _: &ast::CrateConfig,
669 _: &errors::registry::Registry)
670 -> Option<(Input, Option<PathBuf>)> {
674 // Create a CompilController struct for controlling the behaviour of
680 ) -> CompileController<'a>;
683 /// CompilerCalls instance for a regular rustc build.
684 #[derive(Copy, Clone)]
685 pub struct RustcDefaultCalls;
687 // FIXME remove these and use winapi 0.3 instead
688 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
690 fn stdout_isatty() -> bool {
691 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
695 fn stdout_isatty() -> bool {
698 type HANDLE = *mut u8;
699 type LPDWORD = *mut u32;
700 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
702 fn GetStdHandle(which: DWORD) -> HANDLE;
703 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
706 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
708 GetConsoleMode(handle, &mut out) != 0
712 fn handle_explain(code: &str,
713 descriptions: &errors::registry::Registry,
714 output: ErrorOutputType) {
715 let normalised = if code.starts_with("E") {
718 format!("E{0:0>4}", code)
720 match descriptions.find_description(&normalised) {
721 Some(ref description) => {
722 let mut is_in_code_block = false;
723 let mut text = String::new();
725 // Slice off the leading newline and print.
726 for line in description[1..].lines() {
727 let indent_level = line.find(|c: char| !c.is_whitespace())
728 .unwrap_or_else(|| line.len());
729 let dedented_line = &line[indent_level..];
730 if dedented_line.starts_with("```") {
731 is_in_code_block = !is_in_code_block;
732 text.push_str(&line[..(indent_level+3)]);
733 } else if is_in_code_block && dedented_line.starts_with("# ") {
742 show_content_with_pager(&text);
748 early_error(output, &format!("no extended information for {}", code));
753 fn show_content_with_pager(content: &String) {
754 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
755 OsString::from("more.com")
757 OsString::from("less")
760 let mut fallback_to_println = false;
762 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
764 if let Some(pipe) = pager.stdin.as_mut() {
765 if pipe.write_all(content.as_bytes()).is_err() {
766 fallback_to_println = true;
770 if pager.wait().is_err() {
771 fallback_to_println = true;
775 fallback_to_println = true;
779 // If pager fails for whatever reason, we should still print the content
780 // to standard output
781 if fallback_to_println {
782 print!("{}", content);
786 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
787 fn early_callback(&mut self,
788 matches: &getopts::Matches,
790 _: &ast::CrateConfig,
791 descriptions: &errors::registry::Registry,
792 output: ErrorOutputType)
794 if let Some(ref code) = matches.opt_str("explain") {
795 handle_explain(code, descriptions, output);
796 return Compilation::Stop;
799 Compilation::Continue
802 fn no_input(&mut self,
803 matches: &getopts::Matches,
804 sopts: &config::Options,
805 cfg: &ast::CrateConfig,
806 odir: &Option<PathBuf>,
807 ofile: &Option<PathBuf>,
808 descriptions: &errors::registry::Registry)
809 -> Option<(Input, Option<PathBuf>)> {
810 match matches.free.len() {
812 let mut sess = build_session(sopts.clone(),
814 descriptions.clone());
815 if sopts.describe_lints {
816 let mut ls = lint::LintStore::new();
817 rustc_lint::register_builtins(&mut ls, Some(&sess));
818 describe_lints(&sess, &ls, false);
821 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
822 let mut cfg = config::build_configuration(&sess, cfg.clone());
823 let codegen_backend = get_codegen_backend(&sess);
824 target_features::add_configuration(&mut cfg, &sess, &*codegen_backend);
825 sess.parse_sess.config = cfg;
826 let should_stop = RustcDefaultCalls::print_crate_info(
834 if should_stop == Compilation::Stop {
837 early_error(sopts.error_format, "no input filename given");
839 1 => panic!("make_input should have provided valid inputs"),
844 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
852 fn late_callback(&mut self,
853 codegen_backend: &dyn CodegenBackend,
854 matches: &getopts::Matches,
858 odir: &Option<PathBuf>,
859 ofile: &Option<PathBuf>)
861 RustcDefaultCalls::print_crate_info(codegen_backend, sess, Some(input), odir, ofile)
862 .and_then(|| RustcDefaultCalls::list_metadata(sess, cstore, matches, input))
865 fn build_controller(self: Box<Self>,
867 matches: &getopts::Matches)
868 -> CompileController<'a> {
869 let mut control = CompileController::basic();
871 control.keep_ast = sess.opts.debugging_opts.keep_ast;
872 control.continue_parse_after_error = sess.opts.debugging_opts.continue_parse_after_error;
874 if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
875 if ppm.needs_ast_map(&opt_uii) {
876 control.after_hir_lowering.stop = Compilation::Stop;
878 control.after_parse.callback = box move |state| {
879 let mut krate = state.krate.take().unwrap();
880 pretty::visit_crate(state.session, &mut krate, ppm);
881 state.krate = Some(krate);
883 control.after_hir_lowering.callback = box move |state| {
884 pretty::print_after_hir_lowering(state.session,
885 state.cstore.unwrap(),
886 state.hir_map.unwrap(),
887 state.resolutions.unwrap(),
889 &state.expanded_crate.take().unwrap(),
890 state.crate_name.unwrap(),
892 state.output_filenames.unwrap(),
897 control.after_parse.stop = Compilation::Stop;
899 control.after_parse.callback = box move |state| {
900 let mut krate = state.krate.take().unwrap();
901 pretty::visit_crate(state.session, &mut krate, ppm);
902 pretty::print_after_parsing(state.session,
913 if sess.opts.debugging_opts.parse_only ||
914 sess.opts.debugging_opts.show_span.is_some() ||
915 sess.opts.debugging_opts.ast_json_noexpand {
916 control.after_parse.stop = Compilation::Stop;
919 if sess.opts.debugging_opts.no_analysis ||
920 sess.opts.debugging_opts.ast_json {
921 control.after_hir_lowering.stop = Compilation::Stop;
924 if sess.opts.debugging_opts.save_analysis {
925 enable_save_analysis(&mut control);
928 if sess.print_fuel_crate.is_some() {
929 let old_callback = control.compilation_done.callback;
930 control.compilation_done.callback = box move |state| {
932 let sess = state.session;
933 eprintln!("Fuel used by {}: {}",
934 sess.print_fuel_crate.as_ref().unwrap(),
935 sess.print_fuel.load(SeqCst));
942 pub fn enable_save_analysis(control: &mut CompileController) {
943 control.keep_ast = true;
944 control.after_analysis.callback = box |state| {
945 time(state.session, "save analysis", || {
946 save::process_crate(state.tcx.unwrap(),
947 state.expanded_crate.unwrap(),
948 state.crate_name.unwrap(),
951 DumpHandler::new(state.out_dir,
952 state.crate_name.unwrap()))
955 control.after_analysis.run_callback_on_error = true;
958 impl RustcDefaultCalls {
959 pub fn list_metadata(sess: &Session,
961 matches: &getopts::Matches,
964 let r = matches.opt_strs("Z");
965 if r.iter().any(|s| *s == "ls") {
967 &Input::File(ref ifile) => {
968 let path = &(*ifile);
969 let mut v = Vec::new();
970 locator::list_file_metadata(&sess.target.target,
972 &*cstore.metadata_loader,
975 println!("{}", String::from_utf8(v).unwrap());
977 &Input::Str { .. } => {
978 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
981 return Compilation::Stop;
984 Compilation::Continue
988 fn print_crate_info(codegen_backend: &dyn CodegenBackend,
990 input: Option<&Input>,
991 odir: &Option<PathBuf>,
992 ofile: &Option<PathBuf>)
994 use rustc::session::config::PrintRequest::*;
995 // PrintRequest::NativeStaticLibs is special - printed during linking
996 // (empty iterator returns true)
997 if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
998 return Compilation::Continue;
1001 let attrs = match input {
1004 let result = parse_crate_attrs(sess, input);
1006 Ok(attrs) => Some(attrs),
1007 Err(mut parse_error) => {
1009 return Compilation::Stop;
1014 for req in &sess.opts.prints {
1017 let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
1019 println!("{}", targets.join("\n"));
1021 Sysroot => println!("{}", sess.sysroot.display()),
1022 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
1023 FileNames | CrateName => {
1024 let input = input.unwrap_or_else(||
1025 early_error(ErrorOutputType::default(), "no input file provided"));
1026 let attrs = attrs.as_ref().unwrap();
1027 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
1028 let id = rustc_codegen_utils::link::find_crate_name(Some(sess), attrs, input);
1029 if *req == PrintRequest::CrateName {
1033 let crate_types = driver::collect_crate_types(sess, attrs);
1034 for &style in &crate_types {
1035 let fname = rustc_codegen_utils::link::filename_for_input(
1041 println!("{}", fname.file_name().unwrap().to_string_lossy());
1045 let allow_unstable_cfg = UnstableFeatures::from_environment()
1046 .is_nightly_build();
1048 let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| {
1049 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
1050 ident: ast::Path::from_ident(ast::Ident::with_empty_ctxt(name)),
1051 node: ast::MetaItemKind::Word,
1055 // Note that crt-static is a specially recognized cfg
1056 // directive that's printed out here as part of
1057 // rust-lang/rust#37406, but in general the
1058 // `target_feature` cfg is gated under
1059 // rust-lang/rust#29717. For now this is just
1060 // specifically allowing the crt-static cfg and that's
1061 // it, this is intended to get into Cargo and then go
1062 // through to build scripts.
1063 let value = value.as_ref().map(|s| s.as_str());
1064 let value = value.as_ref().map(|s| s.as_ref());
1065 if name != "target_feature" || value != Some("crt-static") {
1066 if !allow_unstable_cfg && gated_cfg.is_some() {
1071 if let Some(value) = value {
1072 Some(format!("{}=\"{}\"", name, value))
1074 Some(name.to_string())
1076 }).collect::<Vec<String>>();
1080 println!("{}", cfg);
1083 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
1084 codegen_backend.print(*req, sess);
1086 // Any output here interferes with Cargo's parsing of other printed output
1087 PrintRequest::NativeStaticLibs => {}
1090 return Compilation::Stop;
1094 /// Returns a version string such as "0.12.0-dev".
1095 fn release_str() -> Option<&'static str> {
1096 option_env!("CFG_RELEASE")
1099 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
1100 fn commit_hash_str() -> Option<&'static str> {
1101 option_env!("CFG_VER_HASH")
1104 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
1105 fn commit_date_str() -> Option<&'static str> {
1106 option_env!("CFG_VER_DATE")
1109 /// Prints version information
1110 pub fn version(binary: &str, matches: &getopts::Matches) {
1111 let verbose = matches.opt_present("verbose");
1113 println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
1116 fn unw(x: Option<&str>) -> &str {
1117 x.unwrap_or("unknown")
1119 println!("binary: {}", binary);
1120 println!("commit-hash: {}", unw(commit_hash_str()));
1121 println!("commit-date: {}", unw(commit_date_str()));
1122 println!("host: {}", config::host_triple());
1123 println!("release: {}", unw(release_str()));
1124 get_codegen_sysroot("llvm")().print_version();
1128 fn usage(verbose: bool, include_unstable_options: bool) {
1129 let groups = if verbose {
1130 config::rustc_optgroups()
1132 config::rustc_short_optgroups()
1134 let mut options = getopts::Options::new();
1135 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
1136 (option.apply)(&mut options);
1138 let message = "Usage: rustc [OPTIONS] INPUT";
1139 let nightly_help = if nightly_options::is_nightly_build() {
1140 "\n -Z help Print internal options for debugging rustc"
1144 let verbose_help = if verbose {
1147 "\n --help -v Print the full set of options rustc accepts"
1149 println!("{}\nAdditional help:
1150 -C help Print codegen options
1152 Print 'lint' options and default settings{}{}\n",
1153 options.usage(message),
1158 fn print_wall_help() {
1160 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
1161 default. Use `rustc -W help` to see all available lints. It's more common to put
1162 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
1163 the command line flag directly.
1167 fn describe_lints(sess: &Session, lint_store: &lint::LintStore, loaded_plugins: bool) {
1169 Available lint options:
1170 -W <foo> Warn about <foo>
1174 -F <foo> Forbid <foo> \
1175 (deny <foo> and all attempts to override)
1179 fn sort_lints(sess: &Session, lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
1180 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
1181 // The sort doesn't case-fold but it's doubtful we care.
1182 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess), x.name));
1186 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
1187 -> Vec<(&'static str, Vec<lint::LintId>)> {
1188 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
1189 lints.sort_by_key(|l| l.0);
1193 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
1196 .partition(|&(_, p)| p);
1197 let plugin = sort_lints(sess, plugin);
1198 let builtin = sort_lints(sess, builtin);
1200 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
1203 .partition(|&(.., p)| p);
1204 let plugin_groups = sort_lint_groups(plugin_groups);
1205 let builtin_groups = sort_lint_groups(builtin_groups);
1207 let max_name_len = plugin.iter()
1209 .map(|&s| s.name.chars().count())
1212 let padded = |x: &str| {
1213 let mut s = " ".repeat(max_name_len - x.chars().count());
1218 println!("Lint checks provided by rustc:\n");
1219 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
1220 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
1222 let print_lints = |lints: Vec<&Lint>| {
1224 let name = lint.name_lower().replace("_", "-");
1225 println!(" {} {:7.7} {}",
1227 lint.default_level.as_str(),
1233 print_lints(builtin);
1235 let max_name_len = max("warnings".len(),
1236 plugin_groups.iter()
1237 .chain(&builtin_groups)
1238 .map(|&(s, _)| s.chars().count())
1242 let padded = |x: &str| {
1243 let mut s = " ".repeat(max_name_len - x.chars().count());
1248 println!("Lint groups provided by rustc:\n");
1249 println!(" {} {}", padded("name"), "sub-lints");
1250 println!(" {} {}", padded("----"), "---------");
1251 println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
1253 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
1254 for (name, to) in lints {
1255 let name = name.to_lowercase().replace("_", "-");
1256 let desc = to.into_iter()
1257 .map(|x| x.to_string().replace("_", "-"))
1258 .collect::<Vec<String>>()
1260 println!(" {} {}", padded(&name), desc);
1265 print_lint_groups(builtin_groups);
1267 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
1268 (false, 0, _) | (false, _, 0) => {
1269 println!("Compiler plugins can provide additional lints and lint groups. To see a \
1270 listing of these, re-run `rustc -W help` with a crate filename.");
1272 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
1273 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
1276 println!("Lint checks provided by plugins loaded by this crate:\n");
1277 print_lints(plugin);
1280 println!("Lint groups provided by plugins loaded by this crate:\n");
1281 print_lint_groups(plugin_groups);
1287 fn describe_debug_flags() {
1288 println!("\nAvailable debug options:\n");
1289 print_flag_list("-Z", config::DB_OPTIONS);
1292 fn describe_codegen_flags() {
1293 println!("\nAvailable codegen options:\n");
1294 print_flag_list("-C", config::CG_OPTIONS);
1297 fn print_flag_list<T>(cmdline_opt: &str,
1298 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
1299 let max_len = flag_list.iter()
1300 .map(|&(name, _, opt_type_desc, _)| {
1301 let extra_len = match opt_type_desc {
1305 name.chars().count() + extra_len
1310 for &(name, _, opt_type_desc, desc) in flag_list {
1311 let (width, extra) = match opt_type_desc {
1312 Some(..) => (max_len - 4, "=val"),
1313 None => (max_len, ""),
1315 println!(" {} {:>width$}{} -- {}",
1317 name.replace("_", "-"),
1324 /// Process command line options. Emits messages as appropriate. If compilation
1325 /// should continue, returns a getopts::Matches object parsed from args,
1326 /// otherwise returns `None`.
1328 /// The compiler's handling of options is a little complicated as it ties into
1329 /// our stability story, and it's even *more* complicated by historical
1330 /// accidents. The current intention of each compiler option is to have one of
1333 /// 1. An option is stable and can be used everywhere.
1334 /// 2. An option is unstable, but was historically allowed on the stable
1336 /// 3. An option is unstable, and can only be used on nightly.
1338 /// Like unstable library and language features, however, unstable options have
1339 /// always required a form of "opt in" to indicate that you're using them. This
1340 /// provides the easy ability to scan a code base to check to see if anything
1341 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1343 /// All options behind `-Z` are considered unstable by default. Other top-level
1344 /// options can also be considered unstable, and they were unlocked through the
1345 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1346 /// instability in both cases, though.
1348 /// So with all that in mind, the comments below have some more detail about the
1349 /// contortions done here to get things to work out correctly.
1350 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
1351 // Throw away the first argument, the name of the binary
1352 let args = &args[1..];
1354 if args.is_empty() {
1355 // user did not write `-v` nor `-Z unstable-options`, so do not
1356 // include that extra information.
1357 usage(false, false);
1361 // Parse with *all* options defined in the compiler, we don't worry about
1362 // option stability here we just want to parse as much as possible.
1363 let mut options = getopts::Options::new();
1364 for option in config::rustc_optgroups() {
1365 (option.apply)(&mut options);
1367 let matches = options.parse(args).unwrap_or_else(|f|
1368 early_error(ErrorOutputType::default(), &f.to_string()));
1370 // For all options we just parsed, we check a few aspects:
1372 // * If the option is stable, we're all good
1373 // * If the option wasn't passed, we're all good
1374 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1375 // ourselves), then we require the `-Z unstable-options` flag to unlock
1376 // this option that was passed.
1377 // * If we're a nightly compiler, then unstable options are now unlocked, so
1378 // we're good to go.
1379 // * Otherwise, if we're a truly unstable option then we generate an error
1380 // (unstable option being used on stable)
1381 // * If we're a historically stable-but-should-be-unstable option then we
1382 // emit a warning that we're going to turn this into an error soon.
1383 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1385 if matches.opt_present("h") || matches.opt_present("help") {
1386 // Only show unstable options in --help if we *really* accept unstable
1387 // options, which catches the case where we got `-Z unstable-options` on
1388 // the stable channel of Rust which was accidentally allowed
1390 usage(matches.opt_present("verbose"),
1391 nightly_options::is_unstable_enabled(&matches));
1395 // Handle the special case of -Wall.
1396 let wall = matches.opt_strs("W");
1397 if wall.iter().any(|x| *x == "all") {
1402 // Don't handle -W help here, because we might first load plugins.
1403 let r = matches.opt_strs("Z");
1404 if r.iter().any(|x| *x == "help") {
1405 describe_debug_flags();
1409 let cg_flags = matches.opt_strs("C");
1411 if cg_flags.iter().any(|x| *x == "help") {
1412 describe_codegen_flags();
1416 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1417 early_warn(ErrorOutputType::default(),
1418 "the --no-stack-check flag is deprecated and does nothing");
1421 if cg_flags.iter().any(|x| *x == "passes=list") {
1422 get_codegen_sysroot("llvm")().print_passes();
1426 if matches.opt_present("version") {
1427 version("rustc", &matches);
1434 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1436 Input::File(ref ifile) => {
1437 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1439 Input::Str { ref name, ref input } => {
1440 parse::parse_crate_attrs_from_source_str(name.clone(),
1447 // Temporarily have stack size set to 32MB to deal with various crates with long method
1448 // chains or deep syntax trees.
1449 // FIXME(oli-obk): get https://github.com/rust-lang/rust/pull/55617 the finish line
1450 const STACK_SIZE: usize = 32 * 1024 * 1024; // 32MB
1452 /// Runs `f` in a suitable thread for running `rustc`; returns a `Result` with either the return
1453 /// value of `f` or -- if a panic occurs -- the panic value.
1455 /// This version applies the given name to the thread. This is used by rustdoc to ensure consistent
1456 /// doctest output across platforms and executions.
1457 pub fn in_named_rustc_thread<F, R>(name: String, f: F) -> Result<R, Box<dyn Any + Send>>
1458 where F: FnOnce() -> R + Send + 'static,
1461 // We need a thread for soundness of thread local storage in rustc. For debugging purposes
1462 // we allow an escape hatch where everything runs on the main thread.
1463 if env::var_os("RUSTC_UNSTABLE_NO_MAIN_THREAD").is_none() {
1464 let mut cfg = thread::Builder::new().name(name);
1466 // If the env is trying to override the stack size then *don't* set it explicitly.
1467 // The libstd thread impl will fetch the `RUST_MIN_STACK` env var itself.
1468 if env::var_os("RUST_MIN_STACK").is_none() {
1469 cfg = cfg.stack_size(STACK_SIZE);
1472 let thread = cfg.spawn(f);
1473 thread.unwrap().join()
1475 let f = panic::AssertUnwindSafe(f);
1476 panic::catch_unwind(f)
1480 /// Runs `f` in a suitable thread for running `rustc`; returns a
1481 /// `Result` with either the return value of `f` or -- if a panic
1482 /// occurs -- the panic value.
1483 pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<dyn Any + Send>>
1484 where F: FnOnce() -> R + Send + 'static,
1487 in_named_rustc_thread("rustc".to_string(), f)
1490 /// Gets a list of extra command-line flags provided by the user, as strings.
1492 /// This function is used during ICEs to show more information useful for
1493 /// debugging, since some ICEs only happens with non-default compiler flags
1494 /// (and the users don't always report them).
1495 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1496 let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1498 // Avoid printing help because of empty args. This can suggest the compiler
1499 // itself is not the program root (consider RLS).
1504 let matches = if let Some(matches) = handle_options(&args) {
1510 let mut result = Vec::new();
1511 let mut excluded_cargo_defaults = false;
1512 for flag in ICE_REPORT_COMPILER_FLAGS {
1513 let prefix = if flag.len() == 1 { "-" } else { "--" };
1515 for content in &matches.opt_strs(flag) {
1516 // Split always returns the first element
1517 let name = if let Some(first) = content.split('=').next() {
1523 let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) {
1529 if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
1530 result.push(format!("{}{} {}", prefix, flag, content));
1532 excluded_cargo_defaults = true;
1537 if !result.is_empty() {
1538 Some((result, excluded_cargo_defaults))
1545 pub struct CompilationFailure;
1547 impl Error for CompilationFailure {}
1549 impl Display for CompilationFailure {
1550 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1551 write!(f, "compilation had errors")
1555 /// Runs a procedure which will detect panics in the compiler and print nicer
1556 /// error messages rather than just failing the test.
1558 /// The diagnostic emitter yielded to the procedure should be used for reporting
1559 /// errors of the compiler.
1560 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) -> Result<(), CompilationFailure> {
1561 in_rustc_thread(move || {
1563 }).map_err(|value| {
1564 if value.is::<errors::FatalErrorMarker>() {
1567 // Thread panicked without emitting a fatal diagnostic
1571 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
1575 let handler = errors::Handler::with_emitter(true, false, emitter);
1577 // a .span_bug or .bug call has already printed what
1578 // it wants to print.
1579 if !value.is::<errors::ExplicitBug>() {
1580 handler.emit(&MultiSpan::new(),
1582 errors::Level::Bug);
1585 let mut xs: Vec<Cow<'static, str>> = vec![
1586 "the compiler unexpectedly panicked. this is a bug.".into(),
1587 format!("we would appreciate a bug report: {}", BUG_REPORT_URL).into(),
1588 format!("rustc {} running on {}",
1589 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1590 config::host_triple()).into(),
1593 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1594 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1596 if excluded_cargo_defaults {
1597 xs.push("some of the compiler flags provided by cargo are hidden".into());
1602 handler.emit(&MultiSpan::new(),
1604 errors::Level::Note);
1607 panic::resume_unwind(Box::new(errors::FatalErrorMarker));
1612 pub fn diagnostics_registry() -> errors::registry::Registry {
1613 use errors::registry::Registry;
1615 let mut all_errors = Vec::new();
1616 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1617 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1618 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1619 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1620 // FIXME: need to figure out a way to get these back in here
1621 // all_errors.extend_from_slice(get_codegen_backend(sess).diagnostics());
1622 all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1623 all_errors.extend_from_slice(&rustc_passes::DIAGNOSTICS);
1624 all_errors.extend_from_slice(&rustc_plugin::DIAGNOSTICS);
1625 all_errors.extend_from_slice(&rustc_mir::DIAGNOSTICS);
1626 all_errors.extend_from_slice(&syntax::DIAGNOSTICS);
1628 Registry::new(&all_errors)
1631 /// This allows tools to enable rust logging without having to magically match rustc's
1632 /// log crate version
1633 pub fn init_rustc_env_logger() {
1638 init_rustc_env_logger();
1639 let result = run(|| {
1640 let args = env::args_os().enumerate()
1641 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1642 early_error(ErrorOutputType::default(),
1643 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1645 .collect::<Vec<_>>();
1647 Box::new(RustcDefaultCalls),
1651 process::exit(result as i32);