1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! The Rust compiler.
15 //! This API is completely unstable and subject to change.
17 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
18 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
19 html_root_url = "https://doc.rust-lang.org/nightly/")]
21 #![feature(box_syntax)]
22 #![cfg_attr(unix, feature(libc))]
25 #![feature(rustc_diagnostic_macros)]
26 #![feature(slice_sort_by_cached_key)]
27 #![feature(set_stdio)]
30 #![recursion_limit="256"]
33 pub extern crate getopts;
34 extern crate graphviz;
35 extern crate env_logger;
38 extern crate rustc_rayon as rayon;
40 extern crate rustc_allocator;
41 extern crate rustc_target;
42 extern crate rustc_borrowck;
43 extern crate rustc_data_structures;
44 extern crate rustc_errors as errors;
45 extern crate rustc_passes;
46 extern crate rustc_lint;
47 extern crate rustc_plugin;
48 extern crate rustc_privacy;
49 extern crate rustc_incremental;
50 extern crate rustc_metadata;
51 extern crate rustc_mir;
52 extern crate rustc_resolve;
53 extern crate rustc_save_analysis;
54 extern crate rustc_traits;
55 extern crate rustc_codegen_utils;
56 extern crate rustc_typeck;
57 extern crate scoped_tls;
58 extern crate serialize;
59 extern crate smallvec;
63 extern crate syntax_ext;
64 extern crate syntax_pos;
66 // Note that the linkage here should be all that we need, on Linux we're not
67 // prefixing the symbols here so this should naturally override our default
68 // allocator. On OSX it should override via the zone allocator. We shouldn't
69 // enable this by default on other platforms, so other platforms aren't handled
71 #[cfg(feature = "jemalloc-sys")]
72 extern crate jemalloc_sys;
74 use driver::CompileController;
75 use pretty::{PpMode, UserIdentifiedItem};
77 use rustc_resolve as resolve;
78 use rustc_save_analysis as save;
79 use rustc_save_analysis::DumpHandler;
80 use rustc_data_structures::sync::{self, Lrc};
81 use rustc_data_structures::OnDrop;
82 use rustc::session::{self, config, Session, build_session, CompileResult};
83 use rustc::session::CompileIncomplete;
84 use rustc::session::config::{Input, PrintRequest, ErrorOutputType};
85 use rustc::session::config::nightly_options;
86 use rustc::session::filesearch;
87 use rustc::session::{early_error, early_warn};
88 use rustc::lint::Lint;
90 use rustc_metadata::locator;
91 use rustc_metadata::cstore::CStore;
92 use rustc_metadata::dynamic_lib::DynamicLibrary;
93 use rustc::util::common::{time, ErrorReported};
94 use rustc_codegen_utils::codegen_backend::CodegenBackend;
96 use serialize::json::ToJson;
101 use std::default::Default;
102 use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
104 use std::error::Error;
105 use std::ffi::OsString;
106 use std::fmt::{self, Display};
107 use std::io::{self, Read, Write};
110 use std::path::{PathBuf, Path};
111 use std::process::{self, Command, Stdio};
113 use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
114 use std::sync::{Once, ONCE_INIT};
118 use syntax::source_map::{SourceMap, FileLoader, RealFileLoader};
119 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
120 use syntax::parse::{self, PResult};
121 use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
129 mod proc_macro_decls;
131 pub mod target_features {
133 use syntax::symbol::Symbol;
134 use rustc::session::Session;
135 use rustc_codegen_utils::codegen_backend::CodegenBackend;
137 /// Add `target_feature = "..."` cfgs for a variety of platform
138 /// specific features (SSE, NEON etc.).
140 /// This is performed by checking whether a whitelisted set of
141 /// features is available on the target machine, by querying LLVM.
142 pub fn add_configuration(cfg: &mut ast::CrateConfig,
144 codegen_backend: &dyn CodegenBackend) {
145 let tf = Symbol::intern("target_feature");
147 cfg.extend(codegen_backend.target_features(sess).into_iter().map(|feat| (tf, Some(feat))));
149 if sess.crt_static_feature() {
150 cfg.insert((tf, Some(Symbol::intern("crt-static"))));
155 /// Exit status code used for successful compilation and help output.
156 pub const EXIT_SUCCESS: isize = 0;
158 /// Exit status code used for compilation failures and invalid flags.
159 pub const EXIT_FAILURE: isize = 1;
161 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
164 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
166 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
168 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
170 pub fn abort_on_err<T>(result: Result<T, CompileIncomplete>, sess: &Session) -> T {
172 Err(CompileIncomplete::Errored(ErrorReported)) => {
173 sess.abort_if_errors();
174 panic!("error reported but abort_if_errors didn't abort???");
176 Err(CompileIncomplete::Stopped) => {
177 sess.fatal("compilation terminated");
183 pub fn run<F>(run_compiler: F) -> isize
184 where F: FnOnce() -> (CompileResult, Option<Session>) + Send + 'static
186 let result = monitor(move || {
187 syntax::with_globals(|| {
188 let (result, session) = run_compiler();
189 if let Err(CompileIncomplete::Errored(_)) = result {
192 sess.abort_if_errors();
193 panic!("error reported but abort_if_errors didn't abort???");
197 errors::emitter::EmitterWriter::stderr(
198 errors::ColorConfig::Auto,
203 let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
204 handler.emit(&MultiSpan::new(),
205 "aborting due to previous error(s)",
206 errors::Level::Fatal);
207 panic::resume_unwind(Box::new(errors::FatalErrorMarker));
215 Ok(()) => EXIT_SUCCESS,
216 Err(_) => EXIT_FAILURE,
220 fn load_backend_from_dylib(path: &Path) -> fn() -> Box<dyn CodegenBackend> {
221 // Note that we're specifically using `open_global_now` here rather than
222 // `open`, namely we want the behavior on Unix of RTLD_GLOBAL and RTLD_NOW,
223 // where NOW means "bind everything right now" because we don't want
224 // surprises later on and RTLD_GLOBAL allows the symbols to be made
225 // available for future dynamic libraries opened. This is currently used by
226 // loading LLVM and then making its symbols available for other dynamic
228 let lib = DynamicLibrary::open_global_now(path).unwrap_or_else(|err| {
229 let err = format!("couldn't load codegen backend {:?}: {:?}", path, err);
230 early_error(ErrorOutputType::default(), &err);
233 match lib.symbol("__rustc_codegen_backend") {
236 mem::transmute::<*mut u8, _>(f)
239 let err = format!("couldn't load codegen backend as it \
240 doesn't export the `__rustc_codegen_backend` \
242 early_error(ErrorOutputType::default(), &err);
248 pub fn get_codegen_backend(sess: &Session) -> Box<dyn CodegenBackend> {
249 static INIT: Once = ONCE_INIT;
253 static mut LOAD: fn() -> Box<dyn CodegenBackend> = || unreachable!();
256 let codegen_name = sess.opts.debugging_opts.codegen_backend.as_ref()
257 .unwrap_or(&sess.target.target.options.codegen_backend);
258 let backend = match &codegen_name[..] {
260 rustc_codegen_utils::codegen_backend::MetadataOnlyCodegenBackend::boxed
262 filename if filename.contains(".") => {
263 load_backend_from_dylib(filename.as_ref())
265 codegen_name => get_codegen_sysroot(codegen_name),
272 let backend = unsafe { LOAD() };
277 fn get_codegen_sysroot(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> {
278 // For now we only allow this function to be called once as it'll dlopen a
279 // few things, which seems to work best if we only do that once. In
280 // general this assertion never trips due to the once guard in `get_codegen_backend`,
281 // but there's a few manual calls to this function in this file we protect
283 static LOADED: AtomicBool = ATOMIC_BOOL_INIT;
284 assert!(!LOADED.fetch_or(true, Ordering::SeqCst),
285 "cannot load the default codegen backend twice");
287 // When we're compiling this library with `--test` it'll run as a binary but
288 // not actually exercise much functionality. As a result most of the logic
289 // here is defunkt (it assumes we're a dynamic library in a sysroot) so
290 // let's just return a dummy creation function which won't be used in
293 return rustc_codegen_utils::codegen_backend::MetadataOnlyCodegenBackend::boxed
296 let target = session::config::host_triple();
297 // get target libdir path based on executable binary path
298 let sysroot = filesearch::get_or_default_sysroot();
299 let mut libdir_candidates = vec![filesearch::make_target_lib_path(&sysroot, &target)];
300 let path = current_dll_path()
301 .and_then(|s| s.canonicalize().ok());
302 if let Some(dll) = path {
303 // use `parent` once to chop off the file name
304 if let Some(path) = dll.parent() {
305 // The original `path` pointed at the `rustc_driver` crate's dll.
306 // Now that dll should only be in one of two locations. The first is
307 // in the compiler's libdir, for example `$sysroot/$libdir/*.dll`. The
308 // other is the target's libdir, for example
309 // `$sysroot/$libdir/rustlib/$target/lib/*.dll`.
311 // We don't know which, so let's assume that if our `path` above
312 // doesn't end in `$target` we *could* be in the main libdir, and always
313 // assume that we may be in the target libdir.
314 libdir_candidates.push(path.to_owned());
316 if !path.parent().map_or(false, |p| p.ends_with(target)) {
317 libdir_candidates.push(path.join(filesearch::target_lib_path(target)));
322 let sysroot = libdir_candidates.iter()
324 debug!("Trying target libdir: {}", libdir.display());
325 libdir.with_file_name(
326 option_env!("CFG_CODEGEN_BACKENDS_DIR").unwrap_or("codegen-backends"))
329 info!("codegen backend candidate: {}", f.display());
333 let sysroot = sysroot.unwrap_or_else(|| {
334 let candidates = libdir_candidates.iter()
335 .map(|p| p.display().to_string())
338 let err = format!("failed to find a `codegen-backends` folder \
339 in the libdir candidates:\n* {}", candidates);
340 early_error(ErrorOutputType::default(), &err);
342 info!("probing {} for a codegen backend", sysroot.display());
344 let d = sysroot.read_dir().unwrap_or_else(|e| {
345 let err = format!("failed to load default codegen backend, couldn't \
346 read `{}`: {}", sysroot.display(), e);
347 early_error(ErrorOutputType::default(), &err);
350 let mut file: Option<PathBuf> = None;
352 let expected_name = format!("rustc_codegen_llvm-{}", backend_name);
353 for entry in d.filter_map(|e| e.ok()) {
354 let path = entry.path();
355 let filename = match path.file_name().and_then(|s| s.to_str()) {
359 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
362 let name = &filename[DLL_PREFIX.len() .. filename.len() - DLL_SUFFIX.len()];
363 if name != expected_name {
366 if let Some(ref prev) = file {
367 let err = format!("duplicate codegen backends found\n\
370 ", prev.display(), path.display());
371 early_error(ErrorOutputType::default(), &err);
373 file = Some(path.clone());
377 Some(ref s) => return load_backend_from_dylib(s),
379 let err = format!("failed to load default codegen backend for `{}`, \
380 no appropriate codegen dylib found in `{}`",
381 backend_name, sysroot.display());
382 early_error(ErrorOutputType::default(), &err);
387 fn current_dll_path() -> Option<PathBuf> {
388 use std::ffi::{OsStr, CStr};
389 use std::os::unix::prelude::*;
392 let addr = current_dll_path as usize as *mut _;
393 let mut info = mem::zeroed();
394 if libc::dladdr(addr, &mut info) == 0 {
395 info!("dladdr failed");
398 if info.dli_fname.is_null() {
399 info!("dladdr returned null pointer");
402 let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
403 let os = OsStr::from_bytes(bytes);
404 Some(PathBuf::from(os))
409 fn current_dll_path() -> Option<PathBuf> {
410 use std::ffi::OsString;
411 use std::os::windows::prelude::*;
414 fn GetModuleHandleExW(dwFlags: u32,
416 phModule: *mut usize) -> i32;
417 fn GetModuleFileNameW(hModule: usize,
418 lpFilename: *mut u16,
422 const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS: u32 = 0x00000004;
426 let r = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
427 current_dll_path as usize,
430 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
433 let mut space = Vec::with_capacity(1024);
434 let r = GetModuleFileNameW(module,
436 space.capacity() as u32);
438 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
442 if r >= space.capacity() {
443 info!("our buffer was too small? {}",
444 io::Error::last_os_error());
448 let os = OsString::from_wide(&space);
449 Some(PathBuf::from(os))
454 // Parse args and run the compiler. This is the primary entry point for rustc.
455 // See comments on CompilerCalls below for details about the callbacks argument.
456 // The FileLoader provides a way to load files from sources other than the file system.
457 pub fn run_compiler<'a>(args: &[String],
458 callbacks: Box<dyn CompilerCalls<'a> + sync::Send + 'a>,
459 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
460 emitter_dest: Option<Box<dyn Write + Send>>)
461 -> (CompileResult, Option<Session>)
463 let matches = match handle_options(args) {
464 Some(matches) => matches,
465 None => return (Ok(()), None),
468 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
470 driver::spawn_thread_pool(sopts, |sopts| {
471 run_compiler_with_pool(matches, sopts, cfg, callbacks, file_loader, emitter_dest)
475 fn run_compiler_with_pool<'a>(
476 matches: getopts::Matches,
477 sopts: config::Options,
478 cfg: ast::CrateConfig,
479 mut callbacks: Box<dyn CompilerCalls<'a> + sync::Send + 'a>,
480 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
481 emitter_dest: Option<Box<dyn Write + Send>>
482 ) -> (CompileResult, Option<Session>) {
483 macro_rules! do_or_return {($expr: expr, $sess: expr) => {
485 Compilation::Stop => return (Ok(()), $sess),
486 Compilation::Continue => {}
490 let descriptions = diagnostics_registry();
492 do_or_return!(callbacks.early_callback(&matches,
499 let (odir, ofile) = make_output(&matches);
500 let (input, input_file_path, input_err) = match make_input(&matches.free) {
501 Some((input, input_file_path, input_err)) => {
502 let (input, input_file_path) = callbacks.some_input(input, input_file_path);
503 (input, input_file_path, input_err)
505 None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) {
506 Some((input, input_file_path)) => (input, input_file_path, None),
507 None => return (Ok(()), None),
511 let loader = file_loader.unwrap_or(box RealFileLoader);
512 let source_map = Lrc::new(SourceMap::with_file_loader(loader, sopts.file_path_mapping()));
513 let mut sess = session::build_session_with_source_map(
514 sopts, input_file_path.clone(), descriptions, source_map, emitter_dest,
517 if let Some(err) = input_err {
518 // Immediately stop compilation if there was an issue reading
519 // the input (for example if the input stream is not UTF-8).
520 sess.err(&err.to_string());
521 return (Err(CompileIncomplete::Stopped), Some(sess));
524 let codegen_backend = get_codegen_backend(&sess);
526 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
528 let mut cfg = config::build_configuration(&sess, cfg);
529 target_features::add_configuration(&mut cfg, &sess, &*codegen_backend);
530 sess.parse_sess.config = cfg;
533 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
535 let cstore = CStore::new(codegen_backend.metadata_loader());
537 do_or_return!(callbacks.late_callback(&*codegen_backend,
543 &ofile), Some(sess));
545 let _sess_abort_error = OnDrop(|| sess.diagnostic().print_error_count());
547 let control = callbacks.build_controller(&sess, &matches);
549 driver::compile_input(codegen_backend,
564 pub fn set_sigpipe_handler() {
566 // Set the SIGPIPE signal handler, so that an EPIPE
567 // will cause rustc to terminate, as expected.
568 assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
573 pub fn set_sigpipe_handler() {}
575 // Extract output directory and file from matches.
576 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
577 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
578 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
582 // Extract input (string or file and optional path) from matches.
583 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
584 if free_matches.len() == 1 {
585 let ifile = &free_matches[0];
587 let mut src = String::new();
588 let err = if io::stdin().read_to_string(&mut src).is_err() {
589 Some(io::Error::new(io::ErrorKind::InvalidData,
590 "couldn't read from stdin, as it did not contain valid UTF-8"))
594 Some((Input::Str { name: FileName::anon_source_code(&src), input: src },
597 Some((Input::File(PathBuf::from(ifile)),
598 Some(PathBuf::from(ifile)), None))
605 fn parse_pretty(sess: &Session,
606 matches: &getopts::Matches)
607 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
608 let pretty = if sess.opts.debugging_opts.unstable_options {
609 matches.opt_default("pretty", "normal").map(|a| {
610 // stable pretty-print variants only
611 pretty::parse_pretty(sess, &a, false)
617 if pretty.is_none() {
618 sess.opts.debugging_opts.unpretty.as_ref().map(|a| {
619 // extended with unstable pretty-print variants
620 pretty::parse_pretty(sess, &a, true)
627 // Whether to stop or continue compilation.
628 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
629 pub enum Compilation {
635 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
637 Compilation::Stop => Compilation::Stop,
638 Compilation::Continue => next(),
643 /// A trait for customizing the compilation process. Offers a number of hooks for
644 /// executing custom code or customizing input.
645 pub trait CompilerCalls<'a> {
646 /// Hook for a callback early in the process of handling arguments. This will
647 /// be called straight after options have been parsed but before anything
648 /// else (e.g., selecting input and output).
649 fn early_callback(&mut self,
650 _: &getopts::Matches,
652 _: &ast::CrateConfig,
653 _: &errors::registry::Registry,
656 Compilation::Continue
659 /// Hook for a callback late in the process of handling arguments. This will
660 /// be called just before actual compilation starts (and before build_controller
661 /// is called), after all arguments etc. have been completely handled.
662 fn late_callback(&mut self,
663 _: &dyn CodegenBackend,
664 _: &getopts::Matches,
671 Compilation::Continue
674 /// Called after we extract the input from the arguments. Gives the implementer
675 /// an opportunity to change the inputs or to add some custom input handling.
676 /// The default behaviour is to simply pass through the inputs.
677 fn some_input(&mut self,
679 input_path: Option<PathBuf>)
680 -> (Input, Option<PathBuf>) {
684 /// Called after we extract the input from the arguments if there is no valid
685 /// input. Gives the implementer an opportunity to supply alternate input (by
686 /// returning a Some value) or to add custom behaviour for this error such as
687 /// emitting error messages. Returning None will cause compilation to stop
689 fn no_input(&mut self,
690 _: &getopts::Matches,
692 _: &ast::CrateConfig,
695 _: &errors::registry::Registry)
696 -> Option<(Input, Option<PathBuf>)> {
700 // Create a CompilController struct for controlling the behaviour of
706 ) -> CompileController<'a>;
709 /// CompilerCalls instance for a regular rustc build.
710 #[derive(Copy, Clone)]
711 pub struct RustcDefaultCalls;
713 // FIXME remove these and use winapi 0.3 instead
714 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
716 fn stdout_isatty() -> bool {
717 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
721 fn stdout_isatty() -> bool {
724 type HANDLE = *mut u8;
725 type LPDWORD = *mut u32;
726 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
728 fn GetStdHandle(which: DWORD) -> HANDLE;
729 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
732 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
734 GetConsoleMode(handle, &mut out) != 0
738 fn handle_explain(code: &str,
739 descriptions: &errors::registry::Registry,
740 output: ErrorOutputType) {
741 let normalised = if code.starts_with("E") {
744 format!("E{0:0>4}", code)
746 match descriptions.find_description(&normalised) {
747 Some(ref description) => {
748 let mut is_in_code_block = false;
749 let mut text = String::new();
751 // Slice off the leading newline and print.
752 for line in description[1..].lines() {
753 let indent_level = line.find(|c: char| !c.is_whitespace())
754 .unwrap_or_else(|| line.len());
755 let dedented_line = &line[indent_level..];
756 if dedented_line.starts_with("```") {
757 is_in_code_block = !is_in_code_block;
758 text.push_str(&line[..(indent_level+3)]);
759 } else if is_in_code_block && dedented_line.starts_with("# ") {
768 show_content_with_pager(&text);
774 early_error(output, &format!("no extended information for {}", code));
779 fn show_content_with_pager(content: &String) {
780 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
781 OsString::from("more.com")
783 OsString::from("less")
786 let mut fallback_to_println = false;
788 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
790 if let Some(pipe) = pager.stdin.as_mut() {
791 if pipe.write_all(content.as_bytes()).is_err() {
792 fallback_to_println = true;
796 if pager.wait().is_err() {
797 fallback_to_println = true;
801 fallback_to_println = true;
805 // If pager fails for whatever reason, we should still print the content
806 // to standard output
807 if fallback_to_println {
808 print!("{}", content);
812 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
813 fn early_callback(&mut self,
814 matches: &getopts::Matches,
816 _: &ast::CrateConfig,
817 descriptions: &errors::registry::Registry,
818 output: ErrorOutputType)
820 if let Some(ref code) = matches.opt_str("explain") {
821 handle_explain(code, descriptions, output);
822 return Compilation::Stop;
825 Compilation::Continue
828 fn no_input(&mut self,
829 matches: &getopts::Matches,
830 sopts: &config::Options,
831 cfg: &ast::CrateConfig,
832 odir: &Option<PathBuf>,
833 ofile: &Option<PathBuf>,
834 descriptions: &errors::registry::Registry)
835 -> Option<(Input, Option<PathBuf>)> {
836 match matches.free.len() {
838 let mut sess = build_session(sopts.clone(),
840 descriptions.clone());
841 if sopts.describe_lints {
842 let mut ls = lint::LintStore::new();
843 rustc_lint::register_builtins(&mut ls, Some(&sess));
844 describe_lints(&sess, &ls, false);
847 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
848 let mut cfg = config::build_configuration(&sess, cfg.clone());
849 let codegen_backend = get_codegen_backend(&sess);
850 target_features::add_configuration(&mut cfg, &sess, &*codegen_backend);
851 sess.parse_sess.config = cfg;
852 let should_stop = RustcDefaultCalls::print_crate_info(
860 if should_stop == Compilation::Stop {
863 early_error(sopts.error_format, "no input filename given");
865 1 => panic!("make_input should have provided valid inputs"),
866 _ => early_error(sopts.error_format, "multiple input filenames provided"),
870 fn late_callback(&mut self,
871 codegen_backend: &dyn CodegenBackend,
872 matches: &getopts::Matches,
876 odir: &Option<PathBuf>,
877 ofile: &Option<PathBuf>)
879 RustcDefaultCalls::print_crate_info(codegen_backend, sess, Some(input), odir, ofile)
880 .and_then(|| RustcDefaultCalls::list_metadata(sess, cstore, matches, input))
883 fn build_controller(self: Box<Self>,
885 matches: &getopts::Matches)
886 -> CompileController<'a> {
887 let mut control = CompileController::basic();
889 control.keep_ast = sess.opts.debugging_opts.keep_ast;
890 control.continue_parse_after_error = sess.opts.debugging_opts.continue_parse_after_error;
892 if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
893 if ppm.needs_ast_map(&opt_uii) {
894 control.after_hir_lowering.stop = Compilation::Stop;
896 control.after_parse.callback = box move |state| {
897 state.krate = Some(pretty::fold_crate(state.session,
898 state.krate.take().unwrap(),
901 control.after_hir_lowering.callback = box move |state| {
902 pretty::print_after_hir_lowering(state.session,
903 state.cstore.unwrap(),
904 state.hir_map.unwrap(),
905 state.analysis.unwrap(),
906 state.resolutions.unwrap(),
908 &state.expanded_crate.take().unwrap(),
909 state.crate_name.unwrap(),
911 state.output_filenames.unwrap(),
916 control.after_parse.stop = Compilation::Stop;
918 control.after_parse.callback = box move |state| {
919 let krate = pretty::fold_crate(state.session, state.krate.take().unwrap(), ppm);
920 pretty::print_after_parsing(state.session,
931 if sess.opts.debugging_opts.parse_only ||
932 sess.opts.debugging_opts.show_span.is_some() ||
933 sess.opts.debugging_opts.ast_json_noexpand {
934 control.after_parse.stop = Compilation::Stop;
937 if sess.opts.debugging_opts.no_analysis ||
938 sess.opts.debugging_opts.ast_json {
939 control.after_hir_lowering.stop = Compilation::Stop;
942 if sess.opts.debugging_opts.save_analysis {
943 enable_save_analysis(&mut control);
946 if sess.print_fuel_crate.is_some() {
947 let old_callback = control.compilation_done.callback;
948 control.compilation_done.callback = box move |state| {
950 let sess = state.session;
951 eprintln!("Fuel used by {}: {}",
952 sess.print_fuel_crate.as_ref().unwrap(),
953 sess.print_fuel.get());
960 pub fn enable_save_analysis(control: &mut CompileController) {
961 control.keep_ast = true;
962 control.after_analysis.callback = box |state| {
963 time(state.session, "save analysis", || {
964 save::process_crate(state.tcx.unwrap(),
965 state.expanded_crate.unwrap(),
966 state.analysis.unwrap(),
967 state.crate_name.unwrap(),
970 DumpHandler::new(state.out_dir,
971 state.crate_name.unwrap()))
974 control.after_analysis.run_callback_on_error = true;
975 control.make_glob_map = resolve::MakeGlobMap::Yes;
978 impl RustcDefaultCalls {
979 pub fn list_metadata(sess: &Session,
981 matches: &getopts::Matches,
984 let r = matches.opt_strs("Z");
985 if r.iter().any(|s| *s == "ls") {
987 &Input::File(ref ifile) => {
988 let path = &(*ifile);
989 let mut v = Vec::new();
990 locator::list_file_metadata(&sess.target.target,
992 &*cstore.metadata_loader,
995 println!("{}", String::from_utf8(v).unwrap());
997 &Input::Str { .. } => {
998 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
1001 return Compilation::Stop;
1004 Compilation::Continue
1008 fn print_crate_info(codegen_backend: &dyn CodegenBackend,
1010 input: Option<&Input>,
1011 odir: &Option<PathBuf>,
1012 ofile: &Option<PathBuf>)
1014 use rustc::session::config::PrintRequest::*;
1015 // PrintRequest::NativeStaticLibs is special - printed during linking
1016 // (empty iterator returns true)
1017 if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
1018 return Compilation::Continue;
1021 let attrs = match input {
1024 let result = parse_crate_attrs(sess, input);
1026 Ok(attrs) => Some(attrs),
1027 Err(mut parse_error) => {
1029 return Compilation::Stop;
1034 for req in &sess.opts.prints {
1037 let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
1039 println!("{}", targets.join("\n"));
1041 Sysroot => println!("{}", sess.sysroot.display()),
1042 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
1043 FileNames | CrateName => {
1044 let input = input.unwrap_or_else(||
1045 early_error(ErrorOutputType::default(), "no input file provided"));
1046 let attrs = attrs.as_ref().unwrap();
1047 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
1048 let id = rustc_codegen_utils::link::find_crate_name(Some(sess), attrs, input);
1049 if *req == PrintRequest::CrateName {
1053 let crate_types = driver::collect_crate_types(sess, attrs);
1054 for &style in &crate_types {
1055 let fname = rustc_codegen_utils::link::filename_for_input(
1061 println!("{}", fname.file_name().unwrap().to_string_lossy());
1065 let allow_unstable_cfg = UnstableFeatures::from_environment()
1066 .is_nightly_build();
1068 let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| {
1069 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
1070 ident: ast::Path::from_ident(ast::Ident::with_empty_ctxt(name)),
1071 node: ast::MetaItemKind::Word,
1075 // Note that crt-static is a specially recognized cfg
1076 // directive that's printed out here as part of
1077 // rust-lang/rust#37406, but in general the
1078 // `target_feature` cfg is gated under
1079 // rust-lang/rust#29717. For now this is just
1080 // specifically allowing the crt-static cfg and that's
1081 // it, this is intended to get into Cargo and then go
1082 // through to build scripts.
1083 let value = value.as_ref().map(|s| s.as_str());
1084 let value = value.as_ref().map(|s| s.as_ref());
1085 if name != "target_feature" || value != Some("crt-static") {
1086 if !allow_unstable_cfg && gated_cfg.is_some() {
1091 if let Some(value) = value {
1092 Some(format!("{}=\"{}\"", name, value))
1094 Some(name.to_string())
1096 }).collect::<Vec<String>>();
1100 println!("{}", cfg);
1103 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
1104 codegen_backend.print(*req, sess);
1106 // Any output here interferes with Cargo's parsing of other printed output
1107 PrintRequest::NativeStaticLibs => {}
1110 return Compilation::Stop;
1114 /// Returns a version string such as "0.12.0-dev".
1115 fn release_str() -> Option<&'static str> {
1116 option_env!("CFG_RELEASE")
1119 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
1120 fn commit_hash_str() -> Option<&'static str> {
1121 option_env!("CFG_VER_HASH")
1124 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
1125 fn commit_date_str() -> Option<&'static str> {
1126 option_env!("CFG_VER_DATE")
1129 /// Prints version information
1130 pub fn version(binary: &str, matches: &getopts::Matches) {
1131 let verbose = matches.opt_present("verbose");
1133 println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
1136 fn unw(x: Option<&str>) -> &str {
1137 x.unwrap_or("unknown")
1139 println!("binary: {}", binary);
1140 println!("commit-hash: {}", unw(commit_hash_str()));
1141 println!("commit-date: {}", unw(commit_date_str()));
1142 println!("host: {}", config::host_triple());
1143 println!("release: {}", unw(release_str()));
1144 get_codegen_sysroot("llvm")().print_version();
1148 fn usage(verbose: bool, include_unstable_options: bool) {
1149 let groups = if verbose {
1150 config::rustc_optgroups()
1152 config::rustc_short_optgroups()
1154 let mut options = getopts::Options::new();
1155 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
1156 (option.apply)(&mut options);
1158 let message = "Usage: rustc [OPTIONS] INPUT";
1159 let nightly_help = if nightly_options::is_nightly_build() {
1160 "\n -Z help Print internal options for debugging rustc"
1164 let verbose_help = if verbose {
1167 "\n --help -v Print the full set of options rustc accepts"
1169 println!("{}\nAdditional help:
1170 -C help Print codegen options
1172 Print 'lint' options and default settings{}{}\n",
1173 options.usage(message),
1178 fn print_wall_help() {
1180 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
1181 default. Use `rustc -W help` to see all available lints. It's more common to put
1182 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
1183 the command line flag directly.
1187 fn describe_lints(sess: &Session, lint_store: &lint::LintStore, loaded_plugins: bool) {
1189 Available lint options:
1190 -W <foo> Warn about <foo>
1194 -F <foo> Forbid <foo> \
1195 (deny <foo> and all attempts to override)
1199 fn sort_lints(sess: &Session, lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
1200 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
1201 // The sort doesn't case-fold but it's doubtful we care.
1202 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess), x.name));
1206 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
1207 -> Vec<(&'static str, Vec<lint::LintId>)> {
1208 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
1209 lints.sort_by_key(|l| l.0);
1213 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
1216 .partition(|&(_, p)| p);
1217 let plugin = sort_lints(sess, plugin);
1218 let builtin = sort_lints(sess, builtin);
1220 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
1223 .partition(|&(.., p)| p);
1224 let plugin_groups = sort_lint_groups(plugin_groups);
1225 let builtin_groups = sort_lint_groups(builtin_groups);
1227 let max_name_len = plugin.iter()
1229 .map(|&s| s.name.chars().count())
1232 let padded = |x: &str| {
1233 let mut s = " ".repeat(max_name_len - x.chars().count());
1238 println!("Lint checks provided by rustc:\n");
1239 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
1240 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
1242 let print_lints = |lints: Vec<&Lint>| {
1244 let name = lint.name_lower().replace("_", "-");
1245 println!(" {} {:7.7} {}",
1247 lint.default_level.as_str(),
1253 print_lints(builtin);
1255 let max_name_len = max("warnings".len(),
1256 plugin_groups.iter()
1257 .chain(&builtin_groups)
1258 .map(|&(s, _)| s.chars().count())
1262 let padded = |x: &str| {
1263 let mut s = " ".repeat(max_name_len - x.chars().count());
1268 println!("Lint groups provided by rustc:\n");
1269 println!(" {} {}", padded("name"), "sub-lints");
1270 println!(" {} {}", padded("----"), "---------");
1271 println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
1273 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
1274 for (name, to) in lints {
1275 let name = name.to_lowercase().replace("_", "-");
1276 let desc = to.into_iter()
1277 .map(|x| x.to_string().replace("_", "-"))
1278 .collect::<Vec<String>>()
1280 println!(" {} {}", padded(&name), desc);
1285 print_lint_groups(builtin_groups);
1287 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
1288 (false, 0, _) | (false, _, 0) => {
1289 println!("Compiler plugins can provide additional lints and lint groups. To see a \
1290 listing of these, re-run `rustc -W help` with a crate filename.");
1292 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
1293 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
1296 println!("Lint checks provided by plugins loaded by this crate:\n");
1297 print_lints(plugin);
1300 println!("Lint groups provided by plugins loaded by this crate:\n");
1301 print_lint_groups(plugin_groups);
1307 fn describe_debug_flags() {
1308 println!("\nAvailable debug options:\n");
1309 print_flag_list("-Z", config::DB_OPTIONS);
1312 fn describe_codegen_flags() {
1313 println!("\nAvailable codegen options:\n");
1314 print_flag_list("-C", config::CG_OPTIONS);
1317 fn print_flag_list<T>(cmdline_opt: &str,
1318 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
1319 let max_len = flag_list.iter()
1320 .map(|&(name, _, opt_type_desc, _)| {
1321 let extra_len = match opt_type_desc {
1325 name.chars().count() + extra_len
1330 for &(name, _, opt_type_desc, desc) in flag_list {
1331 let (width, extra) = match opt_type_desc {
1332 Some(..) => (max_len - 4, "=val"),
1333 None => (max_len, ""),
1335 println!(" {} {:>width$}{} -- {}",
1337 name.replace("_", "-"),
1344 /// Process command line options. Emits messages as appropriate. If compilation
1345 /// should continue, returns a getopts::Matches object parsed from args,
1346 /// otherwise returns None.
1348 /// The compiler's handling of options is a little complicated as it ties into
1349 /// our stability story, and it's even *more* complicated by historical
1350 /// accidents. The current intention of each compiler option is to have one of
1353 /// 1. An option is stable and can be used everywhere.
1354 /// 2. An option is unstable, but was historically allowed on the stable
1356 /// 3. An option is unstable, and can only be used on nightly.
1358 /// Like unstable library and language features, however, unstable options have
1359 /// always required a form of "opt in" to indicate that you're using them. This
1360 /// provides the easy ability to scan a code base to check to see if anything
1361 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1363 /// All options behind `-Z` are considered unstable by default. Other top-level
1364 /// options can also be considered unstable, and they were unlocked through the
1365 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1366 /// instability in both cases, though.
1368 /// So with all that in mind, the comments below have some more detail about the
1369 /// contortions done here to get things to work out correctly.
1370 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
1371 // Throw away the first argument, the name of the binary
1372 let args = &args[1..];
1374 if args.is_empty() {
1375 // user did not write `-v` nor `-Z unstable-options`, so do not
1376 // include that extra information.
1377 usage(false, false);
1381 // Parse with *all* options defined in the compiler, we don't worry about
1382 // option stability here we just want to parse as much as possible.
1383 let mut options = getopts::Options::new();
1384 for option in config::rustc_optgroups() {
1385 (option.apply)(&mut options);
1387 let matches = options.parse(args).unwrap_or_else(|f|
1388 early_error(ErrorOutputType::default(), &f.to_string()));
1390 // For all options we just parsed, we check a few aspects:
1392 // * If the option is stable, we're all good
1393 // * If the option wasn't passed, we're all good
1394 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1395 // ourselves), then we require the `-Z unstable-options` flag to unlock
1396 // this option that was passed.
1397 // * If we're a nightly compiler, then unstable options are now unlocked, so
1398 // we're good to go.
1399 // * Otherwise, if we're a truly unstable option then we generate an error
1400 // (unstable option being used on stable)
1401 // * If we're a historically stable-but-should-be-unstable option then we
1402 // emit a warning that we're going to turn this into an error soon.
1403 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1405 if matches.opt_present("h") || matches.opt_present("help") {
1406 // Only show unstable options in --help if we *really* accept unstable
1407 // options, which catches the case where we got `-Z unstable-options` on
1408 // the stable channel of Rust which was accidentally allowed
1410 usage(matches.opt_present("verbose"),
1411 nightly_options::is_unstable_enabled(&matches));
1415 // Handle the special case of -Wall.
1416 let wall = matches.opt_strs("W");
1417 if wall.iter().any(|x| *x == "all") {
1422 // Don't handle -W help here, because we might first load plugins.
1423 let r = matches.opt_strs("Z");
1424 if r.iter().any(|x| *x == "help") {
1425 describe_debug_flags();
1429 let cg_flags = matches.opt_strs("C");
1431 if cg_flags.iter().any(|x| *x == "help") {
1432 describe_codegen_flags();
1436 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1437 early_warn(ErrorOutputType::default(),
1438 "the --no-stack-check flag is deprecated and does nothing");
1441 if cg_flags.iter().any(|x| *x == "passes=list") {
1442 get_codegen_sysroot("llvm")().print_passes();
1446 if matches.opt_present("version") {
1447 version("rustc", &matches);
1454 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1456 Input::File(ref ifile) => {
1457 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1459 Input::Str { ref name, ref input } => {
1460 parse::parse_crate_attrs_from_source_str(name.clone(),
1467 // Temporarily have stack size set to 32MB to deal with various crates with long method
1468 // chains or deep syntax trees.
1469 // FIXME(oli-obk): get https://github.com/rust-lang/rust/pull/55617 the finish line
1470 const STACK_SIZE: usize = 32 * 1024 * 1024; // 32MB
1472 /// Runs `f` in a suitable thread for running `rustc`; returns a `Result` with either the return
1473 /// value of `f` or -- if a panic occurs -- the panic value.
1475 /// This version applies the given name to the thread. This is used by rustdoc to ensure consistent
1476 /// doctest output across platforms and executions.
1477 pub fn in_named_rustc_thread<F, R>(name: String, f: F) -> Result<R, Box<dyn Any + Send>>
1478 where F: FnOnce() -> R + Send + 'static,
1481 // We need a thread for soundness of thread local storage in rustc. For debugging purposes
1482 // we allow an escape hatch where everything runs on the main thread.
1483 if env::var_os("RUSTC_UNSTABLE_NO_MAIN_THREAD").is_none() {
1484 let mut cfg = thread::Builder::new().name(name);
1486 // If the env is trying to override the stack size then *don't* set it explicitly.
1487 // The libstd thread impl will fetch the `RUST_MIN_STACK` env var itself.
1488 if env::var_os("RUST_MIN_STACK").is_none() {
1489 cfg = cfg.stack_size(STACK_SIZE);
1492 let thread = cfg.spawn(f);
1493 thread.unwrap().join()
1495 let f = panic::AssertUnwindSafe(f);
1496 panic::catch_unwind(f)
1500 /// Runs `f` in a suitable thread for running `rustc`; returns a
1501 /// `Result` with either the return value of `f` or -- if a panic
1502 /// occurs -- the panic value.
1503 pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<dyn Any + Send>>
1504 where F: FnOnce() -> R + Send + 'static,
1507 in_named_rustc_thread("rustc".to_string(), f)
1510 /// Get a list of extra command-line flags provided by the user, as strings.
1512 /// This function is used during ICEs to show more information useful for
1513 /// debugging, since some ICEs only happens with non-default compiler flags
1514 /// (and the users don't always report them).
1515 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1516 let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1518 // Avoid printing help because of empty args. This can suggest the compiler
1519 // itself is not the program root (consider RLS).
1524 let matches = if let Some(matches) = handle_options(&args) {
1530 let mut result = Vec::new();
1531 let mut excluded_cargo_defaults = false;
1532 for flag in ICE_REPORT_COMPILER_FLAGS {
1533 let prefix = if flag.len() == 1 { "-" } else { "--" };
1535 for content in &matches.opt_strs(flag) {
1536 // Split always returns the first element
1537 let name = if let Some(first) = content.split('=').next() {
1543 let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) {
1549 if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
1550 result.push(format!("{}{} {}", prefix, flag, content));
1552 excluded_cargo_defaults = true;
1557 if !result.is_empty() {
1558 Some((result, excluded_cargo_defaults))
1565 pub struct CompilationFailure;
1567 impl Error for CompilationFailure {}
1569 impl Display for CompilationFailure {
1570 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1571 write!(f, "compilation had errors")
1575 /// Run a procedure which will detect panics in the compiler and print nicer
1576 /// error messages rather than just failing the test.
1578 /// The diagnostic emitter yielded to the procedure should be used for reporting
1579 /// errors of the compiler.
1580 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) -> Result<(), CompilationFailure> {
1581 in_rustc_thread(move || {
1583 }).map_err(|value| {
1584 if value.is::<errors::FatalErrorMarker>() {
1587 // Thread panicked without emitting a fatal diagnostic
1591 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
1595 let handler = errors::Handler::with_emitter(true, false, emitter);
1597 // a .span_bug or .bug call has already printed what
1598 // it wants to print.
1599 if !value.is::<errors::ExplicitBug>() {
1600 handler.emit(&MultiSpan::new(),
1602 errors::Level::Bug);
1605 let mut xs: Vec<Cow<'static, str>> = vec![
1606 "the compiler unexpectedly panicked. this is a bug.".into(),
1607 format!("we would appreciate a bug report: {}", BUG_REPORT_URL).into(),
1608 format!("rustc {} running on {}",
1609 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1610 config::host_triple()).into(),
1613 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1614 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1616 if excluded_cargo_defaults {
1617 xs.push("some of the compiler flags provided by cargo are hidden".into());
1622 handler.emit(&MultiSpan::new(),
1624 errors::Level::Note);
1627 panic::resume_unwind(Box::new(errors::FatalErrorMarker));
1632 pub fn diagnostics_registry() -> errors::registry::Registry {
1633 use errors::registry::Registry;
1635 let mut all_errors = Vec::new();
1636 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1637 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1638 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1639 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1640 // FIXME: need to figure out a way to get these back in here
1641 // all_errors.extend_from_slice(get_codegen_backend(sess).diagnostics());
1642 all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1643 all_errors.extend_from_slice(&rustc_passes::DIAGNOSTICS);
1644 all_errors.extend_from_slice(&rustc_plugin::DIAGNOSTICS);
1645 all_errors.extend_from_slice(&rustc_mir::DIAGNOSTICS);
1646 all_errors.extend_from_slice(&syntax::DIAGNOSTICS);
1648 Registry::new(&all_errors)
1651 /// This allows tools to enable rust logging without having to magically match rustc's
1652 /// log crate version
1653 pub fn init_rustc_env_logger() {
1658 init_rustc_env_logger();
1659 let result = run(|| {
1660 let args = env::args_os().enumerate()
1661 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1662 early_error(ErrorOutputType::default(),
1663 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1665 .collect::<Vec<_>>();
1667 Box::new(RustcDefaultCalls),
1671 process::exit(result as i32);