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)]
26 #![feature(loop_break_value)]
29 #![feature(rustc_diagnostic_macros)]
30 #![feature(set_stdio)]
32 #![cfg_attr(stage0, unstable(feature = "rustc_private", issue = "27812"))]
33 #![cfg_attr(stage0, feature(rustc_private))]
34 #![cfg_attr(stage0, feature(staged_api))]
38 extern crate graphviz;
39 extern crate env_logger;
42 extern crate rustc_back;
43 extern crate rustc_borrowck;
44 extern crate rustc_const_eval;
45 extern crate rustc_data_structures;
46 extern crate rustc_errors as errors;
47 extern crate rustc_passes;
48 extern crate rustc_lint;
49 extern crate rustc_plugin;
50 extern crate rustc_privacy;
51 extern crate rustc_incremental;
52 extern crate rustc_metadata;
53 extern crate rustc_mir;
54 extern crate rustc_resolve;
55 extern crate rustc_save_analysis;
56 extern crate rustc_trans;
57 extern crate rustc_typeck;
58 extern crate serialize;
59 extern crate rustc_llvm as llvm;
63 extern crate syntax_ext;
64 extern crate syntax_pos;
66 use driver::CompileController;
67 use pretty::{PpMode, UserIdentifiedItem};
69 use rustc_resolve as resolve;
70 use rustc_save_analysis as save;
71 use rustc_save_analysis::DumpHandler;
72 use rustc_trans::back::link;
73 use rustc_trans::back::write::{create_target_machine, RELOC_MODEL_ARGS, CODE_GEN_MODEL_ARGS};
74 use rustc::dep_graph::DepGraph;
75 use rustc::session::{self, config, Session, build_session, CompileResult};
76 use rustc::session::config::{Input, PrintRequest, OutputType, ErrorOutputType};
77 use rustc::session::config::nightly_options;
78 use rustc::session::{early_error, early_warn};
79 use rustc::lint::Lint;
81 use rustc_metadata::locator;
82 use rustc_metadata::cstore::CStore;
83 use rustc::util::common::time;
85 use serialize::json::ToJson;
89 use std::cmp::Ordering::Equal;
90 use std::default::Default;
92 use std::io::{self, Read, Write};
93 use std::iter::repeat;
94 use std::path::PathBuf;
98 use std::sync::{Arc, Mutex};
102 use syntax::codemap::{CodeMap, FileLoader, RealFileLoader};
103 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
104 use syntax::parse::{self, PResult};
105 use syntax_pos::{DUMMY_SP, MultiSpan};
112 pub mod target_features;
113 mod derive_registrar;
115 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
119 fn abort_msg(err_count: usize) -> String {
121 0 => "aborting with no errors (maybe a bug?)".to_owned(),
122 1 => "aborting due to previous error".to_owned(),
123 e => format!("aborting due to {} previous errors", e),
127 pub fn abort_on_err<T>(result: Result<T, usize>, sess: &Session) -> T {
130 sess.fatal(&abort_msg(err_count));
136 pub fn run<F>(run_compiler: F) -> isize
137 where F: FnOnce() -> (CompileResult, Option<Session>) + Send + 'static
140 let (result, session) = run_compiler();
141 if let Err(err_count) = result {
144 Some(sess) => sess.fatal(&abort_msg(err_count)),
147 errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None);
148 let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
149 handler.emit(&MultiSpan::new(),
150 &abort_msg(err_count),
151 errors::Level::Fatal);
161 // Parse args and run the compiler. This is the primary entry point for rustc.
162 // See comments on CompilerCalls below for details about the callbacks argument.
163 // The FileLoader provides a way to load files from sources other than the file system.
164 pub fn run_compiler<'a>(args: &[String],
165 callbacks: &mut CompilerCalls<'a>,
166 file_loader: Option<Box<FileLoader + 'static>>,
167 emitter_dest: Option<Box<Write + Send>>)
168 -> (CompileResult, Option<Session>)
170 macro_rules! do_or_return {($expr: expr, $sess: expr) => {
172 Compilation::Stop => return (Ok(()), $sess),
173 Compilation::Continue => {}
177 let matches = match handle_options(args) {
178 Some(matches) => matches,
179 None => return (Ok(()), None),
182 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
184 if sopts.debugging_opts.debug_llvm {
185 unsafe { llvm::LLVMRustSetDebug(1); }
188 let descriptions = diagnostics_registry();
190 do_or_return!(callbacks.early_callback(&matches,
197 let (odir, ofile) = make_output(&matches);
198 let (input, input_file_path) = match make_input(&matches.free) {
199 Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
200 None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) {
201 Some((input, input_file_path)) => (input, input_file_path),
202 None => return (Ok(()), None),
206 let dep_graph = DepGraph::new(sopts.build_dep_graph());
207 let cstore = Rc::new(CStore::new(&dep_graph));
209 let loader = file_loader.unwrap_or(box RealFileLoader);
210 let codemap = Rc::new(CodeMap::with_file_loader(loader, sopts.file_path_mapping()));
211 let mut sess = session::build_session_with_codemap(
212 sopts, &dep_graph, input_file_path, descriptions, cstore.clone(), codemap, emitter_dest,
214 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
216 let mut cfg = config::build_configuration(&sess, cfg);
217 target_features::add_configuration(&mut cfg, &sess);
218 sess.parse_sess.config = cfg;
220 do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile), Some(sess));
222 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
223 let control = callbacks.build_controller(&sess, &matches);
224 (driver::compile_input(&sess, &cstore, &input, &odir, &ofile, Some(plugins), &control),
228 // Extract output directory and file from matches.
229 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
230 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
231 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
235 // Extract input (string or file and optional path) from matches.
236 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
237 if free_matches.len() == 1 {
238 let ifile = &free_matches[0];
240 let mut src = String::new();
241 io::stdin().read_to_string(&mut src).unwrap();
242 Some((Input::Str { name: driver::anon_src(), input: src },
245 Some((Input::File(PathBuf::from(ifile)),
246 Some(PathBuf::from(ifile))))
253 fn parse_pretty(sess: &Session,
254 matches: &getopts::Matches)
255 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
256 let pretty = if sess.opts.debugging_opts.unstable_options {
257 matches.opt_default("pretty", "normal").map(|a| {
258 // stable pretty-print variants only
259 pretty::parse_pretty(sess, &a, false)
264 if pretty.is_none() && sess.unstable_options() {
265 matches.opt_str("unpretty").map(|a| {
266 // extended with unstable pretty-print variants
267 pretty::parse_pretty(sess, &a, true)
274 // Whether to stop or continue compilation.
275 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
276 pub enum Compilation {
282 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
284 Compilation::Stop => Compilation::Stop,
285 Compilation::Continue => next(),
290 // A trait for customising the compilation process. Offers a number of hooks for
291 // executing custom code or customising input.
292 pub trait CompilerCalls<'a> {
293 // Hook for a callback early in the process of handling arguments. This will
294 // be called straight after options have been parsed but before anything
295 // else (e.g., selecting input and output).
296 fn early_callback(&mut self,
297 _: &getopts::Matches,
299 _: &ast::CrateConfig,
300 _: &errors::registry::Registry,
303 Compilation::Continue
306 // Hook for a callback late in the process of handling arguments. This will
307 // be called just before actual compilation starts (and before build_controller
308 // is called), after all arguments etc. have been completely handled.
309 fn late_callback(&mut self,
310 _: &getopts::Matches,
316 Compilation::Continue
319 // Called after we extract the input from the arguments. Gives the implementer
320 // an opportunity to change the inputs or to add some custom input handling.
321 // The default behaviour is to simply pass through the inputs.
322 fn some_input(&mut self,
324 input_path: Option<PathBuf>)
325 -> (Input, Option<PathBuf>) {
329 // Called after we extract the input from the arguments if there is no valid
330 // input. Gives the implementer an opportunity to supply alternate input (by
331 // returning a Some value) or to add custom behaviour for this error such as
332 // emitting error messages. Returning None will cause compilation to stop
334 fn no_input(&mut self,
335 _: &getopts::Matches,
337 _: &ast::CrateConfig,
340 _: &errors::registry::Registry)
341 -> Option<(Input, Option<PathBuf>)> {
345 // Create a CompilController struct for controlling the behaviour of
347 fn build_controller(&mut self, _: &Session, _: &getopts::Matches) -> CompileController<'a>;
350 // CompilerCalls instance for a regular rustc build.
351 #[derive(Copy, Clone)]
352 pub struct RustcDefaultCalls;
354 fn handle_explain(code: &str,
355 descriptions: &errors::registry::Registry,
356 output: ErrorOutputType) {
357 let normalised = if code.starts_with("E") {
360 format!("E{0:0>4}", code)
362 match descriptions.find_description(&normalised) {
363 Some(ref description) => {
364 // Slice off the leading newline and print.
365 print!("{}", &(&description[1..]).split("\n").map(|x| {
366 format!("{}\n", if x.starts_with("```") {
371 }).collect::<String>());
374 early_error(output, &format!("no extended information for {}", code));
379 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
380 fn early_callback(&mut self,
381 matches: &getopts::Matches,
383 _: &ast::CrateConfig,
384 descriptions: &errors::registry::Registry,
385 output: ErrorOutputType)
387 if let Some(ref code) = matches.opt_str("explain") {
388 handle_explain(code, descriptions, output);
389 return Compilation::Stop;
392 Compilation::Continue
395 fn no_input(&mut self,
396 matches: &getopts::Matches,
397 sopts: &config::Options,
398 cfg: &ast::CrateConfig,
399 odir: &Option<PathBuf>,
400 ofile: &Option<PathBuf>,
401 descriptions: &errors::registry::Registry)
402 -> Option<(Input, Option<PathBuf>)> {
403 match matches.free.len() {
405 if sopts.describe_lints {
406 let mut ls = lint::LintStore::new();
407 rustc_lint::register_builtins(&mut ls, None);
408 describe_lints(&ls, false);
411 let dep_graph = DepGraph::new(sopts.build_dep_graph());
412 let cstore = Rc::new(CStore::new(&dep_graph));
413 let mut sess = build_session(sopts.clone(),
416 descriptions.clone(),
418 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
419 let mut cfg = config::build_configuration(&sess, cfg.clone());
420 target_features::add_configuration(&mut cfg, &sess);
421 sess.parse_sess.config = cfg;
423 RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
425 if should_stop == Compilation::Stop {
428 early_error(sopts.error_format, "no input filename given");
430 1 => panic!("make_input should have provided valid inputs"),
431 _ => early_error(sopts.error_format, "multiple input filenames provided"),
435 fn late_callback(&mut self,
436 matches: &getopts::Matches,
439 odir: &Option<PathBuf>,
440 ofile: &Option<PathBuf>)
442 RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
443 .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input))
446 fn build_controller(&mut self,
448 matches: &getopts::Matches)
449 -> CompileController<'a> {
450 let mut control = CompileController::basic();
452 if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
453 if ppm.needs_ast_map(&opt_uii) {
454 control.after_hir_lowering.stop = Compilation::Stop;
456 control.after_parse.callback = box move |state| {
457 state.krate = Some(pretty::fold_crate(state.krate.take().unwrap(), ppm));
459 control.after_hir_lowering.callback = box move |state| {
460 pretty::print_after_hir_lowering(state.session,
461 state.hir_map.unwrap(),
462 state.analysis.unwrap(),
463 state.resolutions.unwrap(),
465 &state.expanded_crate.take().unwrap(),
466 state.crate_name.unwrap(),
468 state.arena.unwrap(),
469 state.arenas.unwrap(),
474 control.after_parse.stop = Compilation::Stop;
476 control.after_parse.callback = box move |state| {
477 let krate = pretty::fold_crate(state.krate.take().unwrap(), ppm);
478 pretty::print_after_parsing(state.session,
489 if sess.opts.debugging_opts.parse_only ||
490 sess.opts.debugging_opts.show_span.is_some() ||
491 sess.opts.debugging_opts.ast_json_noexpand {
492 control.after_parse.stop = Compilation::Stop;
495 if sess.opts.debugging_opts.no_analysis ||
496 sess.opts.debugging_opts.ast_json {
497 control.after_hir_lowering.stop = Compilation::Stop;
500 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
501 i == OutputType::Metadata) {
502 control.after_llvm.stop = Compilation::Stop;
505 if save_analysis(sess) {
506 control.after_analysis.callback = box |state| {
507 time(state.session.time_passes(), "save analysis", || {
508 save::process_crate(state.tcx.unwrap(),
509 state.expanded_crate.unwrap(),
510 state.analysis.unwrap(),
511 state.crate_name.unwrap(),
512 DumpHandler::new(save_analysis_format(state.session),
514 state.crate_name.unwrap()))
517 control.after_analysis.run_callback_on_error = true;
518 control.make_glob_map = resolve::MakeGlobMap::Yes;
521 if sess.print_fuel_crate.is_some() {
522 let old_callback = control.compilation_done.callback;
523 control.compilation_done.callback = box move |state| {
525 let sess = state.session;
526 println!("Fuel used by {}: {}",
527 sess.print_fuel_crate.as_ref().unwrap(),
528 sess.print_fuel.get());
535 fn save_analysis(sess: &Session) -> bool {
536 sess.opts.debugging_opts.save_analysis ||
537 sess.opts.debugging_opts.save_analysis_csv ||
538 sess.opts.debugging_opts.save_analysis_api
541 fn save_analysis_format(sess: &Session) -> save::Format {
542 if sess.opts.debugging_opts.save_analysis {
544 } else if sess.opts.debugging_opts.save_analysis_csv {
546 } else if sess.opts.debugging_opts.save_analysis_api {
547 save::Format::JsonApi
553 impl RustcDefaultCalls {
554 pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation {
555 let r = matches.opt_strs("Z");
556 if r.contains(&("ls".to_string())) {
558 &Input::File(ref ifile) => {
559 let path = &(*ifile);
560 let mut v = Vec::new();
561 locator::list_file_metadata(&sess.target.target, path, &mut v).unwrap();
562 println!("{}", String::from_utf8(v).unwrap());
564 &Input::Str { .. } => {
565 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
568 return Compilation::Stop;
571 return Compilation::Continue;
575 fn print_crate_info(sess: &Session,
576 input: Option<&Input>,
577 odir: &Option<PathBuf>,
578 ofile: &Option<PathBuf>)
580 if sess.opts.prints.is_empty() {
581 return Compilation::Continue;
584 let attrs = match input {
587 let result = parse_crate_attrs(sess, input);
589 Ok(attrs) => Some(attrs),
590 Err(mut parse_error) => {
592 return Compilation::Stop;
597 for req in &sess.opts.prints {
599 PrintRequest::TargetList => {
600 let mut targets = rustc_back::target::get_targets().collect::<Vec<String>>();
602 println!("{}", targets.join("\n"));
604 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
605 PrintRequest::TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
606 PrintRequest::FileNames |
607 PrintRequest::CrateName => {
608 let input = match input {
609 Some(input) => input,
610 None => early_error(ErrorOutputType::default(), "no input file provided"),
612 let attrs = attrs.as_ref().unwrap();
613 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
614 let id = link::find_crate_name(Some(sess), attrs, input);
615 if *req == PrintRequest::CrateName {
619 let crate_types = driver::collect_crate_types(sess, attrs);
620 for &style in &crate_types {
621 let fname = link::filename_for_input(sess, style, &id, &t_outputs);
628 PrintRequest::Cfg => {
629 let allow_unstable_cfg = UnstableFeatures::from_environment()
632 let mut cfgs = Vec::new();
633 for &(name, ref value) in sess.parse_sess.config.iter() {
634 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
636 node: ast::MetaItemKind::Word,
640 // Note that crt-static is a specially recognized cfg
641 // directive that's printed out here as part of
642 // rust-lang/rust#37406, but in general the
643 // `target_feature` cfg is gated under
644 // rust-lang/rust#29717. For now this is just
645 // specifically allowing the crt-static cfg and that's
646 // it, this is intended to get into Cargo and then go
647 // through to build scripts.
648 let value = value.as_ref().map(|s| s.as_str());
649 let value = value.as_ref().map(|s| s.as_ref());
650 if name != "target_feature" || value != Some("crt-static") {
651 if !allow_unstable_cfg && gated_cfg.is_some() {
656 cfgs.push(if let Some(value) = value {
657 format!("{}=\"{}\"", name, value)
668 PrintRequest::TargetCPUs => {
669 let tm = create_target_machine(sess);
670 unsafe { llvm::LLVMRustPrintTargetCPUs(tm); }
672 PrintRequest::TargetFeatures => {
673 let tm = create_target_machine(sess);
674 unsafe { llvm::LLVMRustPrintTargetFeatures(tm); }
676 PrintRequest::RelocationModels => {
677 println!("Available relocation models:");
678 for &(name, _) in RELOC_MODEL_ARGS.iter() {
679 println!(" {}", name);
683 PrintRequest::CodeModels => {
684 println!("Available code models:");
685 for &(name, _) in CODE_GEN_MODEL_ARGS.iter(){
686 println!(" {}", name);
692 return Compilation::Stop;
696 /// Returns a version string such as "0.12.0-dev".
697 pub fn release_str() -> Option<&'static str> {
698 option_env!("CFG_RELEASE")
701 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
702 pub fn commit_hash_str() -> Option<&'static str> {
703 option_env!("CFG_VER_HASH")
706 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
707 pub fn commit_date_str() -> Option<&'static str> {
708 option_env!("CFG_VER_DATE")
711 /// Prints version information
712 pub fn version(binary: &str, matches: &getopts::Matches) {
713 let verbose = matches.opt_present("verbose");
717 option_env!("CFG_VERSION").unwrap_or("unknown version"));
719 fn unw(x: Option<&str>) -> &str {
720 x.unwrap_or("unknown")
722 println!("binary: {}", binary);
723 println!("commit-hash: {}", unw(commit_hash_str()));
724 println!("commit-date: {}", unw(commit_date_str()));
725 println!("host: {}", config::host_triple());
726 println!("release: {}", unw(release_str()));
728 println!("LLVM version: {}.{}",
729 llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor());
734 fn usage(verbose: bool, include_unstable_options: bool) {
735 let groups = if verbose {
736 config::rustc_optgroups()
738 config::rustc_short_optgroups()
740 let groups: Vec<_> = groups.into_iter()
741 .filter(|x| include_unstable_options || x.is_stable())
742 .map(|x| x.opt_group)
744 let message = format!("Usage: rustc [OPTIONS] INPUT");
745 let extra_help = if verbose {
748 "\n --help -v Print the full set of options rustc accepts"
750 println!("{}\nAdditional help:
751 -C help Print codegen options
753 Print 'lint' options and default settings
754 -Z help Print internal \
755 options for debugging rustc{}\n",
756 getopts::usage(&message, &groups),
760 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
762 Available lint options:
763 -W <foo> Warn about <foo>
767 -F <foo> Forbid <foo> \
768 (deny <foo> and all attempts to override)
772 fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
773 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
774 lints.sort_by(|x: &&Lint, y: &&Lint| {
775 match x.default_level.cmp(&y.default_level) {
776 // The sort doesn't case-fold but it's doubtful we care.
777 Equal => x.name.cmp(y.name),
784 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
785 -> Vec<(&'static str, Vec<lint::LintId>)> {
786 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
787 lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
788 &(y, _): &(&'static str, Vec<lint::LintId>)| {
794 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
797 .partition(|&(_, p)| p);
798 let plugin = sort_lints(plugin);
799 let builtin = sort_lints(builtin);
801 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
804 .partition(|&(.., p)| p);
805 let plugin_groups = sort_lint_groups(plugin_groups);
806 let builtin_groups = sort_lint_groups(builtin_groups);
808 let max_name_len = plugin.iter()
810 .map(|&s| s.name.chars().count())
813 let padded = |x: &str| {
814 let mut s = repeat(" ")
815 .take(max_name_len - x.chars().count())
816 .collect::<String>();
821 println!("Lint checks provided by rustc:\n");
822 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
823 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
825 let print_lints = |lints: Vec<&Lint>| {
827 let name = lint.name_lower().replace("_", "-");
828 println!(" {} {:7.7} {}",
830 lint.default_level.as_str(),
836 print_lints(builtin);
840 let max_name_len = max("warnings".len(),
842 .chain(&builtin_groups)
843 .map(|&(s, _)| s.chars().count())
847 let padded = |x: &str| {
848 let mut s = repeat(" ")
849 .take(max_name_len - x.chars().count())
850 .collect::<String>();
855 println!("Lint groups provided by rustc:\n");
856 println!(" {} {}", padded("name"), "sub-lints");
857 println!(" {} {}", padded("----"), "---------");
858 println!(" {} {}", padded("warnings"), "all built-in lints");
860 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
861 for (name, to) in lints {
862 let name = name.to_lowercase().replace("_", "-");
863 let desc = to.into_iter()
864 .map(|x| x.to_string().replace("_", "-"))
865 .collect::<Vec<String>>()
867 println!(" {} {}", padded(&name), desc);
872 print_lint_groups(builtin_groups);
874 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
875 (false, 0, _) | (false, _, 0) => {
876 println!("Compiler plugins can provide additional lints and lint groups. To see a \
877 listing of these, re-run `rustc -W help` with a crate filename.");
879 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
880 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
883 println!("Lint checks provided by plugins loaded by this crate:\n");
887 println!("Lint groups provided by plugins loaded by this crate:\n");
888 print_lint_groups(plugin_groups);
894 fn describe_debug_flags() {
895 println!("\nAvailable debug options:\n");
896 print_flag_list("-Z", config::DB_OPTIONS);
899 fn describe_codegen_flags() {
900 println!("\nAvailable codegen options:\n");
901 print_flag_list("-C", config::CG_OPTIONS);
904 fn print_flag_list<T>(cmdline_opt: &str,
905 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
906 let max_len = flag_list.iter()
907 .map(|&(name, _, opt_type_desc, _)| {
908 let extra_len = match opt_type_desc {
912 name.chars().count() + extra_len
917 for &(name, _, opt_type_desc, desc) in flag_list {
918 let (width, extra) = match opt_type_desc {
919 Some(..) => (max_len - 4, "=val"),
920 None => (max_len, ""),
922 println!(" {} {:>width$}{} -- {}",
924 name.replace("_", "-"),
931 /// Process command line options. Emits messages as appropriate. If compilation
932 /// should continue, returns a getopts::Matches object parsed from args,
933 /// otherwise returns None.
935 /// The compiler's handling of options is a little complicated as it ties into
936 /// our stability story, and it's even *more* complicated by historical
937 /// accidents. The current intention of each compiler option is to have one of
940 /// 1. An option is stable and can be used everywhere.
941 /// 2. An option is unstable, but was historically allowed on the stable
943 /// 3. An option is unstable, and can only be used on nightly.
945 /// Like unstable library and language features, however, unstable options have
946 /// always required a form of "opt in" to indicate that you're using them. This
947 /// provides the easy ability to scan a code base to check to see if anything
948 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
950 /// All options behind `-Z` are considered unstable by default. Other top-level
951 /// options can also be considered unstable, and they were unlocked through the
952 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
953 /// instability in both cases, though.
955 /// So with all that in mind, the comments below have some more detail about the
956 /// contortions done here to get things to work out correctly.
957 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
958 // Throw away the first argument, the name of the binary
959 let args = &args[1..];
962 // user did not write `-v` nor `-Z unstable-options`, so do not
963 // include that extra information.
968 // Parse with *all* options defined in the compiler, we don't worry about
969 // option stability here we just want to parse as much as possible.
970 let all_groups: Vec<getopts::OptGroup> = config::rustc_optgroups()
972 .map(|x| x.opt_group)
974 let matches = match getopts::getopts(&args, &all_groups) {
976 Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
979 // For all options we just parsed, we check a few aspects:
981 // * If the option is stable, we're all good
982 // * If the option wasn't passed, we're all good
983 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
984 // ourselves), then we require the `-Z unstable-options` flag to unlock
985 // this option that was passed.
986 // * If we're a nightly compiler, then unstable options are now unlocked, so
988 // * Otherwise, if we're a truly unstable option then we generate an error
989 // (unstable option being used on stable)
990 // * If we're a historically stable-but-should-be-unstable option then we
991 // emit a warning that we're going to turn this into an error soon.
992 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
994 if matches.opt_present("h") || matches.opt_present("help") {
995 // Only show unstable options in --help if we *really* accept unstable
996 // options, which catches the case where we got `-Z unstable-options` on
997 // the stable channel of Rust which was accidentally allowed
999 usage(matches.opt_present("verbose"),
1000 nightly_options::is_unstable_enabled(&matches));
1004 // Don't handle -W help here, because we might first load plugins.
1005 let r = matches.opt_strs("Z");
1006 if r.iter().any(|x| *x == "help") {
1007 describe_debug_flags();
1011 let cg_flags = matches.opt_strs("C");
1012 if cg_flags.iter().any(|x| *x == "help") {
1013 describe_codegen_flags();
1017 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1018 early_warn(ErrorOutputType::default(),
1019 "the --no-stack-check flag is deprecated and does nothing");
1022 if cg_flags.contains(&"passes=list".to_string()) {
1024 ::llvm::LLVMRustPrintPasses();
1029 if matches.opt_present("version") {
1030 version("rustc", &matches);
1037 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1039 Input::File(ref ifile) => {
1040 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1042 Input::Str { ref name, ref input } => {
1043 parse::parse_crate_attrs_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
1048 /// Runs `f` in a suitable thread for running `rustc`; returns a
1049 /// `Result` with either the return value of `f` or -- if a panic
1050 /// occurs -- the panic value.
1051 pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<Any + Send>>
1052 where F: FnOnce() -> R + Send + 'static,
1055 // Temporarily have stack size set to 16MB to deal with nom-using crates failing
1056 const STACK_SIZE: usize = 16 * 1024 * 1024; // 16MB
1058 let mut cfg = thread::Builder::new().name("rustc".to_string());
1060 // FIXME: Hacks on hacks. If the env is trying to override the stack size
1061 // then *don't* set it explicitly.
1062 if env::var_os("RUST_MIN_STACK").is_none() {
1063 cfg = cfg.stack_size(STACK_SIZE);
1066 let thread = cfg.spawn(f);
1067 thread.unwrap().join()
1070 /// Run a procedure which will detect panics in the compiler and print nicer
1071 /// error messages rather than just failing the test.
1073 /// The diagnostic emitter yielded to the procedure should be used for reporting
1074 /// errors of the compiler.
1075 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
1076 struct Sink(Arc<Mutex<Vec<u8>>>);
1077 impl Write for Sink {
1078 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1079 Write::write(&mut *self.0.lock().unwrap(), data)
1081 fn flush(&mut self) -> io::Result<()> {
1086 let data = Arc::new(Mutex::new(Vec::new()));
1087 let err = Sink(data.clone());
1089 let result = in_rustc_thread(move || {
1090 io::set_panic(Some(box err));
1094 if let Err(value) = result {
1095 // Thread panicked without emitting a fatal diagnostic
1096 if !value.is::<errors::FatalError>() {
1098 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None));
1099 let handler = errors::Handler::with_emitter(true, false, emitter);
1101 // a .span_bug or .bug call has already printed what
1102 // it wants to print.
1103 if !value.is::<errors::ExplicitBug>() {
1104 handler.emit(&MultiSpan::new(),
1106 errors::Level::Bug);
1109 let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1110 format!("we would appreciate a bug report: {}", BUG_REPORT_URL)];
1112 handler.emit(&MultiSpan::new(),
1114 errors::Level::Note);
1116 if match env::var_os("RUST_BACKTRACE") {
1117 Some(val) => &val != "0",
1120 handler.emit(&MultiSpan::new(),
1121 "run with `RUST_BACKTRACE=1` for a backtrace",
1122 errors::Level::Note);
1125 writeln!(io::stderr(), "{}", str::from_utf8(&data.lock().unwrap()).unwrap()).unwrap();
1132 fn exit_on_err() -> ! {
1133 // Panic so the process returns a failure code, but don't pollute the
1134 // output with some unnecessary panic messages, we've already
1135 // printed everything that we needed to.
1136 io::set_panic(Some(box io::sink()));
1140 pub fn diagnostics_registry() -> errors::registry::Registry {
1141 use errors::registry::Registry;
1143 let mut all_errors = Vec::new();
1144 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1145 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1146 all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
1147 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1148 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1149 all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
1150 all_errors.extend_from_slice(&rustc_const_eval::DIAGNOSTICS);
1151 all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1153 Registry::new(&all_errors)
1157 env_logger::init().unwrap();
1158 let result = run(|| run_compiler(&env::args().collect::<Vec<_>>(),
1159 &mut RustcDefaultCalls,
1162 process::exit(result as i32);