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 #![crate_name = "rustc_driver"]
18 #![crate_type = "dylib"]
19 #![crate_type = "rlib"]
20 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
21 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
22 html_root_url = "https://doc.rust-lang.org/nightly/")]
25 #![feature(box_syntax)]
28 #![feature(rustc_diagnostic_macros)]
29 #![feature(set_stdio)]
31 #[cfg(not(feature="llvm"))]
36 extern crate graphviz;
37 extern crate env_logger;
38 #[cfg(not(feature="llvm"))]
39 extern crate owning_ref;
42 extern crate rustc_allocator;
43 extern crate rustc_back;
44 extern crate rustc_borrowck;
45 extern crate rustc_const_eval;
46 extern crate rustc_data_structures;
47 extern crate rustc_errors as errors;
48 extern crate rustc_passes;
49 extern crate rustc_lint;
50 extern crate rustc_plugin;
51 extern crate rustc_privacy;
52 extern crate rustc_incremental;
53 extern crate rustc_metadata;
54 extern crate rustc_mir;
55 extern crate rustc_resolve;
56 extern crate rustc_save_analysis;
57 #[cfg(feature="llvm")]
58 extern crate rustc_trans;
59 extern crate rustc_trans_utils;
60 extern crate rustc_typeck;
61 extern crate serialize;
65 extern crate syntax_ext;
66 extern crate syntax_pos;
68 use driver::CompileController;
69 use pretty::{PpMode, UserIdentifiedItem};
71 use rustc_resolve as resolve;
72 use rustc_save_analysis as save;
73 use rustc_save_analysis::DumpHandler;
74 #[cfg(feature="llvm")]
75 use rustc_trans::back::write::{RELOC_MODEL_ARGS, CODE_GEN_MODEL_ARGS};
76 use rustc::dep_graph::DepGraph;
77 use rustc::session::{self, config, Session, build_session, CompileResult};
78 use rustc::session::CompileIncomplete;
79 use rustc::session::config::{Input, PrintRequest, OutputType, ErrorOutputType};
80 use rustc::session::config::nightly_options;
81 use rustc::session::{early_error, early_warn};
82 use rustc::lint::Lint;
84 #[cfg(not(feature="llvm"))]
85 use rustc::middle::cstore::MetadataLoader as MetadataLoaderTrait;
86 use rustc_metadata::locator;
87 use rustc_metadata::cstore::CStore;
88 use rustc::util::common::{time, ErrorReported};
89 #[cfg(not(feature="llvm"))]
90 use rustc_back::target::Target;
92 use serialize::json::ToJson;
96 use std::cmp::Ordering::Equal;
97 use std::default::Default;
99 use std::ffi::OsString;
100 use std::io::{self, Read, Write};
101 use std::iter::repeat;
102 use std::path::PathBuf;
103 #[cfg(not(feature="llvm"))]
105 use std::process::{self, Command, Stdio};
108 use std::sync::{Arc, Mutex};
112 use syntax::codemap::{CodeMap, FileLoader, RealFileLoader};
113 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
114 use syntax::parse::{self, PResult};
115 use syntax_pos::{DUMMY_SP, MultiSpan};
117 #[cfg(not(feature="llvm"))]
118 use owning_ref::{OwningRef, ErasedBoxRef};
125 #[cfg(feature="llvm")]
126 pub mod target_features;
127 mod derive_registrar;
129 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
132 pub fn abort_on_err<T>(result: Result<T, CompileIncomplete>, sess: &Session) -> T {
134 Err(CompileIncomplete::Errored(ErrorReported)) => {
135 sess.abort_if_errors();
136 panic!("error reported but abort_if_errors didn't abort???");
138 Err(CompileIncomplete::Stopped) => {
139 sess.fatal("compilation terminated");
145 pub fn run<F>(run_compiler: F) -> isize
146 where F: FnOnce() -> (CompileResult, Option<Session>) + Send + 'static
149 let (result, session) = run_compiler();
150 if let Err(CompileIncomplete::Errored(_)) = result {
153 sess.abort_if_errors();
154 panic!("error reported but abort_if_errors didn't abort???");
158 errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None);
159 let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
160 handler.emit(&MultiSpan::new(),
161 "aborting due to previous error(s)",
162 errors::Level::Fatal);
171 #[cfg(not(feature="llvm"))]
172 pub struct NoLLvmMetadataLoader;
174 #[cfg(not(feature="llvm"))]
175 pub use NoLLvmMetadataLoader as MetadataLoader;
176 #[cfg(feature="llvm")]
177 pub use rustc_trans::LlvmMetadataLoader as MetadataLoader;
179 #[cfg(not(feature="llvm"))]
180 impl MetadataLoaderTrait for NoLLvmMetadataLoader {
181 fn get_rlib_metadata(&self, _: &Target, filename: &Path) -> Result<ErasedBoxRef<[u8]>, String> {
184 use self::ar::Archive;
186 let file = File::open(filename).map_err(|e|format!("metadata file open err: {:?}", e))?;
187 let mut archive = Archive::new(file);
189 while let Some(entry_result) = archive.next_entry() {
190 let mut entry = entry_result.map_err(|e|format!("metadata section read err: {:?}", e))?;
191 if entry.header().identifier() == "rust.metadata.bin" {
192 let mut buf = Vec::new();
193 io::copy(&mut entry, &mut buf).unwrap();
194 let buf: OwningRef<Vec<u8>, [u8]> = OwningRef::new(buf).into();
195 return Ok(buf.map_owner_box().erase_owner());
199 Err("Couldnt find metadata section".to_string())
202 fn get_dylib_metadata(&self,
205 -> Result<ErasedBoxRef<[u8]>, String> {
206 panic!("Dylib metadata loading not supported without LLVM")
210 // Parse args and run the compiler. This is the primary entry point for rustc.
211 // See comments on CompilerCalls below for details about the callbacks argument.
212 // The FileLoader provides a way to load files from sources other than the file system.
213 #[cfg_attr(not(feature="llvm"), allow(unused_mut))]
214 pub fn run_compiler<'a>(args: &[String],
215 callbacks: &mut CompilerCalls<'a>,
216 file_loader: Option<Box<FileLoader + 'static>>,
217 emitter_dest: Option<Box<Write + Send>>)
218 -> (CompileResult, Option<Session>)
220 macro_rules! do_or_return {($expr: expr, $sess: expr) => {
222 Compilation::Stop => return (Ok(()), $sess),
223 Compilation::Continue => {}
227 let matches = match handle_options(args) {
228 Some(matches) => matches,
229 None => return (Ok(()), None),
232 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
234 if sopts.debugging_opts.debug_llvm {
235 #[cfg(feature="llvm")]
236 rustc_trans::enable_llvm_debug();
239 let descriptions = diagnostics_registry();
241 do_or_return!(callbacks.early_callback(&matches,
248 let (odir, ofile) = make_output(&matches);
249 let (input, input_file_path) = match make_input(&matches.free) {
250 Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
251 None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) {
252 Some((input, input_file_path)) => (input, input_file_path),
253 None => return (Ok(()), None),
257 let dep_graph = DepGraph::new(sopts.build_dep_graph());
258 let cstore = Rc::new(CStore::new(&dep_graph, box ::MetadataLoader));
260 let loader = file_loader.unwrap_or(box RealFileLoader);
261 let codemap = Rc::new(CodeMap::with_file_loader(loader, sopts.file_path_mapping()));
262 let mut sess = session::build_session_with_codemap(
263 sopts, &dep_graph, input_file_path, descriptions, cstore.clone(), codemap, emitter_dest,
265 #[cfg(feature="llvm")]
266 rustc_trans::init(&sess);
267 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
269 let mut cfg = config::build_configuration(&sess, cfg);
270 #[cfg(feature="llvm")]
271 target_features::add_configuration(&mut cfg, &sess);
272 sess.parse_sess.config = cfg;
274 do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile), Some(sess));
276 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
277 let control = callbacks.build_controller(&sess, &matches);
278 (driver::compile_input(&sess, &cstore, &input, &odir, &ofile, Some(plugins), &control),
282 // Extract output directory and file from matches.
283 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
284 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
285 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
289 // Extract input (string or file and optional path) from matches.
290 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
291 if free_matches.len() == 1 {
292 let ifile = &free_matches[0];
294 let mut src = String::new();
295 io::stdin().read_to_string(&mut src).unwrap();
296 Some((Input::Str { name: driver::anon_src(), input: src },
299 Some((Input::File(PathBuf::from(ifile)),
300 Some(PathBuf::from(ifile))))
307 fn parse_pretty(sess: &Session,
308 matches: &getopts::Matches)
309 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
310 let pretty = if sess.opts.debugging_opts.unstable_options {
311 matches.opt_default("pretty", "normal").map(|a| {
312 // stable pretty-print variants only
313 pretty::parse_pretty(sess, &a, false)
318 if pretty.is_none() && sess.unstable_options() {
319 matches.opt_str("unpretty").map(|a| {
320 // extended with unstable pretty-print variants
321 pretty::parse_pretty(sess, &a, true)
328 // Whether to stop or continue compilation.
329 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
330 pub enum Compilation {
336 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
338 Compilation::Stop => Compilation::Stop,
339 Compilation::Continue => next(),
344 // A trait for customising the compilation process. Offers a number of hooks for
345 // executing custom code or customising input.
346 pub trait CompilerCalls<'a> {
347 // Hook for a callback early in the process of handling arguments. This will
348 // be called straight after options have been parsed but before anything
349 // else (e.g., selecting input and output).
350 fn early_callback(&mut self,
351 _: &getopts::Matches,
353 _: &ast::CrateConfig,
354 _: &errors::registry::Registry,
357 Compilation::Continue
360 // Hook for a callback late in the process of handling arguments. This will
361 // be called just before actual compilation starts (and before build_controller
362 // is called), after all arguments etc. have been completely handled.
363 fn late_callback(&mut self,
364 _: &getopts::Matches,
370 Compilation::Continue
373 // Called after we extract the input from the arguments. Gives the implementer
374 // an opportunity to change the inputs or to add some custom input handling.
375 // The default behaviour is to simply pass through the inputs.
376 fn some_input(&mut self,
378 input_path: Option<PathBuf>)
379 -> (Input, Option<PathBuf>) {
383 // Called after we extract the input from the arguments if there is no valid
384 // input. Gives the implementer an opportunity to supply alternate input (by
385 // returning a Some value) or to add custom behaviour for this error such as
386 // emitting error messages. Returning None will cause compilation to stop
388 fn no_input(&mut self,
389 _: &getopts::Matches,
391 _: &ast::CrateConfig,
394 _: &errors::registry::Registry)
395 -> Option<(Input, Option<PathBuf>)> {
399 // Create a CompilController struct for controlling the behaviour of
401 fn build_controller(&mut self, _: &Session, _: &getopts::Matches) -> CompileController<'a>;
404 // CompilerCalls instance for a regular rustc build.
405 #[derive(Copy, Clone)]
406 pub struct RustcDefaultCalls;
408 // FIXME remove these and use winapi 0.3 instead
409 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
411 fn stdout_isatty() -> bool {
412 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
416 fn stdout_isatty() -> bool {
419 type HANDLE = *mut u8;
420 type LPDWORD = *mut u32;
421 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
423 fn GetStdHandle(which: DWORD) -> HANDLE;
424 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
427 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
429 GetConsoleMode(handle, &mut out) != 0
433 fn handle_explain(code: &str,
434 descriptions: &errors::registry::Registry,
435 output: ErrorOutputType) {
436 let normalised = if code.starts_with("E") {
439 format!("E{0:0>4}", code)
441 match descriptions.find_description(&normalised) {
442 Some(ref description) => {
443 let mut is_in_code_block = false;
444 let mut text = String::new();
446 // Slice off the leading newline and print.
447 for line in description[1..].lines() {
448 let indent_level = line.find(|c: char| !c.is_whitespace())
449 .unwrap_or_else(|| line.len());
450 let dedented_line = &line[indent_level..];
451 if dedented_line.starts_with("```") {
452 is_in_code_block = !is_in_code_block;
453 text.push_str(&line[..(indent_level+3)]);
454 } else if is_in_code_block && dedented_line.starts_with("# ") {
463 show_content_with_pager(&text);
469 early_error(output, &format!("no extended information for {}", code));
474 fn show_content_with_pager(content: &String) {
475 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
476 OsString::from("more.com")
478 OsString::from("less")
481 let mut fallback_to_println = false;
483 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
485 if let Some(pipe) = pager.stdin.as_mut() {
486 if pipe.write_all(content.as_bytes()).is_err() {
487 fallback_to_println = true;
491 if pager.wait().is_err() {
492 fallback_to_println = true;
496 fallback_to_println = true;
500 // If pager fails for whatever reason, we should still print the content
501 // to standard output
502 if fallback_to_println {
503 print!("{}", content);
507 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
508 fn early_callback(&mut self,
509 matches: &getopts::Matches,
511 _: &ast::CrateConfig,
512 descriptions: &errors::registry::Registry,
513 output: ErrorOutputType)
515 if let Some(ref code) = matches.opt_str("explain") {
516 handle_explain(code, descriptions, output);
517 return Compilation::Stop;
520 Compilation::Continue
523 #[cfg_attr(not(feature="llvm"), allow(unused_mut))]
524 fn no_input(&mut self,
525 matches: &getopts::Matches,
526 sopts: &config::Options,
527 cfg: &ast::CrateConfig,
528 odir: &Option<PathBuf>,
529 ofile: &Option<PathBuf>,
530 descriptions: &errors::registry::Registry)
531 -> Option<(Input, Option<PathBuf>)> {
532 match matches.free.len() {
534 if sopts.describe_lints {
535 let mut ls = lint::LintStore::new();
536 rustc_lint::register_builtins(&mut ls, None);
537 describe_lints(&ls, false);
540 let dep_graph = DepGraph::new(sopts.build_dep_graph());
541 let cstore = Rc::new(CStore::new(&dep_graph, box ::MetadataLoader));
542 let mut sess = build_session(sopts.clone(),
545 descriptions.clone(),
547 #[cfg(feature="llvm")]
548 rustc_trans::init(&sess);
549 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
550 let mut cfg = config::build_configuration(&sess, cfg.clone());
551 #[cfg(feature="llvm")]
552 target_features::add_configuration(&mut cfg, &sess);
553 sess.parse_sess.config = cfg;
555 RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
557 if should_stop == Compilation::Stop {
560 early_error(sopts.error_format, "no input filename given");
562 1 => panic!("make_input should have provided valid inputs"),
563 _ => early_error(sopts.error_format, "multiple input filenames provided"),
567 fn late_callback(&mut self,
568 matches: &getopts::Matches,
571 odir: &Option<PathBuf>,
572 ofile: &Option<PathBuf>)
574 RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
575 .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input))
578 fn build_controller(&mut self,
580 matches: &getopts::Matches)
581 -> CompileController<'a> {
582 let mut control = CompileController::basic();
584 control.keep_ast = sess.opts.debugging_opts.keep_ast;
585 control.continue_parse_after_error = sess.opts.debugging_opts.continue_parse_after_error;
587 if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
588 if ppm.needs_ast_map(&opt_uii) {
589 control.after_hir_lowering.stop = Compilation::Stop;
591 control.after_parse.callback = box move |state| {
592 state.krate = Some(pretty::fold_crate(state.krate.take().unwrap(), ppm));
594 control.after_hir_lowering.callback = box move |state| {
595 pretty::print_after_hir_lowering(state.session,
596 state.hir_map.unwrap(),
597 state.analysis.unwrap(),
598 state.resolutions.unwrap(),
600 &state.expanded_crate.take().unwrap(),
601 state.crate_name.unwrap(),
603 state.arena.unwrap(),
604 state.arenas.unwrap(),
609 control.after_parse.stop = Compilation::Stop;
611 control.after_parse.callback = box move |state| {
612 let krate = pretty::fold_crate(state.krate.take().unwrap(), ppm);
613 pretty::print_after_parsing(state.session,
624 if sess.opts.debugging_opts.parse_only ||
625 sess.opts.debugging_opts.show_span.is_some() ||
626 sess.opts.debugging_opts.ast_json_noexpand {
627 control.after_parse.stop = Compilation::Stop;
630 if sess.opts.debugging_opts.no_analysis ||
631 sess.opts.debugging_opts.ast_json {
632 control.after_hir_lowering.stop = Compilation::Stop;
635 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
636 i == OutputType::Metadata) {
637 control.after_llvm.stop = Compilation::Stop;
640 if save_analysis(sess) {
641 enable_save_analysis(&mut control);
644 if sess.print_fuel_crate.is_some() {
645 let old_callback = control.compilation_done.callback;
646 control.compilation_done.callback = box move |state| {
648 let sess = state.session;
649 println!("Fuel used by {}: {}",
650 sess.print_fuel_crate.as_ref().unwrap(),
651 sess.print_fuel.get());
658 pub fn enable_save_analysis(control: &mut CompileController) {
659 control.keep_ast = true;
660 control.after_analysis.callback = box |state| {
661 time(state.session.time_passes(), "save analysis", || {
662 save::process_crate(state.tcx.unwrap(),
663 state.expanded_crate.unwrap(),
664 state.analysis.unwrap(),
665 state.crate_name.unwrap(),
667 DumpHandler::new(state.out_dir,
668 state.crate_name.unwrap()))
671 control.after_analysis.run_callback_on_error = true;
672 control.make_glob_map = resolve::MakeGlobMap::Yes;
675 fn save_analysis(sess: &Session) -> bool {
676 sess.opts.debugging_opts.save_analysis
679 impl RustcDefaultCalls {
680 pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation {
681 let r = matches.opt_strs("Z");
682 if r.contains(&("ls".to_string())) {
684 &Input::File(ref ifile) => {
685 let path = &(*ifile);
686 let mut v = Vec::new();
687 locator::list_file_metadata(&sess.target.target,
689 sess.cstore.metadata_loader(),
692 println!("{}", String::from_utf8(v).unwrap());
694 &Input::Str { .. } => {
695 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
698 return Compilation::Stop;
701 return Compilation::Continue;
705 fn print_crate_info(sess: &Session,
706 input: Option<&Input>,
707 odir: &Option<PathBuf>,
708 ofile: &Option<PathBuf>)
710 if sess.opts.prints.is_empty() {
711 return Compilation::Continue;
714 let attrs = match input {
717 let result = parse_crate_attrs(sess, input);
719 Ok(attrs) => Some(attrs),
720 Err(mut parse_error) => {
722 return Compilation::Stop;
727 for req in &sess.opts.prints {
729 PrintRequest::TargetList => {
730 let mut targets = rustc_back::target::get_targets().collect::<Vec<String>>();
732 println!("{}", targets.join("\n"));
734 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
735 PrintRequest::TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
736 PrintRequest::FileNames |
737 PrintRequest::CrateName => {
738 let input = match input {
739 Some(input) => input,
740 None => early_error(ErrorOutputType::default(), "no input file provided"),
742 let attrs = attrs.as_ref().unwrap();
743 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
744 let id = rustc_trans_utils::link::find_crate_name(Some(sess), attrs, input);
745 if *req == PrintRequest::CrateName {
749 let crate_types = driver::collect_crate_types(sess, attrs);
750 for &style in &crate_types {
751 let fname = rustc_trans_utils::link::filename_for_input(
763 PrintRequest::Cfg => {
764 let allow_unstable_cfg = UnstableFeatures::from_environment()
767 let mut cfgs = Vec::new();
768 for &(name, ref value) in sess.parse_sess.config.iter() {
769 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
771 node: ast::MetaItemKind::Word,
775 // Note that crt-static is a specially recognized cfg
776 // directive that's printed out here as part of
777 // rust-lang/rust#37406, but in general the
778 // `target_feature` cfg is gated under
779 // rust-lang/rust#29717. For now this is just
780 // specifically allowing the crt-static cfg and that's
781 // it, this is intended to get into Cargo and then go
782 // through to build scripts.
783 let value = value.as_ref().map(|s| s.as_str());
784 let value = value.as_ref().map(|s| s.as_ref());
785 if name != "target_feature" || value != Some("crt-static") {
786 if !allow_unstable_cfg && gated_cfg.is_some() {
791 cfgs.push(if let Some(value) = value {
792 format!("{}=\"{}\"", name, value)
803 PrintRequest::RelocationModels => {
804 println!("Available relocation models:");
805 #[cfg(feature="llvm")]
806 for &(name, _) in RELOC_MODEL_ARGS.iter() {
807 println!(" {}", name);
811 PrintRequest::CodeModels => {
812 println!("Available code models:");
813 #[cfg(feature="llvm")]
814 for &(name, _) in CODE_GEN_MODEL_ARGS.iter(){
815 println!(" {}", name);
819 PrintRequest::TargetCPUs | PrintRequest::TargetFeatures => {
820 #[cfg(feature="llvm")]
821 rustc_trans::print(*req, sess);
822 #[cfg(not(feature="llvm"))]
823 panic!("LLVM not supported by this rustc")
827 return Compilation::Stop;
831 /// Returns a version string such as "0.12.0-dev".
832 pub fn release_str() -> Option<&'static str> {
833 option_env!("CFG_RELEASE")
836 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
837 pub fn commit_hash_str() -> Option<&'static str> {
838 option_env!("CFG_VER_HASH")
841 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
842 pub fn commit_date_str() -> Option<&'static str> {
843 option_env!("CFG_VER_DATE")
846 /// Prints version information
847 pub fn version(binary: &str, matches: &getopts::Matches) {
848 let verbose = matches.opt_present("verbose");
852 option_env!("CFG_VERSION").unwrap_or("unknown version"));
854 fn unw(x: Option<&str>) -> &str {
855 x.unwrap_or("unknown")
857 println!("binary: {}", binary);
858 println!("commit-hash: {}", unw(commit_hash_str()));
859 println!("commit-date: {}", unw(commit_date_str()));
860 println!("host: {}", config::host_triple());
861 println!("release: {}", unw(release_str()));
862 #[cfg(feature="llvm")]
863 rustc_trans::print_version();
867 fn usage(verbose: bool, include_unstable_options: bool) {
868 let groups = if verbose {
869 config::rustc_optgroups()
871 config::rustc_short_optgroups()
873 let mut options = getopts::Options::new();
874 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
875 (option.apply)(&mut options);
877 let message = format!("Usage: rustc [OPTIONS] INPUT");
878 let nightly_help = if nightly_options::is_nightly_build() {
879 "\n -Z help Print internal options for debugging rustc"
883 let verbose_help = if verbose {
886 "\n --help -v Print the full set of options rustc accepts"
888 println!("{}\nAdditional help:
889 -C help Print codegen options
891 Print 'lint' options and default settings{}{}\n",
892 options.usage(&message),
897 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
899 Available lint options:
900 -W <foo> Warn about <foo>
904 -F <foo> Forbid <foo> \
905 (deny <foo> and all attempts to override)
909 fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
910 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
911 lints.sort_by(|x: &&Lint, y: &&Lint| {
912 match x.default_level.cmp(&y.default_level) {
913 // The sort doesn't case-fold but it's doubtful we care.
914 Equal => x.name.cmp(y.name),
921 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
922 -> Vec<(&'static str, Vec<lint::LintId>)> {
923 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
924 lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
925 &(y, _): &(&'static str, Vec<lint::LintId>)| {
931 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
934 .partition(|&(_, p)| p);
935 let plugin = sort_lints(plugin);
936 let builtin = sort_lints(builtin);
938 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
941 .partition(|&(.., p)| p);
942 let plugin_groups = sort_lint_groups(plugin_groups);
943 let builtin_groups = sort_lint_groups(builtin_groups);
945 let max_name_len = plugin.iter()
947 .map(|&s| s.name.chars().count())
950 let padded = |x: &str| {
951 let mut s = repeat(" ")
952 .take(max_name_len - x.chars().count())
953 .collect::<String>();
958 println!("Lint checks provided by rustc:\n");
959 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
960 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
962 let print_lints = |lints: Vec<&Lint>| {
964 let name = lint.name_lower().replace("_", "-");
965 println!(" {} {:7.7} {}",
967 lint.default_level.as_str(),
973 print_lints(builtin);
977 let max_name_len = max("warnings".len(),
979 .chain(&builtin_groups)
980 .map(|&(s, _)| s.chars().count())
984 let padded = |x: &str| {
985 let mut s = repeat(" ")
986 .take(max_name_len - x.chars().count())
987 .collect::<String>();
992 println!("Lint groups provided by rustc:\n");
993 println!(" {} {}", padded("name"), "sub-lints");
994 println!(" {} {}", padded("----"), "---------");
995 println!(" {} {}", padded("warnings"), "all built-in lints");
997 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
998 for (name, to) in lints {
999 let name = name.to_lowercase().replace("_", "-");
1000 let desc = to.into_iter()
1001 .map(|x| x.to_string().replace("_", "-"))
1002 .collect::<Vec<String>>()
1004 println!(" {} {}", padded(&name), desc);
1009 print_lint_groups(builtin_groups);
1011 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
1012 (false, 0, _) | (false, _, 0) => {
1013 println!("Compiler plugins can provide additional lints and lint groups. To see a \
1014 listing of these, re-run `rustc -W help` with a crate filename.");
1016 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
1017 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
1020 println!("Lint checks provided by plugins loaded by this crate:\n");
1021 print_lints(plugin);
1024 println!("Lint groups provided by plugins loaded by this crate:\n");
1025 print_lint_groups(plugin_groups);
1031 fn describe_debug_flags() {
1032 println!("\nAvailable debug options:\n");
1033 print_flag_list("-Z", config::DB_OPTIONS);
1036 fn describe_codegen_flags() {
1037 println!("\nAvailable codegen options:\n");
1038 print_flag_list("-C", config::CG_OPTIONS);
1041 fn print_flag_list<T>(cmdline_opt: &str,
1042 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
1043 let max_len = flag_list.iter()
1044 .map(|&(name, _, opt_type_desc, _)| {
1045 let extra_len = match opt_type_desc {
1049 name.chars().count() + extra_len
1054 for &(name, _, opt_type_desc, desc) in flag_list {
1055 let (width, extra) = match opt_type_desc {
1056 Some(..) => (max_len - 4, "=val"),
1057 None => (max_len, ""),
1059 println!(" {} {:>width$}{} -- {}",
1061 name.replace("_", "-"),
1068 /// Process command line options. Emits messages as appropriate. If compilation
1069 /// should continue, returns a getopts::Matches object parsed from args,
1070 /// otherwise returns None.
1072 /// The compiler's handling of options is a little complicated as it ties into
1073 /// our stability story, and it's even *more* complicated by historical
1074 /// accidents. The current intention of each compiler option is to have one of
1077 /// 1. An option is stable and can be used everywhere.
1078 /// 2. An option is unstable, but was historically allowed on the stable
1080 /// 3. An option is unstable, and can only be used on nightly.
1082 /// Like unstable library and language features, however, unstable options have
1083 /// always required a form of "opt in" to indicate that you're using them. This
1084 /// provides the easy ability to scan a code base to check to see if anything
1085 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1087 /// All options behind `-Z` are considered unstable by default. Other top-level
1088 /// options can also be considered unstable, and they were unlocked through the
1089 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1090 /// instability in both cases, though.
1092 /// So with all that in mind, the comments below have some more detail about the
1093 /// contortions done here to get things to work out correctly.
1094 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
1095 // Throw away the first argument, the name of the binary
1096 let args = &args[1..];
1098 if args.is_empty() {
1099 // user did not write `-v` nor `-Z unstable-options`, so do not
1100 // include that extra information.
1101 usage(false, false);
1105 // Parse with *all* options defined in the compiler, we don't worry about
1106 // option stability here we just want to parse as much as possible.
1107 let mut options = getopts::Options::new();
1108 for option in config::rustc_optgroups() {
1109 (option.apply)(&mut options);
1111 let matches = match options.parse(args) {
1113 Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
1116 // For all options we just parsed, we check a few aspects:
1118 // * If the option is stable, we're all good
1119 // * If the option wasn't passed, we're all good
1120 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1121 // ourselves), then we require the `-Z unstable-options` flag to unlock
1122 // this option that was passed.
1123 // * If we're a nightly compiler, then unstable options are now unlocked, so
1124 // we're good to go.
1125 // * Otherwise, if we're a truly unstable option then we generate an error
1126 // (unstable option being used on stable)
1127 // * If we're a historically stable-but-should-be-unstable option then we
1128 // emit a warning that we're going to turn this into an error soon.
1129 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1131 if matches.opt_present("h") || matches.opt_present("help") {
1132 // Only show unstable options in --help if we *really* accept unstable
1133 // options, which catches the case where we got `-Z unstable-options` on
1134 // the stable channel of Rust which was accidentally allowed
1136 usage(matches.opt_present("verbose"),
1137 nightly_options::is_unstable_enabled(&matches));
1141 // Don't handle -W help here, because we might first load plugins.
1142 let r = matches.opt_strs("Z");
1143 if r.iter().any(|x| *x == "help") {
1144 describe_debug_flags();
1148 let cg_flags = matches.opt_strs("C");
1149 if cg_flags.iter().any(|x| *x == "help") {
1150 describe_codegen_flags();
1154 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1155 early_warn(ErrorOutputType::default(),
1156 "the --no-stack-check flag is deprecated and does nothing");
1159 if cg_flags.contains(&"passes=list".to_string()) {
1160 #[cfg(feature="llvm")]
1161 rustc_trans::print_passes();
1165 if matches.opt_present("version") {
1166 version("rustc", &matches);
1173 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1175 Input::File(ref ifile) => {
1176 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1178 Input::Str { ref name, ref input } => {
1179 parse::parse_crate_attrs_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
1184 /// Runs `f` in a suitable thread for running `rustc`; returns a
1185 /// `Result` with either the return value of `f` or -- if a panic
1186 /// occurs -- the panic value.
1187 pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<Any + Send>>
1188 where F: FnOnce() -> R + Send + 'static,
1191 // Temporarily have stack size set to 16MB to deal with nom-using crates failing
1192 const STACK_SIZE: usize = 16 * 1024 * 1024; // 16MB
1194 let mut cfg = thread::Builder::new().name("rustc".to_string());
1196 // FIXME: Hacks on hacks. If the env is trying to override the stack size
1197 // then *don't* set it explicitly.
1198 if env::var_os("RUST_MIN_STACK").is_none() {
1199 cfg = cfg.stack_size(STACK_SIZE);
1202 let thread = cfg.spawn(f);
1203 thread.unwrap().join()
1206 /// Run a procedure which will detect panics in the compiler and print nicer
1207 /// error messages rather than just failing the test.
1209 /// The diagnostic emitter yielded to the procedure should be used for reporting
1210 /// errors of the compiler.
1211 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
1212 struct Sink(Arc<Mutex<Vec<u8>>>);
1213 impl Write for Sink {
1214 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1215 Write::write(&mut *self.0.lock().unwrap(), data)
1217 fn flush(&mut self) -> io::Result<()> {
1222 let data = Arc::new(Mutex::new(Vec::new()));
1223 let err = Sink(data.clone());
1225 let result = in_rustc_thread(move || {
1226 io::set_panic(Some(box err));
1230 if let Err(value) = result {
1231 // Thread panicked without emitting a fatal diagnostic
1232 if !value.is::<errors::FatalError>() {
1234 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None));
1235 let handler = errors::Handler::with_emitter(true, false, emitter);
1237 // a .span_bug or .bug call has already printed what
1238 // it wants to print.
1239 if !value.is::<errors::ExplicitBug>() {
1240 handler.emit(&MultiSpan::new(),
1242 errors::Level::Bug);
1245 let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1246 format!("we would appreciate a bug report: {}", BUG_REPORT_URL),
1247 format!("rustc {} running on {}",
1248 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1249 config::host_triple())];
1251 handler.emit(&MultiSpan::new(),
1253 errors::Level::Note);
1255 if match env::var_os("RUST_BACKTRACE") {
1256 Some(val) => &val != "0",
1259 handler.emit(&MultiSpan::new(),
1260 "run with `RUST_BACKTRACE=1` for a backtrace",
1261 errors::Level::Note);
1264 writeln!(io::stderr(), "{}", str::from_utf8(&data.lock().unwrap()).unwrap()).unwrap();
1271 fn exit_on_err() -> ! {
1272 // Panic so the process returns a failure code, but don't pollute the
1273 // output with some unnecessary panic messages, we've already
1274 // printed everything that we needed to.
1275 io::set_panic(Some(box io::sink()));
1279 pub fn diagnostics_registry() -> errors::registry::Registry {
1280 use errors::registry::Registry;
1282 let mut all_errors = Vec::new();
1283 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1284 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1285 all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
1286 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1287 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1288 #[cfg(feature="llvm")]
1289 all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
1290 all_errors.extend_from_slice(&rustc_const_eval::DIAGNOSTICS);
1291 all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1292 all_errors.extend_from_slice(&rustc_passes::DIAGNOSTICS);
1293 all_errors.extend_from_slice(&rustc_plugin::DIAGNOSTICS);
1294 all_errors.extend_from_slice(&rustc_mir::DIAGNOSTICS);
1295 all_errors.extend_from_slice(&syntax::DIAGNOSTICS);
1297 Registry::new(&all_errors)
1300 pub fn get_args() -> Vec<String> {
1301 env::args_os().enumerate()
1302 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1303 early_error(ErrorOutputType::default(),
1304 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1310 env_logger::init().unwrap();
1311 let result = run(|| run_compiler(&get_args(),
1312 &mut RustcDefaultCalls,
1315 process::exit(result as i32);