5 //! This API is completely unstable and subject to change.
7 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
8 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
9 html_root_url = "https://doc.rust-lang.org/nightly/")]
11 #![feature(box_syntax)]
12 #![cfg_attr(unix, feature(libc))]
15 #![feature(rustc_diagnostic_macros)]
16 #![feature(slice_sort_by_cached_key)]
17 #![feature(set_stdio)]
20 #![recursion_limit="256"]
23 pub extern crate getopts;
24 extern crate graphviz;
25 extern crate env_logger;
28 extern crate rustc_rayon as rayon;
30 extern crate rustc_allocator;
31 extern crate rustc_target;
32 extern crate rustc_borrowck;
33 extern crate rustc_data_structures;
34 extern crate rustc_errors as errors;
35 extern crate rustc_passes;
36 extern crate rustc_lint;
37 extern crate rustc_plugin;
38 extern crate rustc_privacy;
39 extern crate rustc_incremental;
40 extern crate rustc_metadata;
41 extern crate rustc_mir;
42 extern crate rustc_resolve;
43 extern crate rustc_save_analysis;
44 extern crate rustc_traits;
45 extern crate rustc_codegen_utils;
46 extern crate rustc_typeck;
47 extern crate scoped_tls;
48 extern crate serialize;
49 extern crate smallvec;
53 extern crate syntax_ext;
54 extern crate syntax_pos;
56 use driver::CompileController;
57 use pretty::{PpMode, UserIdentifiedItem};
59 use rustc_resolve as resolve;
60 use rustc_save_analysis as save;
61 use rustc_save_analysis::DumpHandler;
62 use rustc_data_structures::sync::{self, Lrc};
63 use rustc_data_structures::OnDrop;
64 use rustc::session::{self, config, Session, build_session, CompileResult};
65 use rustc::session::CompileIncomplete;
66 use rustc::session::config::{Input, PrintRequest, ErrorOutputType};
67 use rustc::session::config::nightly_options;
68 use rustc::session::filesearch;
69 use rustc::session::{early_error, early_warn};
70 use rustc::lint::Lint;
72 use rustc_metadata::locator;
73 use rustc_metadata::cstore::CStore;
74 use rustc_metadata::dynamic_lib::DynamicLibrary;
75 use rustc::util::common::{time, ErrorReported};
76 use rustc_codegen_utils::codegen_backend::CodegenBackend;
78 use serialize::json::ToJson;
83 use std::default::Default;
84 use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
86 use std::error::Error;
87 use std::ffi::OsString;
88 use std::fmt::{self, Display};
89 use std::io::{self, Read, Write};
92 use std::path::{PathBuf, Path};
93 use std::process::{self, Command, Stdio};
95 use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
96 use std::sync::{Once, ONCE_INIT};
100 use syntax::source_map::{SourceMap, FileLoader, RealFileLoader};
101 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
102 use syntax::parse::{self, PResult};
103 use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
111 mod proc_macro_decls;
113 pub mod target_features {
115 use syntax::symbol::Symbol;
116 use rustc::session::Session;
117 use rustc_codegen_utils::codegen_backend::CodegenBackend;
119 /// Add `target_feature = "..."` cfgs for a variety of platform
120 /// specific features (SSE, NEON etc.).
122 /// This is performed by checking whether a whitelisted set of
123 /// features is available on the target machine, by querying LLVM.
124 pub fn add_configuration(cfg: &mut ast::CrateConfig,
126 codegen_backend: &dyn CodegenBackend) {
127 let tf = Symbol::intern("target_feature");
129 cfg.extend(codegen_backend.target_features(sess).into_iter().map(|feat| (tf, Some(feat))));
131 if sess.crt_static_feature() {
132 cfg.insert((tf, Some(Symbol::intern("crt-static"))));
137 /// Exit status code used for successful compilation and help output.
138 pub const EXIT_SUCCESS: isize = 0;
140 /// Exit status code used for compilation failures and invalid flags.
141 pub const EXIT_FAILURE: isize = 1;
143 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
146 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
148 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
150 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
152 pub fn abort_on_err<T>(result: Result<T, CompileIncomplete>, sess: &Session) -> T {
154 Err(CompileIncomplete::Errored(ErrorReported)) => {
155 sess.abort_if_errors();
156 panic!("error reported but abort_if_errors didn't abort???");
158 Err(CompileIncomplete::Stopped) => {
159 sess.fatal("compilation terminated");
165 pub fn run<F>(run_compiler: F) -> isize
166 where F: FnOnce() -> (CompileResult, Option<Session>) + Send + 'static
168 let result = monitor(move || {
169 syntax::with_globals(|| {
170 let (result, session) = run_compiler();
171 if let Err(CompileIncomplete::Errored(_)) = result {
174 sess.abort_if_errors();
175 panic!("error reported but abort_if_errors didn't abort???");
179 errors::emitter::EmitterWriter::stderr(
180 errors::ColorConfig::Auto,
185 let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
186 handler.emit(&MultiSpan::new(),
187 "aborting due to previous error(s)",
188 errors::Level::Fatal);
189 panic::resume_unwind(Box::new(errors::FatalErrorMarker));
197 Ok(()) => EXIT_SUCCESS,
198 Err(_) => EXIT_FAILURE,
202 fn load_backend_from_dylib(path: &Path) -> fn() -> Box<dyn CodegenBackend> {
203 // Note that we're specifically using `open_global_now` here rather than
204 // `open`, namely we want the behavior on Unix of RTLD_GLOBAL and RTLD_NOW,
205 // where NOW means "bind everything right now" because we don't want
206 // surprises later on and RTLD_GLOBAL allows the symbols to be made
207 // available for future dynamic libraries opened. This is currently used by
208 // loading LLVM and then making its symbols available for other dynamic
210 let lib = DynamicLibrary::open_global_now(path).unwrap_or_else(|err| {
211 let err = format!("couldn't load codegen backend {:?}: {:?}", path, err);
212 early_error(ErrorOutputType::default(), &err);
215 match lib.symbol("__rustc_codegen_backend") {
218 mem::transmute::<*mut u8, _>(f)
221 let err = format!("couldn't load codegen backend as it \
222 doesn't export the `__rustc_codegen_backend` \
224 early_error(ErrorOutputType::default(), &err);
230 pub fn get_codegen_backend(sess: &Session) -> Box<dyn CodegenBackend> {
231 static INIT: Once = ONCE_INIT;
235 static mut LOAD: fn() -> Box<dyn CodegenBackend> = || unreachable!();
238 let codegen_name = sess.opts.debugging_opts.codegen_backend.as_ref()
239 .unwrap_or(&sess.target.target.options.codegen_backend);
240 let backend = match &codegen_name[..] {
242 rustc_codegen_utils::codegen_backend::MetadataOnlyCodegenBackend::boxed
244 filename if filename.contains(".") => {
245 load_backend_from_dylib(filename.as_ref())
247 codegen_name => get_codegen_sysroot(codegen_name),
254 let backend = unsafe { LOAD() };
259 fn get_codegen_sysroot(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> {
260 // For now we only allow this function to be called once as it'll dlopen a
261 // few things, which seems to work best if we only do that once. In
262 // general this assertion never trips due to the once guard in `get_codegen_backend`,
263 // but there's a few manual calls to this function in this file we protect
265 static LOADED: AtomicBool = ATOMIC_BOOL_INIT;
266 assert!(!LOADED.fetch_or(true, Ordering::SeqCst),
267 "cannot load the default codegen backend twice");
269 // When we're compiling this library with `--test` it'll run as a binary but
270 // not actually exercise much functionality. As a result most of the logic
271 // here is defunkt (it assumes we're a dynamic library in a sysroot) so
272 // let's just return a dummy creation function which won't be used in
275 return rustc_codegen_utils::codegen_backend::MetadataOnlyCodegenBackend::boxed
278 let target = session::config::host_triple();
279 // get target libdir path based on executable binary path
280 let sysroot = filesearch::get_or_default_sysroot();
281 let mut libdir_candidates = vec![filesearch::make_target_lib_path(&sysroot, &target)];
282 let path = current_dll_path()
283 .and_then(|s| s.canonicalize().ok());
284 if let Some(dll) = path {
285 // use `parent` once to chop off the file name
286 if let Some(path) = dll.parent() {
287 // The original `path` pointed at the `rustc_driver` crate's dll.
288 // Now that dll should only be in one of two locations. The first is
289 // in the compiler's libdir, for example `$sysroot/$libdir/*.dll`. The
290 // other is the target's libdir, for example
291 // `$sysroot/$libdir/rustlib/$target/lib/*.dll`.
293 // We don't know which, so let's assume that if our `path` above
294 // doesn't end in `$target` we *could* be in the main libdir, and always
295 // assume that we may be in the target libdir.
296 libdir_candidates.push(path.to_owned());
298 if !path.parent().map_or(false, |p| p.ends_with(target)) {
299 libdir_candidates.push(path.join(filesearch::target_lib_path(target)));
304 let sysroot = libdir_candidates.iter()
306 debug!("Trying target libdir: {}", libdir.display());
307 libdir.with_file_name(
308 option_env!("CFG_CODEGEN_BACKENDS_DIR").unwrap_or("codegen-backends"))
311 info!("codegen backend candidate: {}", f.display());
315 let sysroot = sysroot.unwrap_or_else(|| {
316 let candidates = libdir_candidates.iter()
317 .map(|p| p.display().to_string())
320 let err = format!("failed to find a `codegen-backends` folder \
321 in the libdir candidates:\n* {}", candidates);
322 early_error(ErrorOutputType::default(), &err);
324 info!("probing {} for a codegen backend", sysroot.display());
326 let d = sysroot.read_dir().unwrap_or_else(|e| {
327 let err = format!("failed to load default codegen backend, couldn't \
328 read `{}`: {}", sysroot.display(), e);
329 early_error(ErrorOutputType::default(), &err);
332 let mut file: Option<PathBuf> = None;
334 let expected_name = format!("rustc_codegen_llvm-{}", backend_name);
335 for entry in d.filter_map(|e| e.ok()) {
336 let path = entry.path();
337 let filename = match path.file_name().and_then(|s| s.to_str()) {
341 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
344 let name = &filename[DLL_PREFIX.len() .. filename.len() - DLL_SUFFIX.len()];
345 if name != expected_name {
348 if let Some(ref prev) = file {
349 let err = format!("duplicate codegen backends found\n\
352 ", prev.display(), path.display());
353 early_error(ErrorOutputType::default(), &err);
355 file = Some(path.clone());
359 Some(ref s) => return load_backend_from_dylib(s),
361 let err = format!("failed to load default codegen backend for `{}`, \
362 no appropriate codegen dylib found in `{}`",
363 backend_name, sysroot.display());
364 early_error(ErrorOutputType::default(), &err);
369 fn current_dll_path() -> Option<PathBuf> {
370 use std::ffi::{OsStr, CStr};
371 use std::os::unix::prelude::*;
374 let addr = current_dll_path as usize as *mut _;
375 let mut info = mem::zeroed();
376 if libc::dladdr(addr, &mut info) == 0 {
377 info!("dladdr failed");
380 if info.dli_fname.is_null() {
381 info!("dladdr returned null pointer");
384 let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
385 let os = OsStr::from_bytes(bytes);
386 Some(PathBuf::from(os))
391 fn current_dll_path() -> Option<PathBuf> {
392 use std::ffi::OsString;
393 use std::os::windows::prelude::*;
396 fn GetModuleHandleExW(dwFlags: u32,
398 phModule: *mut usize) -> i32;
399 fn GetModuleFileNameW(hModule: usize,
400 lpFilename: *mut u16,
404 const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS: u32 = 0x00000004;
408 let r = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
409 current_dll_path as usize,
412 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
415 let mut space = Vec::with_capacity(1024);
416 let r = GetModuleFileNameW(module,
418 space.capacity() as u32);
420 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
424 if r >= space.capacity() {
425 info!("our buffer was too small? {}",
426 io::Error::last_os_error());
430 let os = OsString::from_wide(&space);
431 Some(PathBuf::from(os))
436 // Parse args and run the compiler. This is the primary entry point for rustc.
437 // See comments on CompilerCalls below for details about the callbacks argument.
438 // The FileLoader provides a way to load files from sources other than the file system.
439 pub fn run_compiler<'a>(args: &[String],
440 callbacks: Box<dyn CompilerCalls<'a> + sync::Send + 'a>,
441 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
442 emitter_dest: Option<Box<dyn Write + Send>>)
443 -> (CompileResult, Option<Session>)
445 let matches = match handle_options(args) {
446 Some(matches) => matches,
447 None => return (Ok(()), None),
450 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
452 driver::spawn_thread_pool(sopts, |sopts| {
453 run_compiler_with_pool(matches, sopts, cfg, callbacks, file_loader, emitter_dest)
457 fn run_compiler_with_pool<'a>(
458 matches: getopts::Matches,
459 sopts: config::Options,
460 cfg: ast::CrateConfig,
461 mut callbacks: Box<dyn CompilerCalls<'a> + sync::Send + 'a>,
462 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
463 emitter_dest: Option<Box<dyn Write + Send>>
464 ) -> (CompileResult, Option<Session>) {
465 macro_rules! do_or_return {($expr: expr, $sess: expr) => {
467 Compilation::Stop => return (Ok(()), $sess),
468 Compilation::Continue => {}
472 let descriptions = diagnostics_registry();
474 do_or_return!(callbacks.early_callback(&matches,
481 let (odir, ofile) = make_output(&matches);
482 let (input, input_file_path, input_err) = match make_input(&matches.free) {
483 Some((input, input_file_path, input_err)) => {
484 let (input, input_file_path) = callbacks.some_input(input, input_file_path);
485 (input, input_file_path, input_err)
487 None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) {
488 Some((input, input_file_path)) => (input, input_file_path, None),
489 None => return (Ok(()), None),
493 let loader = file_loader.unwrap_or(box RealFileLoader);
494 let source_map = Lrc::new(SourceMap::with_file_loader(loader, sopts.file_path_mapping()));
495 let mut sess = session::build_session_with_source_map(
496 sopts, input_file_path.clone(), descriptions, source_map, emitter_dest,
499 if let Some(err) = input_err {
500 // Immediately stop compilation if there was an issue reading
501 // the input (for example if the input stream is not UTF-8).
502 sess.err(&err.to_string());
503 return (Err(CompileIncomplete::Stopped), Some(sess));
506 let codegen_backend = get_codegen_backend(&sess);
508 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
510 let mut cfg = config::build_configuration(&sess, cfg);
511 target_features::add_configuration(&mut cfg, &sess, &*codegen_backend);
512 sess.parse_sess.config = cfg;
515 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
517 let cstore = CStore::new(codegen_backend.metadata_loader());
519 do_or_return!(callbacks.late_callback(&*codegen_backend,
525 &ofile), Some(sess));
527 let _sess_abort_error = OnDrop(|| sess.diagnostic().print_error_count());
529 let control = callbacks.build_controller(&sess, &matches);
531 driver::compile_input(codegen_backend,
546 pub fn set_sigpipe_handler() {
548 // Set the SIGPIPE signal handler, so that an EPIPE
549 // will cause rustc to terminate, as expected.
550 assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
555 pub fn set_sigpipe_handler() {}
557 // Extract output directory and file from matches.
558 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
559 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
560 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
564 // Extract input (string or file and optional path) from matches.
565 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
566 if free_matches.len() == 1 {
567 let ifile = &free_matches[0];
569 let mut src = String::new();
570 let err = if io::stdin().read_to_string(&mut src).is_err() {
571 Some(io::Error::new(io::ErrorKind::InvalidData,
572 "couldn't read from stdin, as it did not contain valid UTF-8"))
576 Some((Input::Str { name: FileName::anon_source_code(&src), input: src },
579 Some((Input::File(PathBuf::from(ifile)),
580 Some(PathBuf::from(ifile)), None))
587 fn parse_pretty(sess: &Session,
588 matches: &getopts::Matches)
589 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
590 let pretty = if sess.opts.debugging_opts.unstable_options {
591 matches.opt_default("pretty", "normal").map(|a| {
592 // stable pretty-print variants only
593 pretty::parse_pretty(sess, &a, false)
599 if pretty.is_none() {
600 sess.opts.debugging_opts.unpretty.as_ref().map(|a| {
601 // extended with unstable pretty-print variants
602 pretty::parse_pretty(sess, &a, true)
609 // Whether to stop or continue compilation.
610 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
611 pub enum Compilation {
617 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
619 Compilation::Stop => Compilation::Stop,
620 Compilation::Continue => next(),
625 /// A trait for customizing the compilation process. Offers a number of hooks for
626 /// executing custom code or customizing input.
627 pub trait CompilerCalls<'a> {
628 /// Hook for a callback early in the process of handling arguments. This will
629 /// be called straight after options have been parsed but before anything
630 /// else (e.g., selecting input and output).
631 fn early_callback(&mut self,
632 _: &getopts::Matches,
634 _: &ast::CrateConfig,
635 _: &errors::registry::Registry,
638 Compilation::Continue
641 /// Hook for a callback late in the process of handling arguments. This will
642 /// be called just before actual compilation starts (and before build_controller
643 /// is called), after all arguments etc. have been completely handled.
644 fn late_callback(&mut self,
645 _: &dyn CodegenBackend,
646 _: &getopts::Matches,
653 Compilation::Continue
656 /// Called after we extract the input from the arguments. Gives the implementer
657 /// an opportunity to change the inputs or to add some custom input handling.
658 /// The default behaviour is to simply pass through the inputs.
659 fn some_input(&mut self,
661 input_path: Option<PathBuf>)
662 -> (Input, Option<PathBuf>) {
666 /// Called after we extract the input from the arguments if there is no valid
667 /// input. Gives the implementer an opportunity to supply alternate input (by
668 /// returning a Some value) or to add custom behaviour for this error such as
669 /// emitting error messages. Returning None will cause compilation to stop
671 fn no_input(&mut self,
672 _: &getopts::Matches,
674 _: &ast::CrateConfig,
677 _: &errors::registry::Registry)
678 -> Option<(Input, Option<PathBuf>)> {
682 // Create a CompilController struct for controlling the behaviour of
688 ) -> CompileController<'a>;
691 /// CompilerCalls instance for a regular rustc build.
692 #[derive(Copy, Clone)]
693 pub struct RustcDefaultCalls;
695 // FIXME remove these and use winapi 0.3 instead
696 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
698 fn stdout_isatty() -> bool {
699 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
703 fn stdout_isatty() -> bool {
706 type HANDLE = *mut u8;
707 type LPDWORD = *mut u32;
708 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
710 fn GetStdHandle(which: DWORD) -> HANDLE;
711 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
714 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
716 GetConsoleMode(handle, &mut out) != 0
720 fn handle_explain(code: &str,
721 descriptions: &errors::registry::Registry,
722 output: ErrorOutputType) {
723 let normalised = if code.starts_with("E") {
726 format!("E{0:0>4}", code)
728 match descriptions.find_description(&normalised) {
729 Some(ref description) => {
730 let mut is_in_code_block = false;
731 let mut text = String::new();
733 // Slice off the leading newline and print.
734 for line in description[1..].lines() {
735 let indent_level = line.find(|c: char| !c.is_whitespace())
736 .unwrap_or_else(|| line.len());
737 let dedented_line = &line[indent_level..];
738 if dedented_line.starts_with("```") {
739 is_in_code_block = !is_in_code_block;
740 text.push_str(&line[..(indent_level+3)]);
741 } else if is_in_code_block && dedented_line.starts_with("# ") {
750 show_content_with_pager(&text);
756 early_error(output, &format!("no extended information for {}", code));
761 fn show_content_with_pager(content: &String) {
762 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
763 OsString::from("more.com")
765 OsString::from("less")
768 let mut fallback_to_println = false;
770 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
772 if let Some(pipe) = pager.stdin.as_mut() {
773 if pipe.write_all(content.as_bytes()).is_err() {
774 fallback_to_println = true;
778 if pager.wait().is_err() {
779 fallback_to_println = true;
783 fallback_to_println = true;
787 // If pager fails for whatever reason, we should still print the content
788 // to standard output
789 if fallback_to_println {
790 print!("{}", content);
794 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
795 fn early_callback(&mut self,
796 matches: &getopts::Matches,
798 _: &ast::CrateConfig,
799 descriptions: &errors::registry::Registry,
800 output: ErrorOutputType)
802 if let Some(ref code) = matches.opt_str("explain") {
803 handle_explain(code, descriptions, output);
804 return Compilation::Stop;
807 Compilation::Continue
810 fn no_input(&mut self,
811 matches: &getopts::Matches,
812 sopts: &config::Options,
813 cfg: &ast::CrateConfig,
814 odir: &Option<PathBuf>,
815 ofile: &Option<PathBuf>,
816 descriptions: &errors::registry::Registry)
817 -> Option<(Input, Option<PathBuf>)> {
818 match matches.free.len() {
820 let mut sess = build_session(sopts.clone(),
822 descriptions.clone());
823 if sopts.describe_lints {
824 let mut ls = lint::LintStore::new();
825 rustc_lint::register_builtins(&mut ls, Some(&sess));
826 describe_lints(&sess, &ls, false);
829 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
830 let mut cfg = config::build_configuration(&sess, cfg.clone());
831 let codegen_backend = get_codegen_backend(&sess);
832 target_features::add_configuration(&mut cfg, &sess, &*codegen_backend);
833 sess.parse_sess.config = cfg;
834 let should_stop = RustcDefaultCalls::print_crate_info(
842 if should_stop == Compilation::Stop {
845 early_error(sopts.error_format, "no input filename given");
847 1 => panic!("make_input should have provided valid inputs"),
848 _ => early_error(sopts.error_format, "multiple input filenames provided"),
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 state.krate = Some(pretty::fold_crate(state.session,
880 state.krate.take().unwrap(),
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.analysis.unwrap(),
888 state.resolutions.unwrap(),
890 &state.expanded_crate.take().unwrap(),
891 state.crate_name.unwrap(),
893 state.output_filenames.unwrap(),
898 control.after_parse.stop = Compilation::Stop;
900 control.after_parse.callback = box move |state| {
901 let krate = pretty::fold_crate(state.session, state.krate.take().unwrap(), 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.get());
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.analysis.unwrap(),
949 state.crate_name.unwrap(),
952 DumpHandler::new(state.out_dir,
953 state.crate_name.unwrap()))
956 control.after_analysis.run_callback_on_error = true;
957 control.make_glob_map = resolve::MakeGlobMap::Yes;
960 impl RustcDefaultCalls {
961 pub fn list_metadata(sess: &Session,
963 matches: &getopts::Matches,
966 let r = matches.opt_strs("Z");
967 if r.iter().any(|s| *s == "ls") {
969 &Input::File(ref ifile) => {
970 let path = &(*ifile);
971 let mut v = Vec::new();
972 locator::list_file_metadata(&sess.target.target,
974 &*cstore.metadata_loader,
977 println!("{}", String::from_utf8(v).unwrap());
979 &Input::Str { .. } => {
980 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
983 return Compilation::Stop;
986 Compilation::Continue
990 fn print_crate_info(codegen_backend: &dyn CodegenBackend,
992 input: Option<&Input>,
993 odir: &Option<PathBuf>,
994 ofile: &Option<PathBuf>)
996 use rustc::session::config::PrintRequest::*;
997 // PrintRequest::NativeStaticLibs is special - printed during linking
998 // (empty iterator returns true)
999 if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
1000 return Compilation::Continue;
1003 let attrs = match input {
1006 let result = parse_crate_attrs(sess, input);
1008 Ok(attrs) => Some(attrs),
1009 Err(mut parse_error) => {
1011 return Compilation::Stop;
1016 for req in &sess.opts.prints {
1019 let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
1021 println!("{}", targets.join("\n"));
1023 Sysroot => println!("{}", sess.sysroot.display()),
1024 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
1025 FileNames | CrateName => {
1026 let input = input.unwrap_or_else(||
1027 early_error(ErrorOutputType::default(), "no input file provided"));
1028 let attrs = attrs.as_ref().unwrap();
1029 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
1030 let id = rustc_codegen_utils::link::find_crate_name(Some(sess), attrs, input);
1031 if *req == PrintRequest::CrateName {
1035 let crate_types = driver::collect_crate_types(sess, attrs);
1036 for &style in &crate_types {
1037 let fname = rustc_codegen_utils::link::filename_for_input(
1043 println!("{}", fname.file_name().unwrap().to_string_lossy());
1047 let allow_unstable_cfg = UnstableFeatures::from_environment()
1048 .is_nightly_build();
1050 let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| {
1051 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
1052 ident: ast::Path::from_ident(ast::Ident::with_empty_ctxt(name)),
1053 node: ast::MetaItemKind::Word,
1057 // Note that crt-static is a specially recognized cfg
1058 // directive that's printed out here as part of
1059 // rust-lang/rust#37406, but in general the
1060 // `target_feature` cfg is gated under
1061 // rust-lang/rust#29717. For now this is just
1062 // specifically allowing the crt-static cfg and that's
1063 // it, this is intended to get into Cargo and then go
1064 // through to build scripts.
1065 let value = value.as_ref().map(|s| s.as_str());
1066 let value = value.as_ref().map(|s| s.as_ref());
1067 if name != "target_feature" || value != Some("crt-static") {
1068 if !allow_unstable_cfg && gated_cfg.is_some() {
1073 if let Some(value) = value {
1074 Some(format!("{}=\"{}\"", name, value))
1076 Some(name.to_string())
1078 }).collect::<Vec<String>>();
1082 println!("{}", cfg);
1085 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
1086 codegen_backend.print(*req, sess);
1088 // Any output here interferes with Cargo's parsing of other printed output
1089 PrintRequest::NativeStaticLibs => {}
1092 return Compilation::Stop;
1096 /// Returns a version string such as "0.12.0-dev".
1097 fn release_str() -> Option<&'static str> {
1098 option_env!("CFG_RELEASE")
1101 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
1102 fn commit_hash_str() -> Option<&'static str> {
1103 option_env!("CFG_VER_HASH")
1106 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
1107 fn commit_date_str() -> Option<&'static str> {
1108 option_env!("CFG_VER_DATE")
1111 /// Prints version information
1112 pub fn version(binary: &str, matches: &getopts::Matches) {
1113 let verbose = matches.opt_present("verbose");
1115 println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
1118 fn unw(x: Option<&str>) -> &str {
1119 x.unwrap_or("unknown")
1121 println!("binary: {}", binary);
1122 println!("commit-hash: {}", unw(commit_hash_str()));
1123 println!("commit-date: {}", unw(commit_date_str()));
1124 println!("host: {}", config::host_triple());
1125 println!("release: {}", unw(release_str()));
1126 get_codegen_sysroot("llvm")().print_version();
1130 fn usage(verbose: bool, include_unstable_options: bool) {
1131 let groups = if verbose {
1132 config::rustc_optgroups()
1134 config::rustc_short_optgroups()
1136 let mut options = getopts::Options::new();
1137 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
1138 (option.apply)(&mut options);
1140 let message = "Usage: rustc [OPTIONS] INPUT";
1141 let nightly_help = if nightly_options::is_nightly_build() {
1142 "\n -Z help Print internal options for debugging rustc"
1146 let verbose_help = if verbose {
1149 "\n --help -v Print the full set of options rustc accepts"
1151 println!("{}\nAdditional help:
1152 -C help Print codegen options
1154 Print 'lint' options and default settings{}{}\n",
1155 options.usage(message),
1160 fn print_wall_help() {
1162 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
1163 default. Use `rustc -W help` to see all available lints. It's more common to put
1164 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
1165 the command line flag directly.
1169 fn describe_lints(sess: &Session, lint_store: &lint::LintStore, loaded_plugins: bool) {
1171 Available lint options:
1172 -W <foo> Warn about <foo>
1176 -F <foo> Forbid <foo> \
1177 (deny <foo> and all attempts to override)
1181 fn sort_lints(sess: &Session, lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
1182 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
1183 // The sort doesn't case-fold but it's doubtful we care.
1184 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess), x.name));
1188 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
1189 -> Vec<(&'static str, Vec<lint::LintId>)> {
1190 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
1191 lints.sort_by_key(|l| l.0);
1195 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
1198 .partition(|&(_, p)| p);
1199 let plugin = sort_lints(sess, plugin);
1200 let builtin = sort_lints(sess, builtin);
1202 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
1205 .partition(|&(.., p)| p);
1206 let plugin_groups = sort_lint_groups(plugin_groups);
1207 let builtin_groups = sort_lint_groups(builtin_groups);
1209 let max_name_len = plugin.iter()
1211 .map(|&s| s.name.chars().count())
1214 let padded = |x: &str| {
1215 let mut s = " ".repeat(max_name_len - x.chars().count());
1220 println!("Lint checks provided by rustc:\n");
1221 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
1222 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
1224 let print_lints = |lints: Vec<&Lint>| {
1226 let name = lint.name_lower().replace("_", "-");
1227 println!(" {} {:7.7} {}",
1229 lint.default_level.as_str(),
1235 print_lints(builtin);
1237 let max_name_len = max("warnings".len(),
1238 plugin_groups.iter()
1239 .chain(&builtin_groups)
1240 .map(|&(s, _)| s.chars().count())
1244 let padded = |x: &str| {
1245 let mut s = " ".repeat(max_name_len - x.chars().count());
1250 println!("Lint groups provided by rustc:\n");
1251 println!(" {} {}", padded("name"), "sub-lints");
1252 println!(" {} {}", padded("----"), "---------");
1253 println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
1255 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
1256 for (name, to) in lints {
1257 let name = name.to_lowercase().replace("_", "-");
1258 let desc = to.into_iter()
1259 .map(|x| x.to_string().replace("_", "-"))
1260 .collect::<Vec<String>>()
1262 println!(" {} {}", padded(&name), desc);
1267 print_lint_groups(builtin_groups);
1269 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
1270 (false, 0, _) | (false, _, 0) => {
1271 println!("Compiler plugins can provide additional lints and lint groups. To see a \
1272 listing of these, re-run `rustc -W help` with a crate filename.");
1274 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
1275 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
1278 println!("Lint checks provided by plugins loaded by this crate:\n");
1279 print_lints(plugin);
1282 println!("Lint groups provided by plugins loaded by this crate:\n");
1283 print_lint_groups(plugin_groups);
1289 fn describe_debug_flags() {
1290 println!("\nAvailable debug options:\n");
1291 print_flag_list("-Z", config::DB_OPTIONS);
1294 fn describe_codegen_flags() {
1295 println!("\nAvailable codegen options:\n");
1296 print_flag_list("-C", config::CG_OPTIONS);
1299 fn print_flag_list<T>(cmdline_opt: &str,
1300 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
1301 let max_len = flag_list.iter()
1302 .map(|&(name, _, opt_type_desc, _)| {
1303 let extra_len = match opt_type_desc {
1307 name.chars().count() + extra_len
1312 for &(name, _, opt_type_desc, desc) in flag_list {
1313 let (width, extra) = match opt_type_desc {
1314 Some(..) => (max_len - 4, "=val"),
1315 None => (max_len, ""),
1317 println!(" {} {:>width$}{} -- {}",
1319 name.replace("_", "-"),
1326 /// Process command line options. Emits messages as appropriate. If compilation
1327 /// should continue, returns a getopts::Matches object parsed from args,
1328 /// otherwise returns None.
1330 /// The compiler's handling of options is a little complicated as it ties into
1331 /// our stability story, and it's even *more* complicated by historical
1332 /// accidents. The current intention of each compiler option is to have one of
1335 /// 1. An option is stable and can be used everywhere.
1336 /// 2. An option is unstable, but was historically allowed on the stable
1338 /// 3. An option is unstable, and can only be used on nightly.
1340 /// Like unstable library and language features, however, unstable options have
1341 /// always required a form of "opt in" to indicate that you're using them. This
1342 /// provides the easy ability to scan a code base to check to see if anything
1343 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1345 /// All options behind `-Z` are considered unstable by default. Other top-level
1346 /// options can also be considered unstable, and they were unlocked through the
1347 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1348 /// instability in both cases, though.
1350 /// So with all that in mind, the comments below have some more detail about the
1351 /// contortions done here to get things to work out correctly.
1352 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
1353 // Throw away the first argument, the name of the binary
1354 let args = &args[1..];
1356 if args.is_empty() {
1357 // user did not write `-v` nor `-Z unstable-options`, so do not
1358 // include that extra information.
1359 usage(false, false);
1363 // Parse with *all* options defined in the compiler, we don't worry about
1364 // option stability here we just want to parse as much as possible.
1365 let mut options = getopts::Options::new();
1366 for option in config::rustc_optgroups() {
1367 (option.apply)(&mut options);
1369 let matches = options.parse(args).unwrap_or_else(|f|
1370 early_error(ErrorOutputType::default(), &f.to_string()));
1372 // For all options we just parsed, we check a few aspects:
1374 // * If the option is stable, we're all good
1375 // * If the option wasn't passed, we're all good
1376 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1377 // ourselves), then we require the `-Z unstable-options` flag to unlock
1378 // this option that was passed.
1379 // * If we're a nightly compiler, then unstable options are now unlocked, so
1380 // we're good to go.
1381 // * Otherwise, if we're a truly unstable option then we generate an error
1382 // (unstable option being used on stable)
1383 // * If we're a historically stable-but-should-be-unstable option then we
1384 // emit a warning that we're going to turn this into an error soon.
1385 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1387 if matches.opt_present("h") || matches.opt_present("help") {
1388 // Only show unstable options in --help if we *really* accept unstable
1389 // options, which catches the case where we got `-Z unstable-options` on
1390 // the stable channel of Rust which was accidentally allowed
1392 usage(matches.opt_present("verbose"),
1393 nightly_options::is_unstable_enabled(&matches));
1397 // Handle the special case of -Wall.
1398 let wall = matches.opt_strs("W");
1399 if wall.iter().any(|x| *x == "all") {
1404 // Don't handle -W help here, because we might first load plugins.
1405 let r = matches.opt_strs("Z");
1406 if r.iter().any(|x| *x == "help") {
1407 describe_debug_flags();
1411 let cg_flags = matches.opt_strs("C");
1413 if cg_flags.iter().any(|x| *x == "help") {
1414 describe_codegen_flags();
1418 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1419 early_warn(ErrorOutputType::default(),
1420 "the --no-stack-check flag is deprecated and does nothing");
1423 if cg_flags.iter().any(|x| *x == "passes=list") {
1424 get_codegen_sysroot("llvm")().print_passes();
1428 if matches.opt_present("version") {
1429 version("rustc", &matches);
1436 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1438 Input::File(ref ifile) => {
1439 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1441 Input::Str { ref name, ref input } => {
1442 parse::parse_crate_attrs_from_source_str(name.clone(),
1449 // Temporarily have stack size set to 32MB to deal with various crates with long method
1450 // chains or deep syntax trees.
1451 // FIXME(oli-obk): get https://github.com/rust-lang/rust/pull/55617 the finish line
1452 const STACK_SIZE: usize = 32 * 1024 * 1024; // 32MB
1454 /// Runs `f` in a suitable thread for running `rustc`; returns a `Result` with either the return
1455 /// value of `f` or -- if a panic occurs -- the panic value.
1457 /// This version applies the given name to the thread. This is used by rustdoc to ensure consistent
1458 /// doctest output across platforms and executions.
1459 pub fn in_named_rustc_thread<F, R>(name: String, f: F) -> Result<R, Box<dyn Any + Send>>
1460 where F: FnOnce() -> R + Send + 'static,
1463 // We need a thread for soundness of thread local storage in rustc. For debugging purposes
1464 // we allow an escape hatch where everything runs on the main thread.
1465 if env::var_os("RUSTC_UNSTABLE_NO_MAIN_THREAD").is_none() {
1466 let mut cfg = thread::Builder::new().name(name);
1468 // If the env is trying to override the stack size then *don't* set it explicitly.
1469 // The libstd thread impl will fetch the `RUST_MIN_STACK` env var itself.
1470 if env::var_os("RUST_MIN_STACK").is_none() {
1471 cfg = cfg.stack_size(STACK_SIZE);
1474 let thread = cfg.spawn(f);
1475 thread.unwrap().join()
1477 let f = panic::AssertUnwindSafe(f);
1478 panic::catch_unwind(f)
1482 /// Runs `f` in a suitable thread for running `rustc`; returns a
1483 /// `Result` with either the return value of `f` or -- if a panic
1484 /// occurs -- the panic value.
1485 pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<dyn Any + Send>>
1486 where F: FnOnce() -> R + Send + 'static,
1489 in_named_rustc_thread("rustc".to_string(), f)
1492 /// Get a list of extra command-line flags provided by the user, as strings.
1494 /// This function is used during ICEs to show more information useful for
1495 /// debugging, since some ICEs only happens with non-default compiler flags
1496 /// (and the users don't always report them).
1497 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1498 let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1500 // Avoid printing help because of empty args. This can suggest the compiler
1501 // itself is not the program root (consider RLS).
1506 let matches = if let Some(matches) = handle_options(&args) {
1512 let mut result = Vec::new();
1513 let mut excluded_cargo_defaults = false;
1514 for flag in ICE_REPORT_COMPILER_FLAGS {
1515 let prefix = if flag.len() == 1 { "-" } else { "--" };
1517 for content in &matches.opt_strs(flag) {
1518 // Split always returns the first element
1519 let name = if let Some(first) = content.split('=').next() {
1525 let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) {
1531 if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
1532 result.push(format!("{}{} {}", prefix, flag, content));
1534 excluded_cargo_defaults = true;
1539 if !result.is_empty() {
1540 Some((result, excluded_cargo_defaults))
1547 pub struct CompilationFailure;
1549 impl Error for CompilationFailure {}
1551 impl Display for CompilationFailure {
1552 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1553 write!(f, "compilation had errors")
1557 /// Run a procedure which will detect panics in the compiler and print nicer
1558 /// error messages rather than just failing the test.
1560 /// The diagnostic emitter yielded to the procedure should be used for reporting
1561 /// errors of the compiler.
1562 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) -> Result<(), CompilationFailure> {
1563 in_rustc_thread(move || {
1565 }).map_err(|value| {
1566 if value.is::<errors::FatalErrorMarker>() {
1569 // Thread panicked without emitting a fatal diagnostic
1573 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
1577 let handler = errors::Handler::with_emitter(true, false, emitter);
1579 // a .span_bug or .bug call has already printed what
1580 // it wants to print.
1581 if !value.is::<errors::ExplicitBug>() {
1582 handler.emit(&MultiSpan::new(),
1584 errors::Level::Bug);
1587 let mut xs: Vec<Cow<'static, str>> = vec![
1588 "the compiler unexpectedly panicked. this is a bug.".into(),
1589 format!("we would appreciate a bug report: {}", BUG_REPORT_URL).into(),
1590 format!("rustc {} running on {}",
1591 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1592 config::host_triple()).into(),
1595 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1596 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1598 if excluded_cargo_defaults {
1599 xs.push("some of the compiler flags provided by cargo are hidden".into());
1604 handler.emit(&MultiSpan::new(),
1606 errors::Level::Note);
1609 panic::resume_unwind(Box::new(errors::FatalErrorMarker));
1614 pub fn diagnostics_registry() -> errors::registry::Registry {
1615 use errors::registry::Registry;
1617 let mut all_errors = Vec::new();
1618 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1619 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1620 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1621 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1622 // FIXME: need to figure out a way to get these back in here
1623 // all_errors.extend_from_slice(get_codegen_backend(sess).diagnostics());
1624 all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1625 all_errors.extend_from_slice(&rustc_passes::DIAGNOSTICS);
1626 all_errors.extend_from_slice(&rustc_plugin::DIAGNOSTICS);
1627 all_errors.extend_from_slice(&rustc_mir::DIAGNOSTICS);
1628 all_errors.extend_from_slice(&syntax::DIAGNOSTICS);
1630 Registry::new(&all_errors)
1633 /// This allows tools to enable rust logging without having to magically match rustc's
1634 /// log crate version
1635 pub fn init_rustc_env_logger() {
1640 init_rustc_env_logger();
1641 let result = run(|| {
1642 let args = env::args_os().enumerate()
1643 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1644 early_error(ErrorOutputType::default(),
1645 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1647 .collect::<Vec<_>>();
1649 Box::new(RustcDefaultCalls),
1653 process::exit(result as i32);