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> {
194 use rustc_metadata::dynamic_lib::DynamicLibrary;
196 match DynamicLibrary::open(Some(Path::new(backend_name))) {
200 let __rustc_codegen_backend: unsafe fn(&Session) -> Box<TransCrate>;
201 __rustc_codegen_backend = match lib.symbol("__rustc_codegen_backend") {
202 Ok(f) => ::std::mem::transmute::<*mut u8, _>(f),
203 Err(e) => sess.fatal(&format!("Couldnt load codegen backend as it\
204 doesn't export the __rustc_backend_new symbol: {:?}", e)),
206 __rustc_codegen_backend(sess)
208 ::std::mem::forget(lib);
213 sess.fatal(&format!("Couldnt load codegen backend {:?}: {:?}", backend_name, err));
218 pub fn get_trans(sess: &Session) -> Box<TransCrate> {
219 let trans_name = sess.opts.debugging_opts.codegen_backend.clone();
220 match trans_name.as_ref().map(|s|&**s) {
221 None => DefaultTransCrate::new(&sess),
222 Some("llvm") => rustc_trans::LlvmTransCrate::new(&sess),
223 Some("metadata_only") => {
224 rustc_trans_utils::trans_crate::MetadataOnlyTransCrate::new(&sess)
226 Some(filename) if filename.contains(".") => {
227 load_backend_from_dylib(&sess, &filename)
229 Some(trans_name) => sess.fatal(&format!("Unknown codegen backend {}", trans_name)),
233 // Parse args and run the compiler. This is the primary entry point for rustc.
234 // See comments on CompilerCalls below for details about the callbacks argument.
235 // The FileLoader provides a way to load files from sources other than the file system.
236 pub fn run_compiler<'a>(args: &[String],
237 callbacks: &mut CompilerCalls<'a>,
238 file_loader: Option<Box<FileLoader + 'static>>,
239 emitter_dest: Option<Box<Write + Send>>)
240 -> (CompileResult, Option<Session>)
242 macro_rules! do_or_return {($expr: expr, $sess: expr) => {
244 Compilation::Stop => return (Ok(()), $sess),
245 Compilation::Continue => {}
249 let matches = match handle_options(args) {
250 Some(matches) => matches,
251 None => return (Ok(()), None),
254 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
256 let descriptions = diagnostics_registry();
258 do_or_return!(callbacks.early_callback(&matches,
265 let (odir, ofile) = make_output(&matches);
266 let (input, input_file_path) = match make_input(&matches.free) {
267 Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
268 None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) {
269 Some((input, input_file_path)) => (input, input_file_path),
270 None => return (Ok(()), None),
274 let loader = file_loader.unwrap_or(box RealFileLoader);
275 let codemap = Rc::new(CodeMap::with_file_loader(loader, sopts.file_path_mapping()));
276 let mut sess = session::build_session_with_codemap(
277 sopts, input_file_path.clone(), descriptions, codemap, emitter_dest,
280 let trans = get_trans(&sess);
282 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
284 let mut cfg = config::build_configuration(&sess, cfg);
285 target_features::add_configuration(&mut cfg, &sess, &*trans);
286 sess.parse_sess.config = cfg;
288 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
290 let cstore = CStore::new(trans.metadata_loader());
292 do_or_return!(callbacks.late_callback(&*trans,
298 &ofile), Some(sess));
300 let control = callbacks.build_controller(&sess, &matches);
302 (driver::compile_input(trans,
314 // Extract output directory and file from matches.
315 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
316 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
317 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
321 // Extract input (string or file and optional path) from matches.
322 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
323 if free_matches.len() == 1 {
324 let ifile = &free_matches[0];
326 let mut src = String::new();
327 io::stdin().read_to_string(&mut src).unwrap();
328 Some((Input::Str { name: FileName::Anon, input: src },
331 Some((Input::File(PathBuf::from(ifile)),
332 Some(PathBuf::from(ifile))))
339 fn parse_pretty(sess: &Session,
340 matches: &getopts::Matches)
341 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
342 let pretty = if sess.opts.debugging_opts.unstable_options {
343 matches.opt_default("pretty", "normal").map(|a| {
344 // stable pretty-print variants only
345 pretty::parse_pretty(sess, &a, false)
351 if pretty.is_none() {
352 sess.opts.debugging_opts.unpretty.as_ref().map(|a| {
353 // extended with unstable pretty-print variants
354 pretty::parse_pretty(sess, &a, true)
361 // Whether to stop or continue compilation.
362 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
363 pub enum Compilation {
369 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
371 Compilation::Stop => Compilation::Stop,
372 Compilation::Continue => next(),
377 // A trait for customising the compilation process. Offers a number of hooks for
378 // executing custom code or customising input.
379 pub trait CompilerCalls<'a> {
380 // Hook for a callback early in the process of handling arguments. This will
381 // be called straight after options have been parsed but before anything
382 // else (e.g., selecting input and output).
383 fn early_callback(&mut self,
384 _: &getopts::Matches,
386 _: &ast::CrateConfig,
387 _: &errors::registry::Registry,
390 Compilation::Continue
393 // Hook for a callback late in the process of handling arguments. This will
394 // be called just before actual compilation starts (and before build_controller
395 // is called), after all arguments etc. have been completely handled.
396 fn late_callback(&mut self,
398 _: &getopts::Matches,
405 Compilation::Continue
408 // Called after we extract the input from the arguments. Gives the implementer
409 // an opportunity to change the inputs or to add some custom input handling.
410 // The default behaviour is to simply pass through the inputs.
411 fn some_input(&mut self,
413 input_path: Option<PathBuf>)
414 -> (Input, Option<PathBuf>) {
418 // Called after we extract the input from the arguments if there is no valid
419 // input. Gives the implementer an opportunity to supply alternate input (by
420 // returning a Some value) or to add custom behaviour for this error such as
421 // emitting error messages. Returning None will cause compilation to stop
423 fn no_input(&mut self,
424 _: &getopts::Matches,
426 _: &ast::CrateConfig,
429 _: &errors::registry::Registry)
430 -> Option<(Input, Option<PathBuf>)> {
434 // Create a CompilController struct for controlling the behaviour of
436 fn build_controller(&mut self, _: &Session, _: &getopts::Matches) -> CompileController<'a>;
439 // CompilerCalls instance for a regular rustc build.
440 #[derive(Copy, Clone)]
441 pub struct RustcDefaultCalls;
443 // FIXME remove these and use winapi 0.3 instead
444 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
446 fn stdout_isatty() -> bool {
447 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
451 fn stdout_isatty() -> bool {
454 type HANDLE = *mut u8;
455 type LPDWORD = *mut u32;
456 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
458 fn GetStdHandle(which: DWORD) -> HANDLE;
459 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
462 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
464 GetConsoleMode(handle, &mut out) != 0
468 fn handle_explain(code: &str,
469 descriptions: &errors::registry::Registry,
470 output: ErrorOutputType) {
471 let normalised = if code.starts_with("E") {
474 format!("E{0:0>4}", code)
476 match descriptions.find_description(&normalised) {
477 Some(ref description) => {
478 let mut is_in_code_block = false;
479 let mut text = String::new();
481 // Slice off the leading newline and print.
482 for line in description[1..].lines() {
483 let indent_level = line.find(|c: char| !c.is_whitespace())
484 .unwrap_or_else(|| line.len());
485 let dedented_line = &line[indent_level..];
486 if dedented_line.starts_with("```") {
487 is_in_code_block = !is_in_code_block;
488 text.push_str(&line[..(indent_level+3)]);
489 } else if is_in_code_block && dedented_line.starts_with("# ") {
498 show_content_with_pager(&text);
504 early_error(output, &format!("no extended information for {}", code));
509 fn show_content_with_pager(content: &String) {
510 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
511 OsString::from("more.com")
513 OsString::from("less")
516 let mut fallback_to_println = false;
518 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
520 if let Some(pipe) = pager.stdin.as_mut() {
521 if pipe.write_all(content.as_bytes()).is_err() {
522 fallback_to_println = true;
526 if pager.wait().is_err() {
527 fallback_to_println = true;
531 fallback_to_println = true;
535 // If pager fails for whatever reason, we should still print the content
536 // to standard output
537 if fallback_to_println {
538 print!("{}", content);
542 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
543 fn early_callback(&mut self,
544 matches: &getopts::Matches,
546 _: &ast::CrateConfig,
547 descriptions: &errors::registry::Registry,
548 output: ErrorOutputType)
550 if let Some(ref code) = matches.opt_str("explain") {
551 handle_explain(code, descriptions, output);
552 return Compilation::Stop;
555 Compilation::Continue
558 fn no_input(&mut self,
559 matches: &getopts::Matches,
560 sopts: &config::Options,
561 cfg: &ast::CrateConfig,
562 odir: &Option<PathBuf>,
563 ofile: &Option<PathBuf>,
564 descriptions: &errors::registry::Registry)
565 -> Option<(Input, Option<PathBuf>)> {
566 match matches.free.len() {
568 if sopts.describe_lints {
569 let mut ls = lint::LintStore::new();
570 rustc_lint::register_builtins(&mut ls, None);
571 describe_lints(&ls, false);
574 let mut sess = build_session(sopts.clone(),
576 descriptions.clone());
577 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
578 let mut cfg = config::build_configuration(&sess, cfg.clone());
579 let trans = get_trans(&sess);
580 target_features::add_configuration(&mut cfg, &sess, &*trans);
581 sess.parse_sess.config = cfg;
582 let should_stop = RustcDefaultCalls::print_crate_info(
590 if should_stop == Compilation::Stop {
593 early_error(sopts.error_format, "no input filename given");
595 1 => panic!("make_input should have provided valid inputs"),
596 _ => early_error(sopts.error_format, "multiple input filenames provided"),
600 fn late_callback(&mut self,
602 matches: &getopts::Matches,
606 odir: &Option<PathBuf>,
607 ofile: &Option<PathBuf>)
609 RustcDefaultCalls::print_crate_info(trans, sess, Some(input), odir, ofile)
610 .and_then(|| RustcDefaultCalls::list_metadata(sess, cstore, matches, input))
613 fn build_controller(&mut self,
615 matches: &getopts::Matches)
616 -> CompileController<'a> {
617 let mut control = CompileController::basic();
619 control.keep_ast = sess.opts.debugging_opts.keep_ast;
620 control.continue_parse_after_error = sess.opts.debugging_opts.continue_parse_after_error;
622 if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
623 if ppm.needs_ast_map(&opt_uii) {
624 control.after_hir_lowering.stop = Compilation::Stop;
626 control.after_parse.callback = box move |state| {
627 state.krate = Some(pretty::fold_crate(state.session,
628 state.krate.take().unwrap(),
631 control.after_hir_lowering.callback = box move |state| {
632 pretty::print_after_hir_lowering(state.session,
633 state.cstore.unwrap(),
634 state.hir_map.unwrap(),
635 state.analysis.unwrap(),
636 state.resolutions.unwrap(),
638 &state.expanded_crate.take().unwrap(),
639 state.crate_name.unwrap(),
641 state.arenas.unwrap(),
642 state.output_filenames.unwrap(),
647 control.after_parse.stop = Compilation::Stop;
649 control.after_parse.callback = box move |state| {
650 let krate = pretty::fold_crate(state.session, state.krate.take().unwrap(), ppm);
651 pretty::print_after_parsing(state.session,
662 if sess.opts.debugging_opts.parse_only ||
663 sess.opts.debugging_opts.show_span.is_some() ||
664 sess.opts.debugging_opts.ast_json_noexpand {
665 control.after_parse.stop = Compilation::Stop;
668 if sess.opts.debugging_opts.no_analysis ||
669 sess.opts.debugging_opts.ast_json {
670 control.after_hir_lowering.stop = Compilation::Stop;
673 if save_analysis(sess) {
674 enable_save_analysis(&mut control);
677 if sess.print_fuel_crate.is_some() {
678 let old_callback = control.compilation_done.callback;
679 control.compilation_done.callback = box move |state| {
681 let sess = state.session;
682 println!("Fuel used by {}: {}",
683 sess.print_fuel_crate.as_ref().unwrap(),
684 sess.print_fuel.get());
691 pub fn enable_save_analysis(control: &mut CompileController) {
692 control.keep_ast = true;
693 control.after_analysis.callback = box |state| {
694 time(state.session.time_passes(), "save analysis", || {
695 save::process_crate(state.tcx.unwrap(),
696 state.expanded_crate.unwrap(),
697 state.analysis.unwrap(),
698 state.crate_name.unwrap(),
700 DumpHandler::new(state.out_dir,
701 state.crate_name.unwrap()))
704 control.after_analysis.run_callback_on_error = true;
705 control.make_glob_map = resolve::MakeGlobMap::Yes;
708 fn save_analysis(sess: &Session) -> bool {
709 sess.opts.debugging_opts.save_analysis
712 impl RustcDefaultCalls {
713 pub fn list_metadata(sess: &Session,
715 matches: &getopts::Matches,
718 let r = matches.opt_strs("Z");
719 if r.contains(&("ls".to_string())) {
721 &Input::File(ref ifile) => {
722 let path = &(*ifile);
723 let mut v = Vec::new();
724 locator::list_file_metadata(&sess.target.target,
726 cstore.metadata_loader(),
729 println!("{}", String::from_utf8(v).unwrap());
731 &Input::Str { .. } => {
732 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
735 return Compilation::Stop;
738 return Compilation::Continue;
742 fn print_crate_info(trans: &TransCrate,
744 input: Option<&Input>,
745 odir: &Option<PathBuf>,
746 ofile: &Option<PathBuf>)
748 use rustc::session::config::PrintRequest::*;
749 // PrintRequest::NativeStaticLibs is special - printed during linking
750 // (empty iterator returns true)
751 if sess.opts.prints.iter().all(|&p| p==PrintRequest::NativeStaticLibs) {
752 return Compilation::Continue;
755 let attrs = match input {
758 let result = parse_crate_attrs(sess, input);
760 Ok(attrs) => Some(attrs),
761 Err(mut parse_error) => {
763 return Compilation::Stop;
768 for req in &sess.opts.prints {
771 let mut targets = rustc_back::target::get_targets().collect::<Vec<String>>();
773 println!("{}", targets.join("\n"));
775 Sysroot => println!("{}", sess.sysroot().display()),
776 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
777 FileNames | CrateName => {
778 let input = match input {
779 Some(input) => input,
780 None => early_error(ErrorOutputType::default(), "no input file provided"),
782 let attrs = attrs.as_ref().unwrap();
783 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
784 let id = rustc_trans_utils::link::find_crate_name(Some(sess), attrs, input);
785 if *req == PrintRequest::CrateName {
789 let crate_types = driver::collect_crate_types(sess, attrs);
790 for &style in &crate_types {
791 let fname = rustc_trans_utils::link::filename_for_input(
804 let allow_unstable_cfg = UnstableFeatures::from_environment()
807 let mut cfgs = Vec::new();
808 for &(name, ref value) in sess.parse_sess.config.iter() {
809 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
811 node: ast::MetaItemKind::Word,
815 // Note that crt-static is a specially recognized cfg
816 // directive that's printed out here as part of
817 // rust-lang/rust#37406, but in general the
818 // `target_feature` cfg is gated under
819 // rust-lang/rust#29717. For now this is just
820 // specifically allowing the crt-static cfg and that's
821 // it, this is intended to get into Cargo and then go
822 // through to build scripts.
823 let value = value.as_ref().map(|s| s.as_str());
824 let value = value.as_ref().map(|s| s.as_ref());
825 if name != "target_feature" || value != Some("crt-static") {
826 if !allow_unstable_cfg && gated_cfg.is_some() {
831 cfgs.push(if let Some(value) = value {
832 format!("{}=\"{}\"", name, value)
843 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
844 trans.print(*req, sess);
846 // Any output here interferes with Cargo's parsing of other printed output
847 PrintRequest::NativeStaticLibs => {}
850 return Compilation::Stop;
854 /// Returns a version string such as "0.12.0-dev".
855 fn release_str() -> Option<&'static str> {
856 option_env!("CFG_RELEASE")
859 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
860 fn commit_hash_str() -> Option<&'static str> {
861 option_env!("CFG_VER_HASH")
864 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
865 fn commit_date_str() -> Option<&'static str> {
866 option_env!("CFG_VER_DATE")
869 /// Prints version information
870 pub fn version(binary: &str, matches: &getopts::Matches) {
871 let verbose = matches.opt_present("verbose");
875 option_env!("CFG_VERSION").unwrap_or("unknown version"));
877 fn unw(x: Option<&str>) -> &str {
878 x.unwrap_or("unknown")
880 println!("binary: {}", binary);
881 println!("commit-hash: {}", unw(commit_hash_str()));
882 println!("commit-date: {}", unw(commit_date_str()));
883 println!("host: {}", config::host_triple());
884 println!("release: {}", unw(release_str()));
885 rustc_trans::print_version();
889 fn usage(verbose: bool, include_unstable_options: bool) {
890 let groups = if verbose {
891 config::rustc_optgroups()
893 config::rustc_short_optgroups()
895 let mut options = getopts::Options::new();
896 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
897 (option.apply)(&mut options);
899 let message = format!("Usage: rustc [OPTIONS] INPUT");
900 let nightly_help = if nightly_options::is_nightly_build() {
901 "\n -Z help Print internal options for debugging rustc"
905 let verbose_help = if verbose {
908 "\n --help -v Print the full set of options rustc accepts"
910 println!("{}\nAdditional help:
911 -C help Print codegen options
913 Print 'lint' options and default settings{}{}\n",
914 options.usage(&message),
919 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
921 Available lint options:
922 -W <foo> Warn about <foo>
926 -F <foo> Forbid <foo> \
927 (deny <foo> and all attempts to override)
931 fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
932 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
933 lints.sort_by(|x: &&Lint, y: &&Lint| {
934 match x.default_level.cmp(&y.default_level) {
935 // The sort doesn't case-fold but it's doubtful we care.
936 Equal => x.name.cmp(y.name),
943 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
944 -> Vec<(&'static str, Vec<lint::LintId>)> {
945 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
946 lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
947 &(y, _): &(&'static str, Vec<lint::LintId>)| {
953 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
956 .partition(|&(_, p)| p);
957 let plugin = sort_lints(plugin);
958 let builtin = sort_lints(builtin);
960 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
963 .partition(|&(.., p)| p);
964 let plugin_groups = sort_lint_groups(plugin_groups);
965 let builtin_groups = sort_lint_groups(builtin_groups);
967 let max_name_len = plugin.iter()
969 .map(|&s| s.name.chars().count())
972 let padded = |x: &str| {
973 let mut s = repeat(" ")
974 .take(max_name_len - x.chars().count())
975 .collect::<String>();
980 println!("Lint checks provided by rustc:\n");
981 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
982 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
984 let print_lints = |lints: Vec<&Lint>| {
986 let name = lint.name_lower().replace("_", "-");
987 println!(" {} {:7.7} {}",
989 lint.default_level.as_str(),
995 print_lints(builtin);
999 let max_name_len = max("warnings".len(),
1000 plugin_groups.iter()
1001 .chain(&builtin_groups)
1002 .map(|&(s, _)| s.chars().count())
1006 let padded = |x: &str| {
1007 let mut s = repeat(" ")
1008 .take(max_name_len - x.chars().count())
1009 .collect::<String>();
1014 println!("Lint groups provided by rustc:\n");
1015 println!(" {} {}", padded("name"), "sub-lints");
1016 println!(" {} {}", padded("----"), "---------");
1017 println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
1019 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
1020 for (name, to) in lints {
1021 let name = name.to_lowercase().replace("_", "-");
1022 let desc = to.into_iter()
1023 .map(|x| x.to_string().replace("_", "-"))
1024 .collect::<Vec<String>>()
1026 println!(" {} {}", padded(&name), desc);
1031 print_lint_groups(builtin_groups);
1033 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
1034 (false, 0, _) | (false, _, 0) => {
1035 println!("Compiler plugins can provide additional lints and lint groups. To see a \
1036 listing of these, re-run `rustc -W help` with a crate filename.");
1038 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
1039 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
1042 println!("Lint checks provided by plugins loaded by this crate:\n");
1043 print_lints(plugin);
1046 println!("Lint groups provided by plugins loaded by this crate:\n");
1047 print_lint_groups(plugin_groups);
1053 fn describe_debug_flags() {
1054 println!("\nAvailable debug options:\n");
1055 print_flag_list("-Z", config::DB_OPTIONS);
1058 fn describe_codegen_flags() {
1059 println!("\nAvailable codegen options:\n");
1060 print_flag_list("-C", config::CG_OPTIONS);
1063 fn print_flag_list<T>(cmdline_opt: &str,
1064 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
1065 let max_len = flag_list.iter()
1066 .map(|&(name, _, opt_type_desc, _)| {
1067 let extra_len = match opt_type_desc {
1071 name.chars().count() + extra_len
1076 for &(name, _, opt_type_desc, desc) in flag_list {
1077 let (width, extra) = match opt_type_desc {
1078 Some(..) => (max_len - 4, "=val"),
1079 None => (max_len, ""),
1081 println!(" {} {:>width$}{} -- {}",
1083 name.replace("_", "-"),
1090 /// Process command line options. Emits messages as appropriate. If compilation
1091 /// should continue, returns a getopts::Matches object parsed from args,
1092 /// otherwise returns None.
1094 /// The compiler's handling of options is a little complicated as it ties into
1095 /// our stability story, and it's even *more* complicated by historical
1096 /// accidents. The current intention of each compiler option is to have one of
1099 /// 1. An option is stable and can be used everywhere.
1100 /// 2. An option is unstable, but was historically allowed on the stable
1102 /// 3. An option is unstable, and can only be used on nightly.
1104 /// Like unstable library and language features, however, unstable options have
1105 /// always required a form of "opt in" to indicate that you're using them. This
1106 /// provides the easy ability to scan a code base to check to see if anything
1107 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1109 /// All options behind `-Z` are considered unstable by default. Other top-level
1110 /// options can also be considered unstable, and they were unlocked through the
1111 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1112 /// instability in both cases, though.
1114 /// So with all that in mind, the comments below have some more detail about the
1115 /// contortions done here to get things to work out correctly.
1116 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
1117 // Throw away the first argument, the name of the binary
1118 let args = &args[1..];
1120 if args.is_empty() {
1121 // user did not write `-v` nor `-Z unstable-options`, so do not
1122 // include that extra information.
1123 usage(false, false);
1127 // Parse with *all* options defined in the compiler, we don't worry about
1128 // option stability here we just want to parse as much as possible.
1129 let mut options = getopts::Options::new();
1130 for option in config::rustc_optgroups() {
1131 (option.apply)(&mut options);
1133 let matches = match options.parse(args) {
1135 Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
1138 // For all options we just parsed, we check a few aspects:
1140 // * If the option is stable, we're all good
1141 // * If the option wasn't passed, we're all good
1142 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1143 // ourselves), then we require the `-Z unstable-options` flag to unlock
1144 // this option that was passed.
1145 // * If we're a nightly compiler, then unstable options are now unlocked, so
1146 // we're good to go.
1147 // * Otherwise, if we're a truly unstable option then we generate an error
1148 // (unstable option being used on stable)
1149 // * If we're a historically stable-but-should-be-unstable option then we
1150 // emit a warning that we're going to turn this into an error soon.
1151 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1153 if matches.opt_present("h") || matches.opt_present("help") {
1154 // Only show unstable options in --help if we *really* accept unstable
1155 // options, which catches the case where we got `-Z unstable-options` on
1156 // the stable channel of Rust which was accidentally allowed
1158 usage(matches.opt_present("verbose"),
1159 nightly_options::is_unstable_enabled(&matches));
1163 // Don't handle -W help here, because we might first load plugins.
1164 let r = matches.opt_strs("Z");
1165 if r.iter().any(|x| *x == "help") {
1166 describe_debug_flags();
1170 let cg_flags = matches.opt_strs("C");
1171 if cg_flags.iter().any(|x| *x == "help") {
1172 describe_codegen_flags();
1176 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1177 early_warn(ErrorOutputType::default(),
1178 "the --no-stack-check flag is deprecated and does nothing");
1181 if cg_flags.contains(&"passes=list".to_string()) {
1182 rustc_trans::print_passes();
1186 if matches.opt_present("version") {
1187 version("rustc", &matches);
1194 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1196 Input::File(ref ifile) => {
1197 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1199 Input::Str { ref name, ref input } => {
1200 parse::parse_crate_attrs_from_source_str(name.clone(),
1207 /// Runs `f` in a suitable thread for running `rustc`; returns a
1208 /// `Result` with either the return value of `f` or -- if a panic
1209 /// occurs -- the panic value.
1210 pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<Any + Send>>
1211 where F: FnOnce() -> R + Send + 'static,
1214 // Temporarily have stack size set to 16MB to deal with nom-using crates failing
1215 const STACK_SIZE: usize = 16 * 1024 * 1024; // 16MB
1217 let mut cfg = thread::Builder::new().name("rustc".to_string());
1219 // FIXME: Hacks on hacks. If the env is trying to override the stack size
1220 // then *don't* set it explicitly.
1221 if env::var_os("RUST_MIN_STACK").is_none() {
1222 cfg = cfg.stack_size(STACK_SIZE);
1225 let thread = cfg.spawn(f);
1226 thread.unwrap().join()
1229 /// Run a procedure which will detect panics in the compiler and print nicer
1230 /// error messages rather than just failing the test.
1232 /// The diagnostic emitter yielded to the procedure should be used for reporting
1233 /// errors of the compiler.
1234 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
1235 struct Sink(Arc<Mutex<Vec<u8>>>);
1236 impl Write for Sink {
1237 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1238 Write::write(&mut *self.0.lock().unwrap(), data)
1240 fn flush(&mut self) -> io::Result<()> {
1245 let data = Arc::new(Mutex::new(Vec::new()));
1246 let err = Sink(data.clone());
1248 let result = in_rustc_thread(move || {
1249 io::set_panic(Some(box err));
1253 if let Err(value) = result {
1254 // Thread panicked without emitting a fatal diagnostic
1255 if !value.is::<errors::FatalError>() {
1257 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
1260 let handler = errors::Handler::with_emitter(true, false, emitter);
1262 // a .span_bug or .bug call has already printed what
1263 // it wants to print.
1264 if !value.is::<errors::ExplicitBug>() {
1265 handler.emit(&MultiSpan::new(),
1267 errors::Level::Bug);
1270 let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1271 format!("we would appreciate a bug report: {}", BUG_REPORT_URL),
1272 format!("rustc {} running on {}",
1273 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1274 config::host_triple())];
1276 handler.emit(&MultiSpan::new(),
1278 errors::Level::Note);
1280 if match env::var_os("RUST_BACKTRACE") {
1281 Some(val) => &val != "0",
1284 handler.emit(&MultiSpan::new(),
1285 "run with `RUST_BACKTRACE=1` for a backtrace",
1286 errors::Level::Note);
1289 eprintln!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
1296 fn exit_on_err() -> ! {
1297 // Panic so the process returns a failure code, but don't pollute the
1298 // output with some unnecessary panic messages, we've already
1299 // printed everything that we needed to.
1300 io::set_panic(Some(box io::sink()));
1305 pub fn diagnostics_registry() -> errors::registry::Registry {
1306 use errors::registry::Registry;
1312 pub fn diagnostics_registry() -> errors::registry::Registry {
1313 use errors::registry::Registry;
1315 let mut all_errors = Vec::new();
1316 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1317 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1318 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1319 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1320 #[cfg(feature="llvm")]
1321 all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
1322 all_errors.extend_from_slice(&rustc_trans_utils::DIAGNOSTICS);
1323 all_errors.extend_from_slice(&rustc_const_eval::DIAGNOSTICS);
1324 all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1325 all_errors.extend_from_slice(&rustc_passes::DIAGNOSTICS);
1326 all_errors.extend_from_slice(&rustc_plugin::DIAGNOSTICS);
1327 all_errors.extend_from_slice(&rustc_mir::DIAGNOSTICS);
1328 all_errors.extend_from_slice(&syntax::DIAGNOSTICS);
1330 Registry::new(&all_errors)
1333 pub fn get_args() -> Vec<String> {
1334 env::args_os().enumerate()
1335 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1336 early_error(ErrorOutputType::default(),
1337 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1343 env_logger::init().unwrap();
1344 let result = run(|| run_compiler(&get_args(),
1345 &mut RustcDefaultCalls,
1348 process::exit(result as i32);