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 #[cfg(feature="llvm")]
51 pub extern crate rustc_trans;
52 extern crate rustc_trans_utils;
53 extern crate rustc_typeck;
54 extern crate serialize;
58 extern crate syntax_ext;
59 extern crate syntax_pos;
61 use driver::CompileController;
62 use pretty::{PpMode, UserIdentifiedItem};
64 use rustc_resolve as resolve;
65 use rustc_save_analysis as save;
66 use rustc_save_analysis::DumpHandler;
67 use rustc::session::{self, config, Session, build_session, CompileResult};
68 use rustc::session::CompileIncomplete;
69 use rustc::session::config::{Input, PrintRequest, ErrorOutputType};
70 use rustc::session::config::nightly_options;
71 use rustc::session::{early_error, early_warn};
72 use rustc::lint::Lint;
74 use rustc::middle::cstore::CrateStore;
75 use rustc_metadata::locator;
76 use rustc_metadata::cstore::CStore;
77 use rustc::util::common::{time, ErrorReported};
78 use rustc_trans_utils::trans_crate::TransCrate;
80 use serialize::json::ToJson;
84 use std::cmp::Ordering::Equal;
85 use std::default::Default;
87 use std::ffi::OsString;
88 use std::io::{self, Read, Write};
89 use std::iter::repeat;
90 use std::path::PathBuf;
91 use std::process::{self, Command, Stdio};
94 use std::sync::{Arc, Mutex};
98 use syntax::codemap::{CodeMap, FileLoader, RealFileLoader};
99 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
100 use syntax::parse::{self, PResult};
101 use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
109 mod derive_registrar;
111 pub mod target_features {
113 use syntax::symbol::Symbol;
114 use rustc::session::Session;
115 use rustc_trans_utils::trans_crate::TransCrate;
117 /// Add `target_feature = "..."` cfgs for a variety of platform
118 /// specific features (SSE, NEON etc.).
120 /// This is performed by checking whether a whitelisted set of
121 /// features is available on the target machine, by querying LLVM.
122 pub fn add_configuration(cfg: &mut ast::CrateConfig, sess: &Session, trans: &TransCrate) {
123 let tf = Symbol::intern("target_feature");
125 for feat in trans.target_features(sess) {
126 cfg.insert((tf, Some(feat)));
129 if sess.crt_static_feature() {
130 cfg.insert((tf, Some(Symbol::intern("crt-static"))));
135 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
138 pub fn abort_on_err<T>(result: Result<T, CompileIncomplete>, sess: &Session) -> T {
140 Err(CompileIncomplete::Errored(ErrorReported)) => {
141 sess.abort_if_errors();
142 panic!("error reported but abort_if_errors didn't abort???");
144 Err(CompileIncomplete::Stopped) => {
145 sess.fatal("compilation terminated");
151 pub fn run<F>(run_compiler: F) -> isize
152 where F: FnOnce() -> (CompileResult, Option<Session>) + Send + 'static
155 let (result, session) = run_compiler();
156 if let Err(CompileIncomplete::Errored(_)) = result {
159 sess.abort_if_errors();
160 panic!("error reported but abort_if_errors didn't abort???");
164 errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
167 let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
168 handler.emit(&MultiSpan::new(),
169 "aborting due to previous error(s)",
170 errors::Level::Fatal);
179 #[cfg(not(feature="llvm"))]
180 pub use rustc_trans_utils::trans_crate::MetadataOnlyTransCrate as DefaultTransCrate;
181 #[cfg(feature="llvm")]
182 pub use rustc_trans::LlvmTransCrate as DefaultTransCrate;
184 #[cfg(not(feature="llvm"))]
185 pub mod rustc_trans {
186 pub use rustc_trans_utils::trans_crate::MetadataOnlyTransCrate as LlvmTransCrate;
188 pub fn print_version() {}
189 pub fn print_passes() {}
192 fn load_backend_from_dylib(sess: &Session, backend_name: &str) -> Box<TransCrate> {
195 use syntax::symbol::Symbol;
196 use rustc::session::config::OutputFilenames;
197 use rustc::ty::TyCtxt;
198 use rustc::ty::maps::Providers;
199 use rustc::middle::cstore::MetadataLoader;
200 use rustc::dep_graph::DepGraph;
201 use rustc_metadata::dynamic_lib::DynamicLibrary;
202 /// This prevents the dylib from being unloaded when there is still a TransCrate open
203 struct ExternTransCrate {
204 _lib: DynamicLibrary,
205 trans: Box<TransCrate>,
208 impl Drop for ExternTransCrate {
210 // Make sure trans gets dropped before _lib as bad things happen otherwise
211 self.trans = Box::new(::rustc_trans_utils::trans_crate::DummyTransCrate)
215 impl TransCrate for ExternTransCrate {
216 fn print(&self, req: PrintRequest, sess: &Session) {
217 self.trans.print(req, sess);
219 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
220 self.trans.target_features((sess))
223 fn metadata_loader(&self) -> Box<MetadataLoader> {
224 self.trans.metadata_loader()
226 fn provide(&self, providers: &mut Providers) {
227 self.trans.provide(providers)
229 fn provide_extern(&self, providers: &mut Providers) {
230 self.trans.provide_extern(providers)
232 fn trans_crate<'a, 'tcx>(
234 tcx: TyCtxt<'a, 'tcx, 'tcx>,
235 rx: mpsc::Receiver<Box<Any + Send>>
237 self.trans.trans_crate(tcx, rx)
240 fn join_trans_and_link(
244 dep_graph: &DepGraph,
245 outputs: &OutputFilenames,
246 ) -> Result<(), CompileIncomplete> {
247 self.trans.join_trans_and_link(trans, sess, dep_graph, outputs)
251 match DynamicLibrary::open(Some(Path::new(backend_name))) {
255 let __rustc_codegen_backend: unsafe fn(&Session) -> Box<TransCrate>;
256 __rustc_codegen_backend = match lib.symbol("__rustc_codegen_backend") {
257 Ok(f) => ::std::mem::transmute::<*mut u8, _>(f),
258 Err(e) => sess.fatal(&format!("Couldnt load codegen backend as it\
259 doesn't export the __rustc_backend_new symbol: {:?}", e)),
261 __rustc_codegen_backend(sess)
263 Box::new(ExternTransCrate {
270 sess.fatal(&format!("Couldnt load codegen backend {:?}: {:?}", backend_name, err));
275 pub fn get_trans(sess: &Session) -> Box<TransCrate> {
276 let trans_name = sess.opts.debugging_opts.codegen_backend.clone();
277 match trans_name.as_ref().map(|s|&**s) {
278 None => DefaultTransCrate::new(&sess),
279 Some("llvm") => rustc_trans::LlvmTransCrate::new(&sess),
280 Some("metadata_only") => {
281 rustc_trans_utils::trans_crate::MetadataOnlyTransCrate::new(&sess)
283 Some(filename) if filename.contains(".") => {
284 load_backend_from_dylib(&sess, &filename)
286 Some(trans_name) => sess.fatal(&format!("Unknown codegen backend {}", trans_name)),
290 // Parse args and run the compiler. This is the primary entry point for rustc.
291 // See comments on CompilerCalls below for details about the callbacks argument.
292 // The FileLoader provides a way to load files from sources other than the file system.
293 pub fn run_compiler<'a>(args: &[String],
294 callbacks: &mut CompilerCalls<'a>,
295 file_loader: Option<Box<FileLoader + 'static>>,
296 emitter_dest: Option<Box<Write + Send>>)
297 -> (CompileResult, Option<Session>)
299 macro_rules! do_or_return {($expr: expr, $sess: expr) => {
301 Compilation::Stop => return (Ok(()), $sess),
302 Compilation::Continue => {}
306 let matches = match handle_options(args) {
307 Some(matches) => matches,
308 None => return (Ok(()), None),
311 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
313 let descriptions = diagnostics_registry();
315 do_or_return!(callbacks.early_callback(&matches,
322 let (odir, ofile) = make_output(&matches);
323 let (input, input_file_path) = match make_input(&matches.free) {
324 Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
325 None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) {
326 Some((input, input_file_path)) => (input, input_file_path),
327 None => return (Ok(()), None),
331 let loader = file_loader.unwrap_or(box RealFileLoader);
332 let codemap = Rc::new(CodeMap::with_file_loader(loader, sopts.file_path_mapping()));
333 let mut sess = session::build_session_with_codemap(
334 sopts, input_file_path.clone(), descriptions, codemap, emitter_dest,
337 let trans = get_trans(&sess);
339 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
341 let mut cfg = config::build_configuration(&sess, cfg);
342 target_features::add_configuration(&mut cfg, &sess, &*trans);
343 sess.parse_sess.config = cfg;
345 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
347 let cstore = CStore::new(trans.metadata_loader());
349 do_or_return!(callbacks.late_callback(&*trans,
355 &ofile), Some(sess));
357 let control = callbacks.build_controller(&sess, &matches);
359 (driver::compile_input(trans,
371 // Extract output directory and file from matches.
372 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
373 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
374 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
378 // Extract input (string or file and optional path) from matches.
379 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
380 if free_matches.len() == 1 {
381 let ifile = &free_matches[0];
383 let mut src = String::new();
384 io::stdin().read_to_string(&mut src).unwrap();
385 Some((Input::Str { name: FileName::Anon, input: src },
388 Some((Input::File(PathBuf::from(ifile)),
389 Some(PathBuf::from(ifile))))
396 fn parse_pretty(sess: &Session,
397 matches: &getopts::Matches)
398 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
399 let pretty = if sess.opts.debugging_opts.unstable_options {
400 matches.opt_default("pretty", "normal").map(|a| {
401 // stable pretty-print variants only
402 pretty::parse_pretty(sess, &a, false)
407 if pretty.is_none() && sess.unstable_options() {
408 matches.opt_str("unpretty").map(|a| {
409 // extended with unstable pretty-print variants
410 pretty::parse_pretty(sess, &a, true)
417 // Whether to stop or continue compilation.
418 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
419 pub enum Compilation {
425 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
427 Compilation::Stop => Compilation::Stop,
428 Compilation::Continue => next(),
433 // A trait for customising the compilation process. Offers a number of hooks for
434 // executing custom code or customising input.
435 pub trait CompilerCalls<'a> {
436 // Hook for a callback early in the process of handling arguments. This will
437 // be called straight after options have been parsed but before anything
438 // else (e.g., selecting input and output).
439 fn early_callback(&mut self,
440 _: &getopts::Matches,
442 _: &ast::CrateConfig,
443 _: &errors::registry::Registry,
446 Compilation::Continue
449 // Hook for a callback late in the process of handling arguments. This will
450 // be called just before actual compilation starts (and before build_controller
451 // is called), after all arguments etc. have been completely handled.
452 fn late_callback(&mut self,
454 _: &getopts::Matches,
461 Compilation::Continue
464 // Called after we extract the input from the arguments. Gives the implementer
465 // an opportunity to change the inputs or to add some custom input handling.
466 // The default behaviour is to simply pass through the inputs.
467 fn some_input(&mut self,
469 input_path: Option<PathBuf>)
470 -> (Input, Option<PathBuf>) {
474 // Called after we extract the input from the arguments if there is no valid
475 // input. Gives the implementer an opportunity to supply alternate input (by
476 // returning a Some value) or to add custom behaviour for this error such as
477 // emitting error messages. Returning None will cause compilation to stop
479 fn no_input(&mut self,
480 _: &getopts::Matches,
482 _: &ast::CrateConfig,
485 _: &errors::registry::Registry)
486 -> Option<(Input, Option<PathBuf>)> {
490 // Create a CompilController struct for controlling the behaviour of
492 fn build_controller(&mut self, _: &Session, _: &getopts::Matches) -> CompileController<'a>;
495 // CompilerCalls instance for a regular rustc build.
496 #[derive(Copy, Clone)]
497 pub struct RustcDefaultCalls;
499 // FIXME remove these and use winapi 0.3 instead
500 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
502 fn stdout_isatty() -> bool {
503 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
507 fn stdout_isatty() -> bool {
510 type HANDLE = *mut u8;
511 type LPDWORD = *mut u32;
512 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
514 fn GetStdHandle(which: DWORD) -> HANDLE;
515 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
518 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
520 GetConsoleMode(handle, &mut out) != 0
524 fn handle_explain(code: &str,
525 descriptions: &errors::registry::Registry,
526 output: ErrorOutputType) {
527 let normalised = if code.starts_with("E") {
530 format!("E{0:0>4}", code)
532 match descriptions.find_description(&normalised) {
533 Some(ref description) => {
534 let mut is_in_code_block = false;
535 let mut text = String::new();
537 // Slice off the leading newline and print.
538 for line in description[1..].lines() {
539 let indent_level = line.find(|c: char| !c.is_whitespace())
540 .unwrap_or_else(|| line.len());
541 let dedented_line = &line[indent_level..];
542 if dedented_line.starts_with("```") {
543 is_in_code_block = !is_in_code_block;
544 text.push_str(&line[..(indent_level+3)]);
545 } else if is_in_code_block && dedented_line.starts_with("# ") {
554 show_content_with_pager(&text);
560 early_error(output, &format!("no extended information for {}", code));
565 fn show_content_with_pager(content: &String) {
566 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
567 OsString::from("more.com")
569 OsString::from("less")
572 let mut fallback_to_println = false;
574 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
576 if let Some(pipe) = pager.stdin.as_mut() {
577 if pipe.write_all(content.as_bytes()).is_err() {
578 fallback_to_println = true;
582 if pager.wait().is_err() {
583 fallback_to_println = true;
587 fallback_to_println = true;
591 // If pager fails for whatever reason, we should still print the content
592 // to standard output
593 if fallback_to_println {
594 print!("{}", content);
598 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
599 fn early_callback(&mut self,
600 matches: &getopts::Matches,
602 _: &ast::CrateConfig,
603 descriptions: &errors::registry::Registry,
604 output: ErrorOutputType)
606 if let Some(ref code) = matches.opt_str("explain") {
607 handle_explain(code, descriptions, output);
608 return Compilation::Stop;
611 Compilation::Continue
614 fn no_input(&mut self,
615 matches: &getopts::Matches,
616 sopts: &config::Options,
617 cfg: &ast::CrateConfig,
618 odir: &Option<PathBuf>,
619 ofile: &Option<PathBuf>,
620 descriptions: &errors::registry::Registry)
621 -> Option<(Input, Option<PathBuf>)> {
622 match matches.free.len() {
624 if sopts.describe_lints {
625 let mut ls = lint::LintStore::new();
626 rustc_lint::register_builtins(&mut ls, None);
627 describe_lints(&ls, false);
630 let mut sess = build_session(sopts.clone(),
632 descriptions.clone());
633 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
634 let mut cfg = config::build_configuration(&sess, cfg.clone());
635 let trans = get_trans(&sess);
636 target_features::add_configuration(&mut cfg, &sess, &*trans);
637 sess.parse_sess.config = cfg;
638 let should_stop = RustcDefaultCalls::print_crate_info(
646 if should_stop == Compilation::Stop {
649 early_error(sopts.error_format, "no input filename given");
651 1 => panic!("make_input should have provided valid inputs"),
652 _ => early_error(sopts.error_format, "multiple input filenames provided"),
656 fn late_callback(&mut self,
658 matches: &getopts::Matches,
662 odir: &Option<PathBuf>,
663 ofile: &Option<PathBuf>)
665 RustcDefaultCalls::print_crate_info(trans, sess, Some(input), odir, ofile)
666 .and_then(|| RustcDefaultCalls::list_metadata(sess, cstore, matches, input))
669 fn build_controller(&mut self,
671 matches: &getopts::Matches)
672 -> CompileController<'a> {
673 let mut control = CompileController::basic();
675 control.keep_ast = sess.opts.debugging_opts.keep_ast;
676 control.continue_parse_after_error = sess.opts.debugging_opts.continue_parse_after_error;
678 if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
679 if ppm.needs_ast_map(&opt_uii) {
680 control.after_hir_lowering.stop = Compilation::Stop;
682 control.after_parse.callback = box move |state| {
683 state.krate = Some(pretty::fold_crate(state.session,
684 state.krate.take().unwrap(),
687 control.after_hir_lowering.callback = box move |state| {
688 pretty::print_after_hir_lowering(state.session,
689 state.cstore.unwrap(),
690 state.hir_map.unwrap(),
691 state.analysis.unwrap(),
692 state.resolutions.unwrap(),
694 &state.expanded_crate.take().unwrap(),
695 state.crate_name.unwrap(),
697 state.arenas.unwrap(),
698 state.output_filenames.unwrap(),
703 control.after_parse.stop = Compilation::Stop;
705 control.after_parse.callback = box move |state| {
706 let krate = pretty::fold_crate(state.session, state.krate.take().unwrap(), ppm);
707 pretty::print_after_parsing(state.session,
718 if sess.opts.debugging_opts.parse_only ||
719 sess.opts.debugging_opts.show_span.is_some() ||
720 sess.opts.debugging_opts.ast_json_noexpand {
721 control.after_parse.stop = Compilation::Stop;
724 if sess.opts.debugging_opts.no_analysis ||
725 sess.opts.debugging_opts.ast_json {
726 control.after_hir_lowering.stop = Compilation::Stop;
729 if save_analysis(sess) {
730 enable_save_analysis(&mut control);
733 if sess.print_fuel_crate.is_some() {
734 let old_callback = control.compilation_done.callback;
735 control.compilation_done.callback = box move |state| {
737 let sess = state.session;
738 println!("Fuel used by {}: {}",
739 sess.print_fuel_crate.as_ref().unwrap(),
740 sess.print_fuel.get());
747 pub fn enable_save_analysis(control: &mut CompileController) {
748 control.keep_ast = true;
749 control.after_analysis.callback = box |state| {
750 time(state.session.time_passes(), "save analysis", || {
751 save::process_crate(state.tcx.unwrap(),
752 state.expanded_crate.unwrap(),
753 state.analysis.unwrap(),
754 state.crate_name.unwrap(),
756 DumpHandler::new(state.out_dir,
757 state.crate_name.unwrap()))
760 control.after_analysis.run_callback_on_error = true;
761 control.make_glob_map = resolve::MakeGlobMap::Yes;
764 fn save_analysis(sess: &Session) -> bool {
765 sess.opts.debugging_opts.save_analysis
768 impl RustcDefaultCalls {
769 pub fn list_metadata(sess: &Session,
771 matches: &getopts::Matches,
774 let r = matches.opt_strs("Z");
775 if r.contains(&("ls".to_string())) {
777 &Input::File(ref ifile) => {
778 let path = &(*ifile);
779 let mut v = Vec::new();
780 locator::list_file_metadata(&sess.target.target,
782 cstore.metadata_loader(),
785 println!("{}", String::from_utf8(v).unwrap());
787 &Input::Str { .. } => {
788 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
791 return Compilation::Stop;
794 return Compilation::Continue;
798 fn print_crate_info(trans: &TransCrate,
800 input: Option<&Input>,
801 odir: &Option<PathBuf>,
802 ofile: &Option<PathBuf>)
804 use rustc::session::config::PrintRequest::*;
805 // PrintRequest::NativeStaticLibs is special - printed during linking
806 // (empty iterator returns true)
807 if sess.opts.prints.iter().all(|&p| p==PrintRequest::NativeStaticLibs) {
808 return Compilation::Continue;
811 let attrs = match input {
814 let result = parse_crate_attrs(sess, input);
816 Ok(attrs) => Some(attrs),
817 Err(mut parse_error) => {
819 return Compilation::Stop;
824 for req in &sess.opts.prints {
827 let mut targets = rustc_back::target::get_targets().collect::<Vec<String>>();
829 println!("{}", targets.join("\n"));
831 Sysroot => println!("{}", sess.sysroot().display()),
832 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
833 FileNames | CrateName => {
834 let input = match input {
835 Some(input) => input,
836 None => early_error(ErrorOutputType::default(), "no input file provided"),
838 let attrs = attrs.as_ref().unwrap();
839 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
840 let id = rustc_trans_utils::link::find_crate_name(Some(sess), attrs, input);
841 if *req == PrintRequest::CrateName {
845 let crate_types = driver::collect_crate_types(sess, attrs);
846 for &style in &crate_types {
847 let fname = rustc_trans_utils::link::filename_for_input(
860 let allow_unstable_cfg = UnstableFeatures::from_environment()
863 let mut cfgs = Vec::new();
864 for &(name, ref value) in sess.parse_sess.config.iter() {
865 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
867 node: ast::MetaItemKind::Word,
871 // Note that crt-static is a specially recognized cfg
872 // directive that's printed out here as part of
873 // rust-lang/rust#37406, but in general the
874 // `target_feature` cfg is gated under
875 // rust-lang/rust#29717. For now this is just
876 // specifically allowing the crt-static cfg and that's
877 // it, this is intended to get into Cargo and then go
878 // through to build scripts.
879 let value = value.as_ref().map(|s| s.as_str());
880 let value = value.as_ref().map(|s| s.as_ref());
881 if name != "target_feature" || value != Some("crt-static") {
882 if !allow_unstable_cfg && gated_cfg.is_some() {
887 cfgs.push(if let Some(value) = value {
888 format!("{}=\"{}\"", name, value)
899 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
900 trans.print(*req, sess);
902 // Any output here interferes with Cargo's parsing of other printed output
903 PrintRequest::NativeStaticLibs => {}
906 return Compilation::Stop;
910 /// Returns a version string such as "0.12.0-dev".
911 fn release_str() -> Option<&'static str> {
912 option_env!("CFG_RELEASE")
915 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
916 fn commit_hash_str() -> Option<&'static str> {
917 option_env!("CFG_VER_HASH")
920 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
921 fn commit_date_str() -> Option<&'static str> {
922 option_env!("CFG_VER_DATE")
925 /// Prints version information
926 pub fn version(binary: &str, matches: &getopts::Matches) {
927 let verbose = matches.opt_present("verbose");
931 option_env!("CFG_VERSION").unwrap_or("unknown version"));
933 fn unw(x: Option<&str>) -> &str {
934 x.unwrap_or("unknown")
936 println!("binary: {}", binary);
937 println!("commit-hash: {}", unw(commit_hash_str()));
938 println!("commit-date: {}", unw(commit_date_str()));
939 println!("host: {}", config::host_triple());
940 println!("release: {}", unw(release_str()));
941 rustc_trans::print_version();
945 fn usage(verbose: bool, include_unstable_options: bool) {
946 let groups = if verbose {
947 config::rustc_optgroups()
949 config::rustc_short_optgroups()
951 let mut options = getopts::Options::new();
952 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
953 (option.apply)(&mut options);
955 let message = format!("Usage: rustc [OPTIONS] INPUT");
956 let nightly_help = if nightly_options::is_nightly_build() {
957 "\n -Z help Print internal options for debugging rustc"
961 let verbose_help = if verbose {
964 "\n --help -v Print the full set of options rustc accepts"
966 println!("{}\nAdditional help:
967 -C help Print codegen options
969 Print 'lint' options and default settings{}{}\n",
970 options.usage(&message),
975 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
977 Available lint options:
978 -W <foo> Warn about <foo>
982 -F <foo> Forbid <foo> \
983 (deny <foo> and all attempts to override)
987 fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
988 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
989 lints.sort_by(|x: &&Lint, y: &&Lint| {
990 match x.default_level.cmp(&y.default_level) {
991 // The sort doesn't case-fold but it's doubtful we care.
992 Equal => x.name.cmp(y.name),
999 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
1000 -> Vec<(&'static str, Vec<lint::LintId>)> {
1001 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
1002 lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
1003 &(y, _): &(&'static str, Vec<lint::LintId>)| {
1009 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
1012 .partition(|&(_, p)| p);
1013 let plugin = sort_lints(plugin);
1014 let builtin = sort_lints(builtin);
1016 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
1019 .partition(|&(.., p)| p);
1020 let plugin_groups = sort_lint_groups(plugin_groups);
1021 let builtin_groups = sort_lint_groups(builtin_groups);
1023 let max_name_len = plugin.iter()
1025 .map(|&s| s.name.chars().count())
1028 let padded = |x: &str| {
1029 let mut s = repeat(" ")
1030 .take(max_name_len - x.chars().count())
1031 .collect::<String>();
1036 println!("Lint checks provided by rustc:\n");
1037 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
1038 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
1040 let print_lints = |lints: Vec<&Lint>| {
1042 let name = lint.name_lower().replace("_", "-");
1043 println!(" {} {:7.7} {}",
1045 lint.default_level.as_str(),
1051 print_lints(builtin);
1055 let max_name_len = max("warnings".len(),
1056 plugin_groups.iter()
1057 .chain(&builtin_groups)
1058 .map(|&(s, _)| s.chars().count())
1062 let padded = |x: &str| {
1063 let mut s = repeat(" ")
1064 .take(max_name_len - x.chars().count())
1065 .collect::<String>();
1070 println!("Lint groups provided by rustc:\n");
1071 println!(" {} {}", padded("name"), "sub-lints");
1072 println!(" {} {}", padded("----"), "---------");
1073 println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
1075 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
1076 for (name, to) in lints {
1077 let name = name.to_lowercase().replace("_", "-");
1078 let desc = to.into_iter()
1079 .map(|x| x.to_string().replace("_", "-"))
1080 .collect::<Vec<String>>()
1082 println!(" {} {}", padded(&name), desc);
1087 print_lint_groups(builtin_groups);
1089 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
1090 (false, 0, _) | (false, _, 0) => {
1091 println!("Compiler plugins can provide additional lints and lint groups. To see a \
1092 listing of these, re-run `rustc -W help` with a crate filename.");
1094 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
1095 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
1098 println!("Lint checks provided by plugins loaded by this crate:\n");
1099 print_lints(plugin);
1102 println!("Lint groups provided by plugins loaded by this crate:\n");
1103 print_lint_groups(plugin_groups);
1109 fn describe_debug_flags() {
1110 println!("\nAvailable debug options:\n");
1111 print_flag_list("-Z", config::DB_OPTIONS);
1114 fn describe_codegen_flags() {
1115 println!("\nAvailable codegen options:\n");
1116 print_flag_list("-C", config::CG_OPTIONS);
1119 fn print_flag_list<T>(cmdline_opt: &str,
1120 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
1121 let max_len = flag_list.iter()
1122 .map(|&(name, _, opt_type_desc, _)| {
1123 let extra_len = match opt_type_desc {
1127 name.chars().count() + extra_len
1132 for &(name, _, opt_type_desc, desc) in flag_list {
1133 let (width, extra) = match opt_type_desc {
1134 Some(..) => (max_len - 4, "=val"),
1135 None => (max_len, ""),
1137 println!(" {} {:>width$}{} -- {}",
1139 name.replace("_", "-"),
1146 /// Process command line options. Emits messages as appropriate. If compilation
1147 /// should continue, returns a getopts::Matches object parsed from args,
1148 /// otherwise returns None.
1150 /// The compiler's handling of options is a little complicated as it ties into
1151 /// our stability story, and it's even *more* complicated by historical
1152 /// accidents. The current intention of each compiler option is to have one of
1155 /// 1. An option is stable and can be used everywhere.
1156 /// 2. An option is unstable, but was historically allowed on the stable
1158 /// 3. An option is unstable, and can only be used on nightly.
1160 /// Like unstable library and language features, however, unstable options have
1161 /// always required a form of "opt in" to indicate that you're using them. This
1162 /// provides the easy ability to scan a code base to check to see if anything
1163 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1165 /// All options behind `-Z` are considered unstable by default. Other top-level
1166 /// options can also be considered unstable, and they were unlocked through the
1167 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1168 /// instability in both cases, though.
1170 /// So with all that in mind, the comments below have some more detail about the
1171 /// contortions done here to get things to work out correctly.
1172 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
1173 // Throw away the first argument, the name of the binary
1174 let args = &args[1..];
1176 if args.is_empty() {
1177 // user did not write `-v` nor `-Z unstable-options`, so do not
1178 // include that extra information.
1179 usage(false, false);
1183 // Parse with *all* options defined in the compiler, we don't worry about
1184 // option stability here we just want to parse as much as possible.
1185 let mut options = getopts::Options::new();
1186 for option in config::rustc_optgroups() {
1187 (option.apply)(&mut options);
1189 let matches = match options.parse(args) {
1191 Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
1194 // For all options we just parsed, we check a few aspects:
1196 // * If the option is stable, we're all good
1197 // * If the option wasn't passed, we're all good
1198 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1199 // ourselves), then we require the `-Z unstable-options` flag to unlock
1200 // this option that was passed.
1201 // * If we're a nightly compiler, then unstable options are now unlocked, so
1202 // we're good to go.
1203 // * Otherwise, if we're a truly unstable option then we generate an error
1204 // (unstable option being used on stable)
1205 // * If we're a historically stable-but-should-be-unstable option then we
1206 // emit a warning that we're going to turn this into an error soon.
1207 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1209 if matches.opt_present("h") || matches.opt_present("help") {
1210 // Only show unstable options in --help if we *really* accept unstable
1211 // options, which catches the case where we got `-Z unstable-options` on
1212 // the stable channel of Rust which was accidentally allowed
1214 usage(matches.opt_present("verbose"),
1215 nightly_options::is_unstable_enabled(&matches));
1219 // Don't handle -W help here, because we might first load plugins.
1220 let r = matches.opt_strs("Z");
1221 if r.iter().any(|x| *x == "help") {
1222 describe_debug_flags();
1226 let cg_flags = matches.opt_strs("C");
1227 if cg_flags.iter().any(|x| *x == "help") {
1228 describe_codegen_flags();
1232 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1233 early_warn(ErrorOutputType::default(),
1234 "the --no-stack-check flag is deprecated and does nothing");
1237 if cg_flags.contains(&"passes=list".to_string()) {
1238 rustc_trans::print_passes();
1242 if matches.opt_present("version") {
1243 version("rustc", &matches);
1250 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1252 Input::File(ref ifile) => {
1253 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1255 Input::Str { ref name, ref input } => {
1256 parse::parse_crate_attrs_from_source_str(name.clone(),
1263 /// Runs `f` in a suitable thread for running `rustc`; returns a
1264 /// `Result` with either the return value of `f` or -- if a panic
1265 /// occurs -- the panic value.
1266 pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<Any + Send>>
1267 where F: FnOnce() -> R + Send + 'static,
1270 // Temporarily have stack size set to 16MB to deal with nom-using crates failing
1271 const STACK_SIZE: usize = 16 * 1024 * 1024; // 16MB
1273 let mut cfg = thread::Builder::new().name("rustc".to_string());
1275 // FIXME: Hacks on hacks. If the env is trying to override the stack size
1276 // then *don't* set it explicitly.
1277 if env::var_os("RUST_MIN_STACK").is_none() {
1278 cfg = cfg.stack_size(STACK_SIZE);
1281 let thread = cfg.spawn(f);
1282 thread.unwrap().join()
1285 /// Run a procedure which will detect panics in the compiler and print nicer
1286 /// error messages rather than just failing the test.
1288 /// The diagnostic emitter yielded to the procedure should be used for reporting
1289 /// errors of the compiler.
1290 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
1291 struct Sink(Arc<Mutex<Vec<u8>>>);
1292 impl Write for Sink {
1293 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1294 Write::write(&mut *self.0.lock().unwrap(), data)
1296 fn flush(&mut self) -> io::Result<()> {
1301 let data = Arc::new(Mutex::new(Vec::new()));
1302 let err = Sink(data.clone());
1304 let result = in_rustc_thread(move || {
1305 io::set_panic(Some(box err));
1309 if let Err(value) = result {
1310 // Thread panicked without emitting a fatal diagnostic
1311 if !value.is::<errors::FatalError>() {
1313 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
1316 let handler = errors::Handler::with_emitter(true, false, emitter);
1318 // a .span_bug or .bug call has already printed what
1319 // it wants to print.
1320 if !value.is::<errors::ExplicitBug>() {
1321 handler.emit(&MultiSpan::new(),
1323 errors::Level::Bug);
1326 let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1327 format!("we would appreciate a bug report: {}", BUG_REPORT_URL),
1328 format!("rustc {} running on {}",
1329 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1330 config::host_triple())];
1332 handler.emit(&MultiSpan::new(),
1334 errors::Level::Note);
1336 if match env::var_os("RUST_BACKTRACE") {
1337 Some(val) => &val != "0",
1340 handler.emit(&MultiSpan::new(),
1341 "run with `RUST_BACKTRACE=1` for a backtrace",
1342 errors::Level::Note);
1345 eprintln!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
1352 fn exit_on_err() -> ! {
1353 // Panic so the process returns a failure code, but don't pollute the
1354 // output with some unnecessary panic messages, we've already
1355 // printed everything that we needed to.
1356 io::set_panic(Some(box io::sink()));
1361 pub fn diagnostics_registry() -> errors::registry::Registry {
1362 use errors::registry::Registry;
1368 pub fn diagnostics_registry() -> errors::registry::Registry {
1369 use errors::registry::Registry;
1371 let mut all_errors = Vec::new();
1372 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1373 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1374 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1375 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1376 #[cfg(feature="llvm")]
1377 all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
1378 all_errors.extend_from_slice(&rustc_trans_utils::DIAGNOSTICS);
1379 all_errors.extend_from_slice(&rustc_const_eval::DIAGNOSTICS);
1380 all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1381 all_errors.extend_from_slice(&rustc_passes::DIAGNOSTICS);
1382 all_errors.extend_from_slice(&rustc_plugin::DIAGNOSTICS);
1383 all_errors.extend_from_slice(&rustc_mir::DIAGNOSTICS);
1384 all_errors.extend_from_slice(&syntax::DIAGNOSTICS);
1386 Registry::new(&all_errors)
1389 pub fn get_args() -> Vec<String> {
1390 env::args_os().enumerate()
1391 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1392 early_error(ErrorOutputType::default(),
1393 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1399 env_logger::init().unwrap();
1400 let result = run(|| run_compiler(&get_args(),
1401 &mut RustcDefaultCalls,
1404 process::exit(result as i32);