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/")]
22 #![feature(box_syntax)]
23 #![cfg_attr(unix, feature(libc))]
25 #![feature(rustc_diagnostic_macros)]
26 #![feature(set_stdio)]
30 extern crate graphviz;
31 extern crate env_logger;
35 extern crate rustc_allocator;
36 extern crate rustc_back;
37 extern crate rustc_borrowck;
38 extern crate rustc_const_eval;
39 extern crate rustc_data_structures;
40 extern crate rustc_errors as errors;
41 extern crate rustc_passes;
42 extern crate rustc_lint;
43 extern crate rustc_plugin;
44 extern crate rustc_privacy;
45 extern crate rustc_incremental;
46 extern crate rustc_metadata;
47 extern crate rustc_mir;
48 extern crate rustc_resolve;
49 extern crate rustc_save_analysis;
50 extern crate rustc_trans_utils;
51 extern crate rustc_typeck;
52 extern crate serialize;
56 extern crate syntax_ext;
57 extern crate syntax_pos;
59 use driver::CompileController;
60 use pretty::{PpMode, UserIdentifiedItem};
62 use rustc_resolve as resolve;
63 use rustc_save_analysis as save;
64 use rustc_save_analysis::DumpHandler;
65 use rustc::session::{self, config, Session, build_session, CompileResult};
66 use rustc::session::CompileIncomplete;
67 use rustc::session::config::{Input, PrintRequest, ErrorOutputType};
68 use rustc::session::config::nightly_options;
69 use rustc::session::filesearch;
70 use rustc::session::{early_error, early_warn};
71 use rustc::lint::Lint;
73 use rustc::middle::cstore::CrateStore;
74 use rustc_metadata::locator;
75 use rustc_metadata::cstore::CStore;
76 use rustc_metadata::dynamic_lib::DynamicLibrary;
77 use rustc::util::common::{time, ErrorReported};
78 use rustc_trans_utils::trans_crate::TransCrate;
80 use serialize::json::ToJson;
83 use std::cmp::Ordering::Equal;
85 use std::default::Default;
86 use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
88 use std::ffi::OsString;
89 use std::io::{self, Read, Write};
90 use std::iter::repeat;
93 use std::path::{PathBuf, Path};
94 use std::process::{self, Command, Stdio};
97 use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
98 use std::sync::{Once, ONCE_INIT};
102 use syntax::codemap::{CodeMap, FileLoader, RealFileLoader};
103 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
104 use syntax::parse::{self, PResult};
105 use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
113 mod derive_registrar;
115 pub mod target_features {
117 use syntax::symbol::Symbol;
118 use rustc::session::Session;
119 use rustc_trans_utils::trans_crate::TransCrate;
121 /// Add `target_feature = "..."` cfgs for a variety of platform
122 /// specific features (SSE, NEON etc.).
124 /// This is performed by checking whether a whitelisted set of
125 /// features is available on the target machine, by querying LLVM.
126 pub fn add_configuration(cfg: &mut ast::CrateConfig, sess: &Session, trans: &TransCrate) {
127 let tf = Symbol::intern("target_feature");
129 for feat in trans.target_features(sess) {
130 cfg.insert((tf, Some(feat)));
133 if sess.crt_static_feature() {
134 cfg.insert((tf, Some(Symbol::intern("crt-static"))));
139 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
142 pub fn abort_on_err<T>(result: Result<T, CompileIncomplete>, sess: &Session) -> T {
144 Err(CompileIncomplete::Errored(ErrorReported)) => {
145 sess.abort_if_errors();
146 panic!("error reported but abort_if_errors didn't abort???");
148 Err(CompileIncomplete::Stopped) => {
149 sess.fatal("compilation terminated");
155 pub fn run<F>(run_compiler: F) -> isize
156 where F: FnOnce() -> (CompileResult, Option<Session>) + Send + 'static
159 let (result, session) = run_compiler();
160 if let Err(CompileIncomplete::Errored(_)) = result {
163 sess.abort_if_errors();
164 panic!("error reported but abort_if_errors didn't abort???");
168 errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
171 let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
172 handler.emit(&MultiSpan::new(),
173 "aborting due to previous error(s)",
174 errors::Level::Fatal);
175 panic::resume_unwind(Box::new(errors::FatalErrorMarker));
183 fn load_backend_from_dylib(path: &Path) -> fn() -> Box<TransCrate> {
184 // Note that we're specifically using `open_global_now` here rather than
185 // `open`, namely we want the behavior on Unix of RTLD_GLOBAL and RTLD_NOW,
186 // where NOW means "bind everything right now" because we don't want
187 // surprises later on and RTLD_GLOBAL allows the symbols to be made
188 // available for future dynamic libraries opened. This is currently used by
189 // loading LLVM and then making its symbols available for other dynamic
191 let lib = match DynamicLibrary::open_global_now(path) {
194 let err = format!("couldn't load codegen backend {:?}: {:?}",
197 early_error(ErrorOutputType::default(), &err);
201 match lib.symbol("__rustc_codegen_backend") {
204 mem::transmute::<*mut u8, _>(f)
207 let err = format!("couldn't load codegen backend as it \
208 doesn't export the `__rustc_codegen_backend` \
210 early_error(ErrorOutputType::default(), &err);
216 pub fn get_trans(sess: &Session) -> Box<TransCrate> {
217 static INIT: Once = ONCE_INIT;
218 static mut LOAD: fn() -> Box<TransCrate> = || unreachable!();
221 let trans_name = sess.opts.debugging_opts.codegen_backend.as_ref();
222 let backend = match trans_name.map(|s| &**s) {
224 Some("llvm") => get_trans_default(),
225 Some("metadata_only") => {
226 rustc_trans_utils::trans_crate::MetadataOnlyTransCrate::new
228 Some(filename) if filename.contains(".") => {
229 load_backend_from_dylib(filename.as_ref())
231 Some(trans_name) => {
232 sess.fatal(&format!("unknown codegen backend {}", trans_name));
240 let backend = unsafe { LOAD() };
245 fn get_trans_default() -> fn() -> Box<TransCrate> {
246 // For now we only allow this function to be called once as it'll dlopen a
247 // few things, which seems to work best if we only do that once. In
248 // general this assertion never trips due to the once guard in `get_trans`,
249 // but there's a few manual calls to this function in this file we protect
251 static LOADED: AtomicBool = ATOMIC_BOOL_INIT;
252 assert!(!LOADED.fetch_or(true, Ordering::SeqCst),
253 "cannot load the default trans backend twice");
255 // When we're compiling this library with `--test` it'll run as a binary but
256 // not actually exercise much functionality. As a result most of the logic
257 // here is defunkt (it assumes we're a dynamic library in a sysroot) so
258 // let's just return a dummy creation function which won't be used in
261 return rustc_trans_utils::trans_crate::MetadataOnlyTransCrate::new
264 let target = session::config::host_triple();
265 let mut sysroot_candidates = vec![filesearch::get_or_default_sysroot()];
266 let path = current_dll_path()
267 .and_then(|s| s.canonicalize().ok());
268 if let Some(dll) = path {
269 // use `parent` twice to chop off the file name and then also the
270 // directory containing the dll which should be either `lib` or `bin`.
271 if let Some(path) = dll.parent().and_then(|p| p.parent()) {
272 // The original `path` pointed at the `rustc_driver` crate's dll.
273 // Now that dll should only be in one of two locations. The first is
274 // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The
275 // other is the target's libdir, for example
276 // `$sysroot/lib/rustlib/$target/lib/*.dll`.
278 // We don't know which, so let's assume that if our `path` above
279 // ends in `$target` we *could* be in the target libdir, and always
280 // assume that we may be in the main libdir.
281 sysroot_candidates.push(path.to_owned());
283 if path.ends_with(target) {
284 sysroot_candidates.extend(path.parent() // chop off `$target`
285 .and_then(|p| p.parent()) // chop off `rustlib`
286 .and_then(|p| p.parent()) // chop off `lib`
287 .map(|s| s.to_owned()));
292 let sysroot = sysroot_candidates.iter()
294 let libdir = filesearch::relative_target_lib_path(&sysroot, &target);
295 sysroot.join(&libdir).join("codegen-backends")
298 info!("codegen backend candidate: {}", f.display());
302 let sysroot = match sysroot {
305 let candidates = sysroot_candidates.iter()
306 .map(|p| p.display().to_string())
309 let err = format!("failed to find a `codegen-backends` folder \
310 in the sysroot candidates:\n* {}", candidates);
311 early_error(ErrorOutputType::default(), &err);
314 info!("probing {} for a codegen backend", sysroot.display());
316 let d = match sysroot.read_dir() {
319 let err = format!("failed to load default codegen backend, couldn't \
320 read `{}`: {}", sysroot.display(), e);
321 early_error(ErrorOutputType::default(), &err);
325 let mut file: Option<PathBuf> = None;
327 for entry in d.filter_map(|e| e.ok()) {
328 let path = entry.path();
329 let filename = match path.file_name().and_then(|s| s.to_str()) {
333 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
336 let name = &filename[DLL_PREFIX.len() .. filename.len() - DLL_SUFFIX.len()];
337 if !name.starts_with("rustc_trans") {
340 if let Some(ref prev) = file {
341 let err = format!("duplicate codegen backends found\n\
344 ", prev.display(), path.display());
345 early_error(ErrorOutputType::default(), &err);
347 file = Some(path.clone());
351 Some(ref s) => return load_backend_from_dylib(s),
353 let err = format!("failed to load default codegen backend, no appropriate \
354 codegen dylib found in `{}`", sysroot.display());
355 early_error(ErrorOutputType::default(), &err);
360 fn current_dll_path() -> Option<PathBuf> {
361 use std::ffi::{OsStr, CStr};
362 use std::os::unix::prelude::*;
365 let addr = current_dll_path as usize as *mut _;
366 let mut info = mem::zeroed();
367 if libc::dladdr(addr, &mut info) == 0 {
368 info!("dladdr failed");
371 if info.dli_fname.is_null() {
372 info!("dladdr returned null pointer");
375 let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
376 let os = OsStr::from_bytes(bytes);
377 Some(PathBuf::from(os))
382 fn current_dll_path() -> Option<PathBuf> {
383 use std::ffi::OsString;
384 use std::os::windows::prelude::*;
387 fn GetModuleHandleExW(dwFlags: u32,
389 phModule: *mut usize) -> i32;
390 fn GetModuleFileNameW(hModule: usize,
391 lpFilename: *mut u16,
395 const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS: u32 = 0x00000004;
399 let r = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
400 current_dll_path as usize,
403 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
406 let mut space = Vec::with_capacity(1024);
407 let r = GetModuleFileNameW(module,
409 space.capacity() as u32);
411 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
415 if r >= space.capacity() {
416 info!("our buffer was too small? {}",
417 io::Error::last_os_error());
421 let os = OsString::from_wide(&space);
422 Some(PathBuf::from(os))
427 // Parse args and run the compiler. This is the primary entry point for rustc.
428 // See comments on CompilerCalls below for details about the callbacks argument.
429 // The FileLoader provides a way to load files from sources other than the file system.
430 pub fn run_compiler<'a>(args: &[String],
431 callbacks: &mut CompilerCalls<'a>,
432 file_loader: Option<Box<FileLoader + 'static>>,
433 emitter_dest: Option<Box<Write + Send>>)
434 -> (CompileResult, Option<Session>)
436 macro_rules! do_or_return {($expr: expr, $sess: expr) => {
438 Compilation::Stop => return (Ok(()), $sess),
439 Compilation::Continue => {}
443 let matches = match handle_options(args) {
444 Some(matches) => matches,
445 None => return (Ok(()), None),
448 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
450 let descriptions = diagnostics_registry();
452 do_or_return!(callbacks.early_callback(&matches,
459 let (odir, ofile) = make_output(&matches);
460 let (input, input_file_path) = match make_input(&matches.free) {
461 Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
462 None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) {
463 Some((input, input_file_path)) => (input, input_file_path),
464 None => return (Ok(()), None),
468 let loader = file_loader.unwrap_or(box RealFileLoader);
469 let codemap = Rc::new(CodeMap::with_file_loader(loader, sopts.file_path_mapping()));
470 let mut sess = session::build_session_with_codemap(
471 sopts, input_file_path.clone(), descriptions, codemap, emitter_dest,
474 let trans = get_trans(&sess);
476 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
478 let mut cfg = config::build_configuration(&sess, cfg);
479 target_features::add_configuration(&mut cfg, &sess, &*trans);
480 sess.parse_sess.config = cfg;
482 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
484 let cstore = CStore::new(trans.metadata_loader());
486 do_or_return!(callbacks.late_callback(&*trans,
492 &ofile), Some(sess));
494 let control = callbacks.build_controller(&sess, &matches);
496 (driver::compile_input(trans,
508 // Extract output directory and file from matches.
509 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
510 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
511 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
515 // Extract input (string or file and optional path) from matches.
516 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
517 if free_matches.len() == 1 {
518 let ifile = &free_matches[0];
520 let mut src = String::new();
521 io::stdin().read_to_string(&mut src).unwrap();
522 Some((Input::Str { name: FileName::Anon, input: src },
525 Some((Input::File(PathBuf::from(ifile)),
526 Some(PathBuf::from(ifile))))
533 fn parse_pretty(sess: &Session,
534 matches: &getopts::Matches)
535 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
536 let pretty = if sess.opts.debugging_opts.unstable_options {
537 matches.opt_default("pretty", "normal").map(|a| {
538 // stable pretty-print variants only
539 pretty::parse_pretty(sess, &a, false)
545 if pretty.is_none() {
546 sess.opts.debugging_opts.unpretty.as_ref().map(|a| {
547 // extended with unstable pretty-print variants
548 pretty::parse_pretty(sess, &a, true)
555 // Whether to stop or continue compilation.
556 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
557 pub enum Compilation {
563 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
565 Compilation::Stop => Compilation::Stop,
566 Compilation::Continue => next(),
571 // A trait for customising the compilation process. Offers a number of hooks for
572 // executing custom code or customising input.
573 pub trait CompilerCalls<'a> {
574 // Hook for a callback early in the process of handling arguments. This will
575 // be called straight after options have been parsed but before anything
576 // else (e.g., selecting input and output).
577 fn early_callback(&mut self,
578 _: &getopts::Matches,
580 _: &ast::CrateConfig,
581 _: &errors::registry::Registry,
584 Compilation::Continue
587 // Hook for a callback late in the process of handling arguments. This will
588 // be called just before actual compilation starts (and before build_controller
589 // is called), after all arguments etc. have been completely handled.
590 fn late_callback(&mut self,
592 _: &getopts::Matches,
599 Compilation::Continue
602 // Called after we extract the input from the arguments. Gives the implementer
603 // an opportunity to change the inputs or to add some custom input handling.
604 // The default behaviour is to simply pass through the inputs.
605 fn some_input(&mut self,
607 input_path: Option<PathBuf>)
608 -> (Input, Option<PathBuf>) {
612 // Called after we extract the input from the arguments if there is no valid
613 // input. Gives the implementer an opportunity to supply alternate input (by
614 // returning a Some value) or to add custom behaviour for this error such as
615 // emitting error messages. Returning None will cause compilation to stop
617 fn no_input(&mut self,
618 _: &getopts::Matches,
620 _: &ast::CrateConfig,
623 _: &errors::registry::Registry)
624 -> Option<(Input, Option<PathBuf>)> {
628 // Create a CompilController struct for controlling the behaviour of
630 fn build_controller(&mut self, _: &Session, _: &getopts::Matches) -> CompileController<'a>;
633 // CompilerCalls instance for a regular rustc build.
634 #[derive(Copy, Clone)]
635 pub struct RustcDefaultCalls;
637 // FIXME remove these and use winapi 0.3 instead
638 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
640 fn stdout_isatty() -> bool {
641 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
645 fn stdout_isatty() -> bool {
648 type HANDLE = *mut u8;
649 type LPDWORD = *mut u32;
650 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
652 fn GetStdHandle(which: DWORD) -> HANDLE;
653 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
656 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
658 GetConsoleMode(handle, &mut out) != 0
662 fn handle_explain(code: &str,
663 descriptions: &errors::registry::Registry,
664 output: ErrorOutputType) {
665 let normalised = if code.starts_with("E") {
668 format!("E{0:0>4}", code)
670 match descriptions.find_description(&normalised) {
671 Some(ref description) => {
672 let mut is_in_code_block = false;
673 let mut text = String::new();
675 // Slice off the leading newline and print.
676 for line in description[1..].lines() {
677 let indent_level = line.find(|c: char| !c.is_whitespace())
678 .unwrap_or_else(|| line.len());
679 let dedented_line = &line[indent_level..];
680 if dedented_line.starts_with("```") {
681 is_in_code_block = !is_in_code_block;
682 text.push_str(&line[..(indent_level+3)]);
683 } else if is_in_code_block && dedented_line.starts_with("# ") {
692 show_content_with_pager(&text);
698 early_error(output, &format!("no extended information for {}", code));
703 fn show_content_with_pager(content: &String) {
704 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
705 OsString::from("more.com")
707 OsString::from("less")
710 let mut fallback_to_println = false;
712 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
714 if let Some(pipe) = pager.stdin.as_mut() {
715 if pipe.write_all(content.as_bytes()).is_err() {
716 fallback_to_println = true;
720 if pager.wait().is_err() {
721 fallback_to_println = true;
725 fallback_to_println = true;
729 // If pager fails for whatever reason, we should still print the content
730 // to standard output
731 if fallback_to_println {
732 print!("{}", content);
736 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
737 fn early_callback(&mut self,
738 matches: &getopts::Matches,
740 _: &ast::CrateConfig,
741 descriptions: &errors::registry::Registry,
742 output: ErrorOutputType)
744 if let Some(ref code) = matches.opt_str("explain") {
745 handle_explain(code, descriptions, output);
746 return Compilation::Stop;
749 Compilation::Continue
752 fn no_input(&mut self,
753 matches: &getopts::Matches,
754 sopts: &config::Options,
755 cfg: &ast::CrateConfig,
756 odir: &Option<PathBuf>,
757 ofile: &Option<PathBuf>,
758 descriptions: &errors::registry::Registry)
759 -> Option<(Input, Option<PathBuf>)> {
760 match matches.free.len() {
762 if sopts.describe_lints {
763 let mut ls = lint::LintStore::new();
764 rustc_lint::register_builtins(&mut ls, None);
765 describe_lints(&ls, false);
768 let mut sess = build_session(sopts.clone(),
770 descriptions.clone());
771 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
772 let mut cfg = config::build_configuration(&sess, cfg.clone());
773 let trans = get_trans(&sess);
774 target_features::add_configuration(&mut cfg, &sess, &*trans);
775 sess.parse_sess.config = cfg;
776 let should_stop = RustcDefaultCalls::print_crate_info(
784 if should_stop == Compilation::Stop {
787 early_error(sopts.error_format, "no input filename given");
789 1 => panic!("make_input should have provided valid inputs"),
790 _ => early_error(sopts.error_format, "multiple input filenames provided"),
794 fn late_callback(&mut self,
796 matches: &getopts::Matches,
800 odir: &Option<PathBuf>,
801 ofile: &Option<PathBuf>)
803 RustcDefaultCalls::print_crate_info(trans, sess, Some(input), odir, ofile)
804 .and_then(|| RustcDefaultCalls::list_metadata(sess, cstore, matches, input))
807 fn build_controller(&mut self,
809 matches: &getopts::Matches)
810 -> CompileController<'a> {
811 let mut control = CompileController::basic();
813 control.keep_ast = sess.opts.debugging_opts.keep_ast;
814 control.continue_parse_after_error = sess.opts.debugging_opts.continue_parse_after_error;
816 if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
817 if ppm.needs_ast_map(&opt_uii) {
818 control.after_hir_lowering.stop = Compilation::Stop;
820 control.after_parse.callback = box move |state| {
821 state.krate = Some(pretty::fold_crate(state.session,
822 state.krate.take().unwrap(),
825 control.after_hir_lowering.callback = box move |state| {
826 pretty::print_after_hir_lowering(state.session,
827 state.cstore.unwrap(),
828 state.hir_map.unwrap(),
829 state.analysis.unwrap(),
830 state.resolutions.unwrap(),
832 &state.expanded_crate.take().unwrap(),
833 state.crate_name.unwrap(),
835 state.arenas.unwrap(),
836 state.output_filenames.unwrap(),
841 control.after_parse.stop = Compilation::Stop;
843 control.after_parse.callback = box move |state| {
844 let krate = pretty::fold_crate(state.session, state.krate.take().unwrap(), ppm);
845 pretty::print_after_parsing(state.session,
856 if sess.opts.debugging_opts.parse_only ||
857 sess.opts.debugging_opts.show_span.is_some() ||
858 sess.opts.debugging_opts.ast_json_noexpand {
859 control.after_parse.stop = Compilation::Stop;
862 if sess.opts.debugging_opts.no_analysis ||
863 sess.opts.debugging_opts.ast_json {
864 control.after_hir_lowering.stop = Compilation::Stop;
867 if sess.opts.debugging_opts.save_analysis {
868 enable_save_analysis(&mut control);
871 if sess.print_fuel_crate.is_some() {
872 let old_callback = control.compilation_done.callback;
873 control.compilation_done.callback = box move |state| {
875 let sess = state.session;
876 println!("Fuel used by {}: {}",
877 sess.print_fuel_crate.as_ref().unwrap(),
878 sess.print_fuel.get());
885 pub fn enable_save_analysis(control: &mut CompileController) {
886 control.keep_ast = true;
887 control.after_analysis.callback = box |state| {
888 time(state.session.time_passes(), "save analysis", || {
889 save::process_crate(state.tcx.unwrap(),
890 state.expanded_crate.unwrap(),
891 state.analysis.unwrap(),
892 state.crate_name.unwrap(),
894 DumpHandler::new(state.out_dir,
895 state.crate_name.unwrap()))
898 control.after_analysis.run_callback_on_error = true;
899 control.make_glob_map = resolve::MakeGlobMap::Yes;
902 impl RustcDefaultCalls {
903 pub fn list_metadata(sess: &Session,
905 matches: &getopts::Matches,
908 let r = matches.opt_strs("Z");
909 if r.contains(&("ls".to_string())) {
911 &Input::File(ref ifile) => {
912 let path = &(*ifile);
913 let mut v = Vec::new();
914 locator::list_file_metadata(&sess.target.target,
916 cstore.metadata_loader(),
919 println!("{}", String::from_utf8(v).unwrap());
921 &Input::Str { .. } => {
922 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
925 return Compilation::Stop;
928 return Compilation::Continue;
932 fn print_crate_info(trans: &TransCrate,
934 input: Option<&Input>,
935 odir: &Option<PathBuf>,
936 ofile: &Option<PathBuf>)
938 use rustc::session::config::PrintRequest::*;
939 // PrintRequest::NativeStaticLibs is special - printed during linking
940 // (empty iterator returns true)
941 if sess.opts.prints.iter().all(|&p| p==PrintRequest::NativeStaticLibs) {
942 return Compilation::Continue;
945 let attrs = match input {
948 let result = parse_crate_attrs(sess, input);
950 Ok(attrs) => Some(attrs),
951 Err(mut parse_error) => {
953 return Compilation::Stop;
958 for req in &sess.opts.prints {
961 let mut targets = rustc_back::target::get_targets().collect::<Vec<String>>();
963 println!("{}", targets.join("\n"));
965 Sysroot => println!("{}", sess.sysroot().display()),
966 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
967 FileNames | CrateName => {
968 let input = match input {
969 Some(input) => input,
970 None => early_error(ErrorOutputType::default(), "no input file provided"),
972 let attrs = attrs.as_ref().unwrap();
973 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
974 let id = rustc_trans_utils::link::find_crate_name(Some(sess), attrs, input);
975 if *req == PrintRequest::CrateName {
979 let crate_types = driver::collect_crate_types(sess, attrs);
980 for &style in &crate_types {
981 let fname = rustc_trans_utils::link::filename_for_input(
994 let allow_unstable_cfg = UnstableFeatures::from_environment()
997 let mut cfgs = Vec::new();
998 for &(name, ref value) in sess.parse_sess.config.iter() {
999 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
1001 node: ast::MetaItemKind::Word,
1005 // Note that crt-static is a specially recognized cfg
1006 // directive that's printed out here as part of
1007 // rust-lang/rust#37406, but in general the
1008 // `target_feature` cfg is gated under
1009 // rust-lang/rust#29717. For now this is just
1010 // specifically allowing the crt-static cfg and that's
1011 // it, this is intended to get into Cargo and then go
1012 // through to build scripts.
1013 let value = value.as_ref().map(|s| s.as_str());
1014 let value = value.as_ref().map(|s| s.as_ref());
1015 if name != "target_feature" || value != Some("crt-static") {
1016 if !allow_unstable_cfg && gated_cfg.is_some() {
1021 cfgs.push(if let Some(value) = value {
1022 format!("{}=\"{}\"", name, value)
1030 println!("{}", cfg);
1033 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
1034 trans.print(*req, sess);
1036 // Any output here interferes with Cargo's parsing of other printed output
1037 PrintRequest::NativeStaticLibs => {}
1040 return Compilation::Stop;
1044 /// Returns a version string such as "0.12.0-dev".
1045 fn release_str() -> Option<&'static str> {
1046 option_env!("CFG_RELEASE")
1049 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
1050 fn commit_hash_str() -> Option<&'static str> {
1051 option_env!("CFG_VER_HASH")
1054 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
1055 fn commit_date_str() -> Option<&'static str> {
1056 option_env!("CFG_VER_DATE")
1059 /// Prints version information
1060 pub fn version(binary: &str, matches: &getopts::Matches) {
1061 let verbose = matches.opt_present("verbose");
1065 option_env!("CFG_VERSION").unwrap_or("unknown version"));
1067 fn unw(x: Option<&str>) -> &str {
1068 x.unwrap_or("unknown")
1070 println!("binary: {}", binary);
1071 println!("commit-hash: {}", unw(commit_hash_str()));
1072 println!("commit-date: {}", unw(commit_date_str()));
1073 println!("host: {}", config::host_triple());
1074 println!("release: {}", unw(release_str()));
1075 get_trans_default()().print_version();
1079 fn usage(verbose: bool, include_unstable_options: bool) {
1080 let groups = if verbose {
1081 config::rustc_optgroups()
1083 config::rustc_short_optgroups()
1085 let mut options = getopts::Options::new();
1086 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
1087 (option.apply)(&mut options);
1089 let message = format!("Usage: rustc [OPTIONS] INPUT");
1090 let nightly_help = if nightly_options::is_nightly_build() {
1091 "\n -Z help Print internal options for debugging rustc"
1095 let verbose_help = if verbose {
1098 "\n --help -v Print the full set of options rustc accepts"
1100 println!("{}\nAdditional help:
1101 -C help Print codegen options
1103 Print 'lint' options and default settings{}{}\n",
1104 options.usage(&message),
1109 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
1111 Available lint options:
1112 -W <foo> Warn about <foo>
1116 -F <foo> Forbid <foo> \
1117 (deny <foo> and all attempts to override)
1121 fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
1122 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
1123 lints.sort_by(|x: &&Lint, y: &&Lint| {
1124 match x.default_level.cmp(&y.default_level) {
1125 // The sort doesn't case-fold but it's doubtful we care.
1126 Equal => x.name.cmp(y.name),
1133 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
1134 -> Vec<(&'static str, Vec<lint::LintId>)> {
1135 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
1136 lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
1137 &(y, _): &(&'static str, Vec<lint::LintId>)| {
1143 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
1146 .partition(|&(_, p)| p);
1147 let plugin = sort_lints(plugin);
1148 let builtin = sort_lints(builtin);
1150 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
1153 .partition(|&(.., p)| p);
1154 let plugin_groups = sort_lint_groups(plugin_groups);
1155 let builtin_groups = sort_lint_groups(builtin_groups);
1157 let max_name_len = plugin.iter()
1159 .map(|&s| s.name.chars().count())
1162 let padded = |x: &str| {
1163 let mut s = repeat(" ")
1164 .take(max_name_len - x.chars().count())
1165 .collect::<String>();
1170 println!("Lint checks provided by rustc:\n");
1171 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
1172 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
1174 let print_lints = |lints: Vec<&Lint>| {
1176 let name = lint.name_lower().replace("_", "-");
1177 println!(" {} {:7.7} {}",
1179 lint.default_level.as_str(),
1185 print_lints(builtin);
1189 let max_name_len = max("warnings".len(),
1190 plugin_groups.iter()
1191 .chain(&builtin_groups)
1192 .map(|&(s, _)| s.chars().count())
1196 let padded = |x: &str| {
1197 let mut s = repeat(" ")
1198 .take(max_name_len - x.chars().count())
1199 .collect::<String>();
1204 println!("Lint groups provided by rustc:\n");
1205 println!(" {} {}", padded("name"), "sub-lints");
1206 println!(" {} {}", padded("----"), "---------");
1207 println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
1209 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
1210 for (name, to) in lints {
1211 let name = name.to_lowercase().replace("_", "-");
1212 let desc = to.into_iter()
1213 .map(|x| x.to_string().replace("_", "-"))
1214 .collect::<Vec<String>>()
1216 println!(" {} {}", padded(&name), desc);
1221 print_lint_groups(builtin_groups);
1223 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
1224 (false, 0, _) | (false, _, 0) => {
1225 println!("Compiler plugins can provide additional lints and lint groups. To see a \
1226 listing of these, re-run `rustc -W help` with a crate filename.");
1228 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
1229 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
1232 println!("Lint checks provided by plugins loaded by this crate:\n");
1233 print_lints(plugin);
1236 println!("Lint groups provided by plugins loaded by this crate:\n");
1237 print_lint_groups(plugin_groups);
1243 fn describe_debug_flags() {
1244 println!("\nAvailable debug options:\n");
1245 print_flag_list("-Z", config::DB_OPTIONS);
1248 fn describe_codegen_flags() {
1249 println!("\nAvailable codegen options:\n");
1250 print_flag_list("-C", config::CG_OPTIONS);
1253 fn print_flag_list<T>(cmdline_opt: &str,
1254 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
1255 let max_len = flag_list.iter()
1256 .map(|&(name, _, opt_type_desc, _)| {
1257 let extra_len = match opt_type_desc {
1261 name.chars().count() + extra_len
1266 for &(name, _, opt_type_desc, desc) in flag_list {
1267 let (width, extra) = match opt_type_desc {
1268 Some(..) => (max_len - 4, "=val"),
1269 None => (max_len, ""),
1271 println!(" {} {:>width$}{} -- {}",
1273 name.replace("_", "-"),
1280 /// Process command line options. Emits messages as appropriate. If compilation
1281 /// should continue, returns a getopts::Matches object parsed from args,
1282 /// otherwise returns None.
1284 /// The compiler's handling of options is a little complicated as it ties into
1285 /// our stability story, and it's even *more* complicated by historical
1286 /// accidents. The current intention of each compiler option is to have one of
1289 /// 1. An option is stable and can be used everywhere.
1290 /// 2. An option is unstable, but was historically allowed on the stable
1292 /// 3. An option is unstable, and can only be used on nightly.
1294 /// Like unstable library and language features, however, unstable options have
1295 /// always required a form of "opt in" to indicate that you're using them. This
1296 /// provides the easy ability to scan a code base to check to see if anything
1297 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1299 /// All options behind `-Z` are considered unstable by default. Other top-level
1300 /// options can also be considered unstable, and they were unlocked through the
1301 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1302 /// instability in both cases, though.
1304 /// So with all that in mind, the comments below have some more detail about the
1305 /// contortions done here to get things to work out correctly.
1306 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
1307 // Throw away the first argument, the name of the binary
1308 let args = &args[1..];
1310 if args.is_empty() {
1311 // user did not write `-v` nor `-Z unstable-options`, so do not
1312 // include that extra information.
1313 usage(false, false);
1317 // Parse with *all* options defined in the compiler, we don't worry about
1318 // option stability here we just want to parse as much as possible.
1319 let mut options = getopts::Options::new();
1320 for option in config::rustc_optgroups() {
1321 (option.apply)(&mut options);
1323 let matches = match options.parse(args) {
1325 Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
1328 // For all options we just parsed, we check a few aspects:
1330 // * If the option is stable, we're all good
1331 // * If the option wasn't passed, we're all good
1332 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1333 // ourselves), then we require the `-Z unstable-options` flag to unlock
1334 // this option that was passed.
1335 // * If we're a nightly compiler, then unstable options are now unlocked, so
1336 // we're good to go.
1337 // * Otherwise, if we're a truly unstable option then we generate an error
1338 // (unstable option being used on stable)
1339 // * If we're a historically stable-but-should-be-unstable option then we
1340 // emit a warning that we're going to turn this into an error soon.
1341 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1343 if matches.opt_present("h") || matches.opt_present("help") {
1344 // Only show unstable options in --help if we *really* accept unstable
1345 // options, which catches the case where we got `-Z unstable-options` on
1346 // the stable channel of Rust which was accidentally allowed
1348 usage(matches.opt_present("verbose"),
1349 nightly_options::is_unstable_enabled(&matches));
1353 // Don't handle -W help here, because we might first load plugins.
1354 let r = matches.opt_strs("Z");
1355 if r.iter().any(|x| *x == "help") {
1356 describe_debug_flags();
1360 let cg_flags = matches.opt_strs("C");
1361 if cg_flags.iter().any(|x| *x == "help") {
1362 describe_codegen_flags();
1366 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1367 early_warn(ErrorOutputType::default(),
1368 "the --no-stack-check flag is deprecated and does nothing");
1371 if cg_flags.contains(&"passes=list".to_string()) {
1372 get_trans_default()().print_passes();
1376 if matches.opt_present("version") {
1377 version("rustc", &matches);
1384 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1386 Input::File(ref ifile) => {
1387 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1389 Input::Str { ref name, ref input } => {
1390 parse::parse_crate_attrs_from_source_str(name.clone(),
1397 /// Runs `f` in a suitable thread for running `rustc`; returns a
1398 /// `Result` with either the return value of `f` or -- if a panic
1399 /// occurs -- the panic value.
1400 pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<Any + Send>>
1401 where F: FnOnce() -> R + Send + 'static,
1404 // Temporarily have stack size set to 16MB to deal with nom-using crates failing
1405 const STACK_SIZE: usize = 16 * 1024 * 1024; // 16MB
1407 let mut cfg = thread::Builder::new().name("rustc".to_string());
1409 // FIXME: Hacks on hacks. If the env is trying to override the stack size
1410 // then *don't* set it explicitly.
1411 if env::var_os("RUST_MIN_STACK").is_none() {
1412 cfg = cfg.stack_size(STACK_SIZE);
1415 let thread = cfg.spawn(f);
1416 thread.unwrap().join()
1419 /// Run a procedure which will detect panics in the compiler and print nicer
1420 /// error messages rather than just failing the test.
1422 /// The diagnostic emitter yielded to the procedure should be used for reporting
1423 /// errors of the compiler.
1424 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
1425 let result = in_rustc_thread(move || {
1429 if let Err(value) = result {
1430 // Thread panicked without emitting a fatal diagnostic
1431 if !value.is::<errors::FatalErrorMarker>() {
1436 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
1439 let handler = errors::Handler::with_emitter(true, false, emitter);
1441 // a .span_bug or .bug call has already printed what
1442 // it wants to print.
1443 if !value.is::<errors::ExplicitBug>() {
1444 handler.emit(&MultiSpan::new(),
1446 errors::Level::Bug);
1449 let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1450 format!("we would appreciate a bug report: {}", BUG_REPORT_URL),
1451 format!("rustc {} running on {}",
1452 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1453 config::host_triple())];
1455 handler.emit(&MultiSpan::new(),
1457 errors::Level::Note);
1461 panic::resume_unwind(Box::new(errors::FatalErrorMarker));
1466 pub fn diagnostics_registry() -> errors::registry::Registry {
1467 use errors::registry::Registry;
1473 pub fn diagnostics_registry() -> errors::registry::Registry {
1474 use errors::registry::Registry;
1476 let mut all_errors = Vec::new();
1477 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1478 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1479 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1480 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1481 // FIXME: need to figure out a way to get these back in here
1482 // all_errors.extend_from_slice(get_trans(sess).diagnostics());
1483 all_errors.extend_from_slice(&rustc_trans_utils::DIAGNOSTICS);
1484 all_errors.extend_from_slice(&rustc_const_eval::DIAGNOSTICS);
1485 all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1486 all_errors.extend_from_slice(&rustc_passes::DIAGNOSTICS);
1487 all_errors.extend_from_slice(&rustc_plugin::DIAGNOSTICS);
1488 all_errors.extend_from_slice(&rustc_mir::DIAGNOSTICS);
1489 all_errors.extend_from_slice(&syntax::DIAGNOSTICS);
1491 Registry::new(&all_errors)
1495 env_logger::init().unwrap();
1496 let result = run(|| {
1497 let args = env::args_os().enumerate()
1498 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1499 early_error(ErrorOutputType::default(),
1500 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1502 .collect::<Vec<_>>();
1504 &mut RustcDefaultCalls,
1508 process::exit(result as i32);