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 #![unstable(feature = "rustc_private", issue = "27812")]
19 #![crate_type = "dylib"]
20 #![crate_type = "rlib"]
21 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
22 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
23 html_root_url = "https://doc.rust-lang.org/nightly/")]
26 #![feature(box_syntax)]
27 #![feature(loop_break_value)]
30 #![feature(rustc_diagnostic_macros)]
31 #![feature(rustc_private)]
32 #![feature(set_stdio)]
33 #![feature(staged_api)]
37 extern crate graphviz;
38 extern crate env_logger;
41 extern crate rustc_back;
42 extern crate rustc_borrowck;
43 extern crate rustc_const_eval;
44 extern crate rustc_data_structures;
45 extern crate rustc_errors as errors;
46 extern crate rustc_passes;
47 extern crate rustc_lint;
48 extern crate rustc_plugin;
49 extern crate rustc_privacy;
50 extern crate rustc_incremental;
51 extern crate rustc_metadata;
52 extern crate rustc_mir;
53 extern crate rustc_resolve;
54 extern crate rustc_save_analysis;
55 extern crate rustc_trans;
56 extern crate rustc_typeck;
57 extern crate serialize;
58 extern crate rustc_llvm as llvm;
62 extern crate syntax_ext;
63 extern crate syntax_pos;
65 use driver::CompileController;
66 use pretty::{PpMode, UserIdentifiedItem};
68 use rustc_resolve as resolve;
69 use rustc_save_analysis as save;
70 use rustc_save_analysis::DumpHandler;
71 use rustc_trans::back::link;
72 use rustc_trans::back::write::{create_target_machine, RELOC_MODEL_ARGS, CODE_GEN_MODEL_ARGS};
73 use rustc::dep_graph::DepGraph;
74 use rustc::session::{self, config, Session, build_session, CompileResult};
75 use rustc::session::config::{Input, PrintRequest, OutputType, ErrorOutputType};
76 use rustc::session::config::nightly_options;
77 use rustc::session::{early_error, early_warn};
78 use rustc::lint::Lint;
80 use rustc_metadata::locator;
81 use rustc_metadata::cstore::CStore;
82 use rustc::util::common::time;
84 use serialize::json::ToJson;
88 use std::cmp::Ordering::Equal;
89 use std::default::Default;
91 use std::io::{self, Read, Write};
92 use std::iter::repeat;
93 use std::path::PathBuf;
97 use std::sync::{Arc, Mutex};
101 use syntax::codemap::{CodeMap, FileLoader, RealFileLoader};
102 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
103 use syntax::parse::{self, PResult};
104 use syntax_pos::{DUMMY_SP, MultiSpan};
111 pub mod target_features;
112 mod derive_registrar;
114 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
118 fn abort_msg(err_count: usize) -> String {
120 0 => "aborting with no errors (maybe a bug?)".to_owned(),
121 1 => "aborting due to previous error".to_owned(),
122 e => format!("aborting due to {} previous errors", e),
126 pub fn abort_on_err<T>(result: Result<T, usize>, sess: &Session) -> T {
129 sess.fatal(&abort_msg(err_count));
135 pub fn run<F>(run_compiler: F) -> isize
136 where F: FnOnce() -> (CompileResult, Option<Session>) + Send + 'static
139 let (result, session) = run_compiler();
140 if let Err(err_count) = result {
143 Some(sess) => sess.fatal(&abort_msg(err_count)),
146 errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None);
147 let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
148 handler.emit(&MultiSpan::new(),
149 &abort_msg(err_count),
150 errors::Level::Fatal);
160 // Parse args and run the compiler. This is the primary entry point for rustc.
161 // See comments on CompilerCalls below for details about the callbacks argument.
162 // The FileLoader provides a way to load files from sources other than the file system.
163 pub fn run_compiler<'a>(args: &[String],
164 callbacks: &mut CompilerCalls<'a>,
165 file_loader: Option<Box<FileLoader + 'static>>,
166 emitter_dest: Option<Box<Write + Send>>)
167 -> (CompileResult, Option<Session>)
169 macro_rules! do_or_return {($expr: expr, $sess: expr) => {
171 Compilation::Stop => return (Ok(()), $sess),
172 Compilation::Continue => {}
176 let matches = match handle_options(args) {
177 Some(matches) => matches,
178 None => return (Ok(()), None),
181 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
183 if sopts.debugging_opts.debug_llvm {
184 unsafe { llvm::LLVMRustSetDebug(1); }
187 let descriptions = diagnostics_registry();
189 do_or_return!(callbacks.early_callback(&matches,
196 let (odir, ofile) = make_output(&matches);
197 let (input, input_file_path) = match make_input(&matches.free) {
198 Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
199 None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) {
200 Some((input, input_file_path)) => (input, input_file_path),
201 None => return (Ok(()), None),
205 let dep_graph = DepGraph::new(sopts.build_dep_graph());
206 let cstore = Rc::new(CStore::new(&dep_graph));
208 let loader = file_loader.unwrap_or(box RealFileLoader);
209 let codemap = Rc::new(CodeMap::with_file_loader(loader, sopts.file_path_mapping()));
210 let mut sess = session::build_session_with_codemap(
211 sopts, &dep_graph, input_file_path, descriptions, cstore.clone(), codemap, emitter_dest,
213 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
215 let mut cfg = config::build_configuration(&sess, cfg);
216 target_features::add_configuration(&mut cfg, &sess);
217 sess.parse_sess.config = cfg;
219 do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile), Some(sess));
221 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
222 let control = callbacks.build_controller(&sess, &matches);
223 (driver::compile_input(&sess, &cstore, &input, &odir, &ofile, Some(plugins), &control),
227 // Extract output directory and file from matches.
228 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
229 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
230 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
234 // Extract input (string or file and optional path) from matches.
235 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
236 if free_matches.len() == 1 {
237 let ifile = &free_matches[0];
239 let mut src = String::new();
240 io::stdin().read_to_string(&mut src).unwrap();
241 Some((Input::Str { name: driver::anon_src(), input: src },
244 Some((Input::File(PathBuf::from(ifile)),
245 Some(PathBuf::from(ifile))))
252 fn parse_pretty(sess: &Session,
253 matches: &getopts::Matches)
254 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
255 let pretty = if sess.opts.debugging_opts.unstable_options {
256 matches.opt_default("pretty", "normal").map(|a| {
257 // stable pretty-print variants only
258 pretty::parse_pretty(sess, &a, false)
263 if pretty.is_none() && sess.unstable_options() {
264 matches.opt_str("unpretty").map(|a| {
265 // extended with unstable pretty-print variants
266 pretty::parse_pretty(sess, &a, true)
273 // Whether to stop or continue compilation.
274 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
275 pub enum Compilation {
281 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
283 Compilation::Stop => Compilation::Stop,
284 Compilation::Continue => next(),
289 // A trait for customising the compilation process. Offers a number of hooks for
290 // executing custom code or customising input.
291 pub trait CompilerCalls<'a> {
292 // Hook for a callback early in the process of handling arguments. This will
293 // be called straight after options have been parsed but before anything
294 // else (e.g., selecting input and output).
295 fn early_callback(&mut self,
296 _: &getopts::Matches,
298 _: &ast::CrateConfig,
299 _: &errors::registry::Registry,
302 Compilation::Continue
305 // Hook for a callback late in the process of handling arguments. This will
306 // be called just before actual compilation starts (and before build_controller
307 // is called), after all arguments etc. have been completely handled.
308 fn late_callback(&mut self,
309 _: &getopts::Matches,
315 Compilation::Continue
318 // Called after we extract the input from the arguments. Gives the implementer
319 // an opportunity to change the inputs or to add some custom input handling.
320 // The default behaviour is to simply pass through the inputs.
321 fn some_input(&mut self,
323 input_path: Option<PathBuf>)
324 -> (Input, Option<PathBuf>) {
328 // Called after we extract the input from the arguments if there is no valid
329 // input. Gives the implementer an opportunity to supply alternate input (by
330 // returning a Some value) or to add custom behaviour for this error such as
331 // emitting error messages. Returning None will cause compilation to stop
333 fn no_input(&mut self,
334 _: &getopts::Matches,
336 _: &ast::CrateConfig,
339 _: &errors::registry::Registry)
340 -> Option<(Input, Option<PathBuf>)> {
344 // Create a CompilController struct for controlling the behaviour of
346 fn build_controller(&mut self, _: &Session, _: &getopts::Matches) -> CompileController<'a>;
349 // CompilerCalls instance for a regular rustc build.
350 #[derive(Copy, Clone)]
351 pub struct RustcDefaultCalls;
353 fn handle_explain(code: &str,
354 descriptions: &errors::registry::Registry,
355 output: ErrorOutputType) {
356 let normalised = if code.starts_with("E") {
359 format!("E{0:0>4}", code)
361 match descriptions.find_description(&normalised) {
362 Some(ref description) => {
363 // Slice off the leading newline and print.
364 print!("{}", &(&description[1..]).split("\n").map(|x| {
365 format!("{}\n", if x.starts_with("```") {
370 }).collect::<String>());
373 early_error(output, &format!("no extended information for {}", code));
378 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
379 fn early_callback(&mut self,
380 matches: &getopts::Matches,
382 _: &ast::CrateConfig,
383 descriptions: &errors::registry::Registry,
384 output: ErrorOutputType)
386 if let Some(ref code) = matches.opt_str("explain") {
387 handle_explain(code, descriptions, output);
388 return Compilation::Stop;
391 Compilation::Continue
394 fn no_input(&mut self,
395 matches: &getopts::Matches,
396 sopts: &config::Options,
397 cfg: &ast::CrateConfig,
398 odir: &Option<PathBuf>,
399 ofile: &Option<PathBuf>,
400 descriptions: &errors::registry::Registry)
401 -> Option<(Input, Option<PathBuf>)> {
402 match matches.free.len() {
404 if sopts.describe_lints {
405 let mut ls = lint::LintStore::new();
406 rustc_lint::register_builtins(&mut ls, None);
407 describe_lints(&ls, false);
410 let dep_graph = DepGraph::new(sopts.build_dep_graph());
411 let cstore = Rc::new(CStore::new(&dep_graph));
412 let mut sess = build_session(sopts.clone(),
415 descriptions.clone(),
417 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
418 let mut cfg = config::build_configuration(&sess, cfg.clone());
419 target_features::add_configuration(&mut cfg, &sess);
420 sess.parse_sess.config = cfg;
422 RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
424 if should_stop == Compilation::Stop {
427 early_error(sopts.error_format, "no input filename given");
429 1 => panic!("make_input should have provided valid inputs"),
430 _ => early_error(sopts.error_format, "multiple input filenames provided"),
434 fn late_callback(&mut self,
435 matches: &getopts::Matches,
438 odir: &Option<PathBuf>,
439 ofile: &Option<PathBuf>)
441 RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
442 .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input))
445 fn build_controller(&mut self,
447 matches: &getopts::Matches)
448 -> CompileController<'a> {
449 let mut control = CompileController::basic();
451 if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
452 if ppm.needs_ast_map(&opt_uii) {
453 control.after_hir_lowering.stop = Compilation::Stop;
455 control.after_parse.callback = box move |state| {
456 state.krate = Some(pretty::fold_crate(state.krate.take().unwrap(), ppm));
458 control.after_hir_lowering.callback = box move |state| {
459 pretty::print_after_hir_lowering(state.session,
460 state.hir_map.unwrap(),
461 state.analysis.unwrap(),
462 state.resolutions.unwrap(),
464 &state.expanded_crate.take().unwrap(),
465 state.crate_name.unwrap(),
467 state.arena.unwrap(),
468 state.arenas.unwrap(),
473 control.after_parse.stop = Compilation::Stop;
475 control.after_parse.callback = box move |state| {
476 let krate = pretty::fold_crate(state.krate.take().unwrap(), ppm);
477 pretty::print_after_parsing(state.session,
488 if sess.opts.debugging_opts.parse_only ||
489 sess.opts.debugging_opts.show_span.is_some() ||
490 sess.opts.debugging_opts.ast_json_noexpand {
491 control.after_parse.stop = Compilation::Stop;
494 if sess.opts.debugging_opts.no_analysis ||
495 sess.opts.debugging_opts.ast_json {
496 control.after_hir_lowering.stop = Compilation::Stop;
499 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
500 i == OutputType::Metadata) {
501 control.after_llvm.stop = Compilation::Stop;
504 if save_analysis(sess) {
505 control.after_analysis.callback = box |state| {
506 time(state.session.time_passes(), "save analysis", || {
507 save::process_crate(state.tcx.unwrap(),
508 state.expanded_crate.unwrap(),
509 state.analysis.unwrap(),
510 state.crate_name.unwrap(),
511 DumpHandler::new(save_analysis_format(state.session),
513 state.crate_name.unwrap()))
516 control.after_analysis.run_callback_on_error = true;
517 control.make_glob_map = resolve::MakeGlobMap::Yes;
520 if sess.print_fuel_crate.is_some() {
521 let old_callback = control.compilation_done.callback;
522 control.compilation_done.callback = box move |state| {
524 let sess = state.session;
525 println!("Fuel used by {}: {}",
526 sess.print_fuel_crate.as_ref().unwrap(),
527 sess.print_fuel.get());
534 fn save_analysis(sess: &Session) -> bool {
535 sess.opts.debugging_opts.save_analysis ||
536 sess.opts.debugging_opts.save_analysis_csv ||
537 sess.opts.debugging_opts.save_analysis_api
540 fn save_analysis_format(sess: &Session) -> save::Format {
541 if sess.opts.debugging_opts.save_analysis {
543 } else if sess.opts.debugging_opts.save_analysis_csv {
545 } else if sess.opts.debugging_opts.save_analysis_api {
546 save::Format::JsonApi
552 impl RustcDefaultCalls {
553 pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation {
554 let r = matches.opt_strs("Z");
555 if r.contains(&("ls".to_string())) {
557 &Input::File(ref ifile) => {
558 let path = &(*ifile);
559 let mut v = Vec::new();
560 locator::list_file_metadata(&sess.target.target, path, &mut v).unwrap();
561 println!("{}", String::from_utf8(v).unwrap());
563 &Input::Str { .. } => {
564 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
567 return Compilation::Stop;
570 return Compilation::Continue;
574 fn print_crate_info(sess: &Session,
575 input: Option<&Input>,
576 odir: &Option<PathBuf>,
577 ofile: &Option<PathBuf>)
579 if sess.opts.prints.is_empty() {
580 return Compilation::Continue;
583 let attrs = match input {
586 let result = parse_crate_attrs(sess, input);
588 Ok(attrs) => Some(attrs),
589 Err(mut parse_error) => {
591 return Compilation::Stop;
596 for req in &sess.opts.prints {
598 PrintRequest::TargetList => {
599 let mut targets = rustc_back::target::get_targets().collect::<Vec<String>>();
601 println!("{}", targets.join("\n"));
603 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
604 PrintRequest::TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
605 PrintRequest::FileNames |
606 PrintRequest::CrateName => {
607 let input = match input {
608 Some(input) => input,
609 None => early_error(ErrorOutputType::default(), "no input file provided"),
611 let attrs = attrs.as_ref().unwrap();
612 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
613 let id = link::find_crate_name(Some(sess), attrs, input);
614 if *req == PrintRequest::CrateName {
618 let crate_types = driver::collect_crate_types(sess, attrs);
619 for &style in &crate_types {
620 let fname = link::filename_for_input(sess, style, &id, &t_outputs);
627 PrintRequest::Cfg => {
628 let allow_unstable_cfg = UnstableFeatures::from_environment()
631 let mut cfgs = Vec::new();
632 for &(name, ref value) in sess.parse_sess.config.iter() {
633 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
635 node: ast::MetaItemKind::Word,
638 if !allow_unstable_cfg && gated_cfg.is_some() {
642 cfgs.push(if let &Some(ref value) = value {
643 format!("{}=\"{}\"", name, value)
654 PrintRequest::TargetCPUs => {
655 let tm = create_target_machine(sess);
656 unsafe { llvm::LLVMRustPrintTargetCPUs(tm); }
658 PrintRequest::TargetFeatures => {
659 let tm = create_target_machine(sess);
660 unsafe { llvm::LLVMRustPrintTargetFeatures(tm); }
662 PrintRequest::RelocationModels => {
663 println!("Available relocation models:");
664 for &(name, _) in RELOC_MODEL_ARGS.iter() {
665 println!(" {}", name);
669 PrintRequest::CodeModels => {
670 println!("Available code models:");
671 for &(name, _) in CODE_GEN_MODEL_ARGS.iter(){
672 println!(" {}", name);
678 return Compilation::Stop;
682 /// Returns a version string such as "0.12.0-dev".
683 pub fn release_str() -> Option<&'static str> {
684 option_env!("CFG_RELEASE")
687 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
688 pub fn commit_hash_str() -> Option<&'static str> {
689 option_env!("CFG_VER_HASH")
692 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
693 pub fn commit_date_str() -> Option<&'static str> {
694 option_env!("CFG_VER_DATE")
697 /// Prints version information
698 pub fn version(binary: &str, matches: &getopts::Matches) {
699 let verbose = matches.opt_present("verbose");
703 option_env!("CFG_VERSION").unwrap_or("unknown version"));
705 fn unw(x: Option<&str>) -> &str {
706 x.unwrap_or("unknown")
708 println!("binary: {}", binary);
709 println!("commit-hash: {}", unw(commit_hash_str()));
710 println!("commit-date: {}", unw(commit_date_str()));
711 println!("host: {}", config::host_triple());
712 println!("release: {}", unw(release_str()));
714 println!("LLVM version: {}.{}",
715 llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor());
720 fn usage(verbose: bool, include_unstable_options: bool) {
721 let groups = if verbose {
722 config::rustc_optgroups()
724 config::rustc_short_optgroups()
726 let groups: Vec<_> = groups.into_iter()
727 .filter(|x| include_unstable_options || x.is_stable())
728 .map(|x| x.opt_group)
730 let message = format!("Usage: rustc [OPTIONS] INPUT");
731 let extra_help = if verbose {
734 "\n --help -v Print the full set of options rustc accepts"
736 println!("{}\nAdditional help:
737 -C help Print codegen options
739 Print 'lint' options and default settings
740 -Z help Print internal \
741 options for debugging rustc{}\n",
742 getopts::usage(&message, &groups),
746 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
748 Available lint options:
749 -W <foo> Warn about <foo>
753 -F <foo> Forbid <foo> \
754 (deny <foo> and all attempts to override)
758 fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
759 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
760 lints.sort_by(|x: &&Lint, y: &&Lint| {
761 match x.default_level.cmp(&y.default_level) {
762 // The sort doesn't case-fold but it's doubtful we care.
763 Equal => x.name.cmp(y.name),
770 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
771 -> Vec<(&'static str, Vec<lint::LintId>)> {
772 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
773 lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
774 &(y, _): &(&'static str, Vec<lint::LintId>)| {
780 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
783 .partition(|&(_, p)| p);
784 let plugin = sort_lints(plugin);
785 let builtin = sort_lints(builtin);
787 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
790 .partition(|&(.., p)| p);
791 let plugin_groups = sort_lint_groups(plugin_groups);
792 let builtin_groups = sort_lint_groups(builtin_groups);
794 let max_name_len = plugin.iter()
796 .map(|&s| s.name.chars().count())
799 let padded = |x: &str| {
800 let mut s = repeat(" ")
801 .take(max_name_len - x.chars().count())
802 .collect::<String>();
807 println!("Lint checks provided by rustc:\n");
808 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
809 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
811 let print_lints = |lints: Vec<&Lint>| {
813 let name = lint.name_lower().replace("_", "-");
814 println!(" {} {:7.7} {}",
816 lint.default_level.as_str(),
822 print_lints(builtin);
826 let max_name_len = max("warnings".len(),
828 .chain(&builtin_groups)
829 .map(|&(s, _)| s.chars().count())
833 let padded = |x: &str| {
834 let mut s = repeat(" ")
835 .take(max_name_len - x.chars().count())
836 .collect::<String>();
841 println!("Lint groups provided by rustc:\n");
842 println!(" {} {}", padded("name"), "sub-lints");
843 println!(" {} {}", padded("----"), "---------");
844 println!(" {} {}", padded("warnings"), "all built-in lints");
846 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
847 for (name, to) in lints {
848 let name = name.to_lowercase().replace("_", "-");
849 let desc = to.into_iter()
850 .map(|x| x.to_string().replace("_", "-"))
851 .collect::<Vec<String>>()
853 println!(" {} {}", padded(&name), desc);
858 print_lint_groups(builtin_groups);
860 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
861 (false, 0, _) | (false, _, 0) => {
862 println!("Compiler plugins can provide additional lints and lint groups. To see a \
863 listing of these, re-run `rustc -W help` with a crate filename.");
865 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
866 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
869 println!("Lint checks provided by plugins loaded by this crate:\n");
873 println!("Lint groups provided by plugins loaded by this crate:\n");
874 print_lint_groups(plugin_groups);
880 fn describe_debug_flags() {
881 println!("\nAvailable debug options:\n");
882 print_flag_list("-Z", config::DB_OPTIONS);
885 fn describe_codegen_flags() {
886 println!("\nAvailable codegen options:\n");
887 print_flag_list("-C", config::CG_OPTIONS);
890 fn print_flag_list<T>(cmdline_opt: &str,
891 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
892 let max_len = flag_list.iter()
893 .map(|&(name, _, opt_type_desc, _)| {
894 let extra_len = match opt_type_desc {
898 name.chars().count() + extra_len
903 for &(name, _, opt_type_desc, desc) in flag_list {
904 let (width, extra) = match opt_type_desc {
905 Some(..) => (max_len - 4, "=val"),
906 None => (max_len, ""),
908 println!(" {} {:>width$}{} -- {}",
910 name.replace("_", "-"),
917 /// Process command line options. Emits messages as appropriate. If compilation
918 /// should continue, returns a getopts::Matches object parsed from args,
919 /// otherwise returns None.
921 /// The compiler's handling of options is a little complicated as it ties into
922 /// our stability story, and it's even *more* complicated by historical
923 /// accidents. The current intention of each compiler option is to have one of
926 /// 1. An option is stable and can be used everywhere.
927 /// 2. An option is unstable, but was historically allowed on the stable
929 /// 3. An option is unstable, and can only be used on nightly.
931 /// Like unstable library and language features, however, unstable options have
932 /// always required a form of "opt in" to indicate that you're using them. This
933 /// provides the easy ability to scan a code base to check to see if anything
934 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
936 /// All options behind `-Z` are considered unstable by default. Other top-level
937 /// options can also be considered unstable, and they were unlocked through the
938 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
939 /// instability in both cases, though.
941 /// So with all that in mind, the comments below have some more detail about the
942 /// contortions done here to get things to work out correctly.
943 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
944 // Throw away the first argument, the name of the binary
945 let args = &args[1..];
948 // user did not write `-v` nor `-Z unstable-options`, so do not
949 // include that extra information.
954 // Parse with *all* options defined in the compiler, we don't worry about
955 // option stability here we just want to parse as much as possible.
956 let all_groups: Vec<getopts::OptGroup> = config::rustc_optgroups()
958 .map(|x| x.opt_group)
960 let matches = match getopts::getopts(&args, &all_groups) {
962 Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
965 // For all options we just parsed, we check a few aspects:
967 // * If the option is stable, we're all good
968 // * If the option wasn't passed, we're all good
969 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
970 // ourselves), then we require the `-Z unstable-options` flag to unlock
971 // this option that was passed.
972 // * If we're a nightly compiler, then unstable options are now unlocked, so
974 // * Otherwise, if we're a truly unstable option then we generate an error
975 // (unstable option being used on stable)
976 // * If we're a historically stable-but-should-be-unstable option then we
977 // emit a warning that we're going to turn this into an error soon.
978 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
980 if matches.opt_present("h") || matches.opt_present("help") {
981 // Only show unstable options in --help if we *really* accept unstable
982 // options, which catches the case where we got `-Z unstable-options` on
983 // the stable channel of Rust which was accidentally allowed
985 usage(matches.opt_present("verbose"),
986 nightly_options::is_unstable_enabled(&matches));
990 // Don't handle -W help here, because we might first load plugins.
991 let r = matches.opt_strs("Z");
992 if r.iter().any(|x| *x == "help") {
993 describe_debug_flags();
997 let cg_flags = matches.opt_strs("C");
998 if cg_flags.iter().any(|x| *x == "help") {
999 describe_codegen_flags();
1003 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1004 early_warn(ErrorOutputType::default(),
1005 "the --no-stack-check flag is deprecated and does nothing");
1008 if cg_flags.contains(&"passes=list".to_string()) {
1010 ::llvm::LLVMRustPrintPasses();
1015 if matches.opt_present("version") {
1016 version("rustc", &matches);
1023 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1025 Input::File(ref ifile) => {
1026 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1028 Input::Str { ref name, ref input } => {
1029 parse::parse_crate_attrs_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
1034 /// Runs `f` in a suitable thread for running `rustc`; returns a
1035 /// `Result` with either the return value of `f` or -- if a panic
1036 /// occurs -- the panic value.
1037 pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<Any + Send>>
1038 where F: FnOnce() -> R + Send + 'static,
1041 // Temporarily have stack size set to 16MB to deal with nom-using crates failing
1042 const STACK_SIZE: usize = 16 * 1024 * 1024; // 16MB
1044 let mut cfg = thread::Builder::new().name("rustc".to_string());
1046 // FIXME: Hacks on hacks. If the env is trying to override the stack size
1047 // then *don't* set it explicitly.
1048 if env::var_os("RUST_MIN_STACK").is_none() {
1049 cfg = cfg.stack_size(STACK_SIZE);
1052 let thread = cfg.spawn(f);
1053 thread.unwrap().join()
1056 /// Run a procedure which will detect panics in the compiler and print nicer
1057 /// error messages rather than just failing the test.
1059 /// The diagnostic emitter yielded to the procedure should be used for reporting
1060 /// errors of the compiler.
1061 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
1062 struct Sink(Arc<Mutex<Vec<u8>>>);
1063 impl Write for Sink {
1064 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1065 Write::write(&mut *self.0.lock().unwrap(), data)
1067 fn flush(&mut self) -> io::Result<()> {
1072 let data = Arc::new(Mutex::new(Vec::new()));
1073 let err = Sink(data.clone());
1075 let result = in_rustc_thread(move || {
1076 io::set_panic(Some(box err));
1080 if let Err(value) = result {
1081 // Thread panicked without emitting a fatal diagnostic
1082 if !value.is::<errors::FatalError>() {
1084 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None));
1085 let handler = errors::Handler::with_emitter(true, false, emitter);
1087 // a .span_bug or .bug call has already printed what
1088 // it wants to print.
1089 if !value.is::<errors::ExplicitBug>() {
1090 handler.emit(&MultiSpan::new(),
1092 errors::Level::Bug);
1095 let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1096 format!("we would appreciate a bug report: {}", BUG_REPORT_URL)];
1098 handler.emit(&MultiSpan::new(),
1100 errors::Level::Note);
1102 if match env::var_os("RUST_BACKTRACE") {
1103 Some(val) => &val != "0",
1106 handler.emit(&MultiSpan::new(),
1107 "run with `RUST_BACKTRACE=1` for a backtrace",
1108 errors::Level::Note);
1111 writeln!(io::stderr(), "{}", str::from_utf8(&data.lock().unwrap()).unwrap()).unwrap();
1118 fn exit_on_err() -> ! {
1119 // Panic so the process returns a failure code, but don't pollute the
1120 // output with some unnecessary panic messages, we've already
1121 // printed everything that we needed to.
1122 io::set_panic(Some(box io::sink()));
1126 pub fn diagnostics_registry() -> errors::registry::Registry {
1127 use errors::registry::Registry;
1129 let mut all_errors = Vec::new();
1130 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1131 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1132 all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
1133 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1134 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1135 all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
1136 all_errors.extend_from_slice(&rustc_const_eval::DIAGNOSTICS);
1137 all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1139 Registry::new(&all_errors)
1143 env_logger::init().unwrap();
1144 let result = run(|| run_compiler(&env::args().collect::<Vec<_>>(),
1145 &mut RustcDefaultCalls,
1148 process::exit(result as i32);