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/")]
24 #![cfg_attr(not(stage0), deny(warnings))]
26 #![feature(box_syntax)]
29 #![feature(rustc_diagnostic_macros)]
30 #![feature(rustc_private)]
31 #![feature(set_stdio)]
32 #![feature(staged_api)]
33 #![feature(question_mark)]
38 extern crate graphviz;
41 extern crate rustc_back;
42 extern crate rustc_borrowck;
43 extern crate rustc_const_eval;
44 extern crate rustc_errors as errors;
45 extern crate rustc_passes;
46 extern crate rustc_lint;
47 extern crate rustc_plugin;
48 extern crate rustc_privacy;
49 extern crate rustc_incremental;
50 extern crate rustc_metadata;
51 extern crate rustc_mir;
52 extern crate rustc_resolve;
53 extern crate rustc_save_analysis;
54 extern crate rustc_trans;
55 extern crate rustc_typeck;
56 extern crate serialize;
57 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_trans::back::link;
71 use rustc_trans::back::write::{create_target_machine, RELOC_MODEL_ARGS, CODE_GEN_MODEL_ARGS};
72 use rustc::dep_graph::DepGraph;
73 use rustc::session::{self, config, Session, build_session, CompileResult};
74 use rustc::session::config::{Input, PrintRequest, OutputType, ErrorOutputType};
75 use rustc::session::config::{get_unstable_features_setting, nightly_options};
76 use rustc::lint::Lint;
78 use rustc_metadata::loader;
79 use rustc_metadata::cstore::CStore;
80 use rustc::util::common::time;
83 use std::cmp::Ordering::Equal;
84 use std::default::Default;
86 use std::io::{self, Read, Write};
87 use std::iter::repeat;
88 use std::path::PathBuf;
92 use std::sync::{Arc, Mutex};
95 use rustc::session::early_error;
97 use syntax::{ast, json};
98 use syntax::attr::AttrMetaMethods;
99 use syntax::codemap::{CodeMap, FileLoader, RealFileLoader};
100 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
101 use syntax::parse::{self, PResult};
102 use syntax_pos::MultiSpan;
103 use errors::emitter::Emitter;
110 pub mod target_features;
113 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
117 fn abort_msg(err_count: usize) -> String {
119 0 => "aborting with no errors (maybe a bug?)".to_owned(),
120 1 => "aborting due to previous error".to_owned(),
121 e => format!("aborting due to {} previous errors", e),
125 pub fn abort_on_err<T>(result: Result<T, usize>, sess: &Session) -> T {
128 sess.fatal(&abort_msg(err_count));
134 pub fn run(args: Vec<String>) -> isize {
136 let (result, session) = run_compiler(&args, &mut RustcDefaultCalls);
137 if let Err(err_count) = result {
140 Some(sess) => sess.fatal(&abort_msg(err_count)),
143 errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
145 let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
146 handler.emit(&MultiSpan::new(),
147 &abort_msg(err_count),
148 errors::Level::Fatal);
158 pub fn run_compiler<'a>(args: &[String],
159 callbacks: &mut CompilerCalls<'a>)
160 -> (CompileResult, Option<Session>) {
161 run_compiler_with_file_loader(args, callbacks, box RealFileLoader)
164 // Parse args and run the compiler. This is the primary entry point for rustc.
165 // See comments on CompilerCalls below for details about the callbacks argument.
166 // The FileLoader provides a way to load files from sources other than the file system.
167 pub fn run_compiler_with_file_loader<'a, L>(args: &[String],
168 callbacks: &mut CompilerCalls<'a>,
170 -> (CompileResult, Option<Session>)
171 where L: FileLoader + 'static {
172 macro_rules! do_or_return {($expr: expr, $sess: expr) => {
174 Compilation::Stop => return (Ok(()), $sess),
175 Compilation::Continue => {}
179 let matches = match handle_options(args) {
180 Some(matches) => matches,
181 None => return (Ok(()), None),
184 let sopts = config::build_session_options(&matches);
186 if sopts.debugging_opts.debug_llvm {
187 unsafe { llvm::LLVMRustSetDebug(1); }
190 let descriptions = diagnostics_registry();
192 do_or_return!(callbacks.early_callback(&matches,
198 let (odir, ofile) = make_output(&matches);
199 let (input, input_file_path) = match make_input(&matches.free) {
200 Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
201 None => match callbacks.no_input(&matches, &sopts, &odir, &ofile, &descriptions) {
202 Some((input, input_file_path)) => (input, input_file_path),
203 None => return (Ok(()), None),
207 let dep_graph = DepGraph::new(sopts.build_dep_graph());
208 let cstore = Rc::new(CStore::new(&dep_graph));
209 let codemap = Rc::new(CodeMap::with_file_loader(loader));
210 let sess = session::build_session_with_codemap(sopts,
216 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
217 let mut cfg = config::build_configuration(&sess);
218 target_features::add_configuration(&mut cfg, &sess);
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, cfg, &input, &odir, &ofile,
225 Some(plugins), &control),
229 // Extract output directory and file from matches.
230 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
231 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
232 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
236 // Extract input (string or file and optional path) from matches.
237 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
238 if free_matches.len() == 1 {
239 let ifile = &free_matches[0][..];
241 let mut src = String::new();
242 io::stdin().read_to_string(&mut src).unwrap();
243 Some((Input::Str { name: driver::anon_src(), input: src },
246 Some((Input::File(PathBuf::from(ifile)),
247 Some(PathBuf::from(ifile))))
254 fn parse_pretty(sess: &Session,
255 matches: &getopts::Matches)
256 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
257 let pretty = if sess.opts.debugging_opts.unstable_options {
258 matches.opt_default("pretty", "normal").map(|a| {
259 // stable pretty-print variants only
260 pretty::parse_pretty(sess, &a, false)
265 if pretty.is_none() && sess.unstable_options() {
266 matches.opt_str("unpretty").map(|a| {
267 // extended with unstable pretty-print variants
268 pretty::parse_pretty(sess, &a, true)
275 // Whether to stop or continue compilation.
276 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
277 pub enum Compilation {
283 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
285 Compilation::Stop => Compilation::Stop,
286 Compilation::Continue => next(),
291 // A trait for customising the compilation process. Offers a number of hooks for
292 // executing custom code or customising input.
293 pub trait CompilerCalls<'a> {
294 // Hook for a callback early in the process of handling arguments. This will
295 // be called straight after options have been parsed but before anything
296 // else (e.g., selecting input and output).
297 fn early_callback(&mut self,
298 _: &getopts::Matches,
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,
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 fn check_cfg(sopts: &config::Options,
379 output: ErrorOutputType) {
380 let emitter: Box<Emitter> = match output {
381 config::ErrorOutputType::HumanReadable(color_config) => {
382 Box::new(errors::emitter::EmitterWriter::stderr(color_config, None))
384 config::ErrorOutputType::Json => Box::new(json::JsonEmitter::basic()),
386 let handler = errors::Handler::with_emitter(true, false, emitter);
388 let mut saw_invalid_predicate = false;
389 for item in sopts.cfg.iter() {
390 if item.is_meta_item_list() {
391 saw_invalid_predicate = true;
392 handler.emit(&MultiSpan::new(),
393 &format!("invalid predicate in --cfg command line argument: `{}`",
395 errors::Level::Fatal);
399 if saw_invalid_predicate {
400 panic!(errors::FatalError);
404 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
405 fn early_callback(&mut self,
406 matches: &getopts::Matches,
407 sopts: &config::Options,
408 descriptions: &errors::registry::Registry,
409 output: ErrorOutputType)
411 if let Some(ref code) = matches.opt_str("explain") {
412 handle_explain(code, descriptions, output);
413 return Compilation::Stop;
416 check_cfg(sopts, output);
417 Compilation::Continue
420 fn no_input(&mut self,
421 matches: &getopts::Matches,
422 sopts: &config::Options,
423 odir: &Option<PathBuf>,
424 ofile: &Option<PathBuf>,
425 descriptions: &errors::registry::Registry)
426 -> Option<(Input, Option<PathBuf>)> {
427 match matches.free.len() {
429 if sopts.describe_lints {
430 let mut ls = lint::LintStore::new();
431 rustc_lint::register_builtins(&mut ls, None);
432 describe_lints(&ls, false);
435 let dep_graph = DepGraph::new(sopts.build_dep_graph());
436 let cstore = Rc::new(CStore::new(&dep_graph));
437 let sess = build_session(sopts.clone(),
440 descriptions.clone(),
442 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
443 let should_stop = RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
444 if should_stop == Compilation::Stop {
447 early_error(sopts.error_format, "no input filename given");
449 1 => panic!("make_input should have provided valid inputs"),
450 _ => early_error(sopts.error_format, "multiple input filenames provided"),
456 fn late_callback(&mut self,
457 matches: &getopts::Matches,
460 odir: &Option<PathBuf>,
461 ofile: &Option<PathBuf>)
463 RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
464 .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input))
467 fn build_controller(&mut self,
469 matches: &getopts::Matches)
470 -> CompileController<'a> {
471 let mut control = CompileController::basic();
473 if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
474 if ppm.needs_ast_map(&opt_uii) {
475 control.after_hir_lowering.stop = Compilation::Stop;
477 control.after_parse.callback = box move |state| {
478 state.krate = Some(pretty::fold_crate(state.krate.take().unwrap(), ppm));
480 control.after_hir_lowering.callback = box move |state| {
481 pretty::print_after_hir_lowering(state.session,
482 state.ast_map.unwrap(),
483 state.analysis.unwrap(),
484 state.resolutions.unwrap(),
486 &state.expanded_crate.take().unwrap(),
487 state.crate_name.unwrap(),
489 state.arenas.unwrap(),
494 control.after_parse.stop = Compilation::Stop;
496 control.after_parse.callback = box move |state| {
497 let krate = pretty::fold_crate(state.krate.take().unwrap(), ppm);
498 pretty::print_after_parsing(state.session,
509 if sess.opts.parse_only || sess.opts.debugging_opts.show_span.is_some() ||
510 sess.opts.debugging_opts.ast_json_noexpand {
511 control.after_parse.stop = Compilation::Stop;
514 if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
515 control.after_hir_lowering.stop = Compilation::Stop;
518 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe) {
519 control.after_llvm.stop = Compilation::Stop;
522 if save_analysis(sess) {
523 control.after_analysis.callback = box |state| {
524 time(state.session.time_passes(), "save analysis", || {
525 save::process_crate(state.tcx.unwrap(),
526 state.expanded_crate.unwrap(),
527 state.analysis.unwrap(),
528 state.crate_name.unwrap(),
530 save_analysis_format(state.session))
533 control.after_analysis.run_callback_on_error = true;
534 control.make_glob_map = resolve::MakeGlobMap::Yes;
541 fn save_analysis(sess: &Session) -> bool {
542 sess.opts.debugging_opts.save_analysis ||
543 sess.opts.debugging_opts.save_analysis_csv
546 fn save_analysis_format(sess: &Session) -> save::Format {
547 if sess.opts.debugging_opts.save_analysis {
549 } else if sess.opts.debugging_opts.save_analysis_csv {
556 impl RustcDefaultCalls {
557 pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation {
558 let r = matches.opt_strs("Z");
559 if r.contains(&("ls".to_string())) {
561 &Input::File(ref ifile) => {
562 let path = &(*ifile);
563 let mut v = Vec::new();
564 loader::list_file_metadata(&sess.target.target, path, &mut v)
566 println!("{}", String::from_utf8(v).unwrap());
568 &Input::Str { .. } => {
569 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
572 return Compilation::Stop;
575 return Compilation::Continue;
579 fn print_crate_info(sess: &Session,
580 input: Option<&Input>,
581 odir: &Option<PathBuf>,
582 ofile: &Option<PathBuf>)
584 if sess.opts.prints.is_empty() {
585 return Compilation::Continue;
588 let attrs = match input {
591 let result = parse_crate_attrs(sess, input);
593 Ok(attrs) => Some(attrs),
594 Err(mut parse_error) => {
596 return Compilation::Stop;
601 for req in &sess.opts.prints {
603 PrintRequest::TargetList => {
604 let mut targets = rustc_back::target::get_targets().collect::<Vec<String>>();
606 println!("{}", targets.join("\n"));
608 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
609 PrintRequest::FileNames |
610 PrintRequest::CrateName => {
611 let input = match input {
612 Some(input) => input,
613 None => early_error(ErrorOutputType::default(), "no input file provided"),
615 let attrs = attrs.as_ref().unwrap();
616 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
617 let id = link::find_crate_name(Some(sess), attrs, input);
618 if *req == PrintRequest::CrateName {
622 let crate_types = driver::collect_crate_types(sess, attrs);
623 for &style in &crate_types {
624 let fname = link::filename_for_input(sess, style, &id, &t_outputs);
631 PrintRequest::Cfg => {
632 let mut cfg = config::build_configuration(&sess);
633 target_features::add_configuration(&mut cfg, &sess);
635 let allow_unstable_cfg = match get_unstable_features_setting() {
636 UnstableFeatures::Disallow => false,
641 if !allow_unstable_cfg && GatedCfg::gate(&*cfg).is_some() {
645 println!("{}", cfg.name());
646 } else if cfg.is_value_str() {
647 if let Some(s) = cfg.value_str() {
648 println!("{}=\"{}\"", cfg.name(), s);
650 } else if cfg.is_meta_item_list() {
651 // Right now there are not and should not be any
652 // MetaItemKind::List items in the configuration returned by
653 // `build_configuration`.
654 panic!("MetaItemKind::List encountered in default cfg")
658 PrintRequest::TargetCPUs => {
659 let tm = create_target_machine(sess);
660 unsafe { llvm::LLVMRustPrintTargetCPUs(tm); }
662 PrintRequest::TargetFeatures => {
663 let tm = create_target_machine(sess);
664 unsafe { llvm::LLVMRustPrintTargetFeatures(tm); }
666 PrintRequest::RelocationModels => {
667 println!("Available relocation models:");
668 for &(name, _) in RELOC_MODEL_ARGS.iter() {
669 println!(" {}", name);
673 PrintRequest::CodeModels => {
674 println!("Available code models:");
675 for &(name, _) in CODE_GEN_MODEL_ARGS.iter(){
676 println!(" {}", name);
682 return Compilation::Stop;
686 /// Returns a version string such as "0.12.0-dev".
687 pub fn release_str() -> Option<&'static str> {
688 option_env!("CFG_RELEASE")
691 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
692 pub fn commit_hash_str() -> Option<&'static str> {
693 option_env!("CFG_VER_HASH")
696 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
697 pub fn commit_date_str() -> Option<&'static str> {
698 option_env!("CFG_VER_DATE")
701 /// Prints version information
702 pub fn version(binary: &str, matches: &getopts::Matches) {
703 let verbose = matches.opt_present("verbose");
707 option_env!("CFG_VERSION").unwrap_or("unknown version"));
709 fn unw(x: Option<&str>) -> &str {
710 x.unwrap_or("unknown")
712 println!("binary: {}", binary);
713 println!("commit-hash: {}", unw(commit_hash_str()));
714 println!("commit-date: {}", unw(commit_date_str()));
715 println!("host: {}", config::host_triple());
716 println!("release: {}", unw(release_str()));
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, and deny all overrides)
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.as_str().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 complication 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.contains(&"passes=list".to_string()) {
1005 ::llvm::LLVMRustPrintPasses();
1010 if matches.opt_present("version") {
1011 version("rustc", &matches);
1018 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1020 Input::File(ref ifile) => {
1021 parse::parse_crate_attrs_from_file(ifile, Vec::new(), &sess.parse_sess)
1023 Input::Str { ref name, ref input } => {
1024 parse::parse_crate_attrs_from_source_str(name.clone(),
1032 /// Run a procedure which will detect panics in the compiler and print nicer
1033 /// error messages rather than just failing the test.
1035 /// The diagnostic emitter yielded to the procedure should be used for reporting
1036 /// errors of the compiler.
1037 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
1038 const STACK_SIZE: usize = 8 * 1024 * 1024; // 8MB
1040 struct Sink(Arc<Mutex<Vec<u8>>>);
1041 impl Write for Sink {
1042 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1043 Write::write(&mut *self.0.lock().unwrap(), data)
1045 fn flush(&mut self) -> io::Result<()> {
1050 let data = Arc::new(Mutex::new(Vec::new()));
1051 let err = Sink(data.clone());
1053 let mut cfg = thread::Builder::new().name("rustc".to_string());
1055 // FIXME: Hacks on hacks. If the env is trying to override the stack size
1056 // then *don't* set it explicitly.
1057 if env::var_os("RUST_MIN_STACK").is_none() {
1058 cfg = cfg.stack_size(STACK_SIZE);
1061 let thread = cfg.spawn(move || {
1062 io::set_panic(box err);
1066 if let Err(value) = thread.unwrap().join() {
1067 // Thread panicked without emitting a fatal diagnostic
1068 if !value.is::<errors::FatalError>() {
1070 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None));
1071 let handler = errors::Handler::with_emitter(true, false, emitter);
1073 // a .span_bug or .bug call has already printed what
1074 // it wants to print.
1075 if !value.is::<errors::ExplicitBug>() {
1076 handler.emit(&MultiSpan::new(),
1078 errors::Level::Bug);
1081 let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1082 format!("we would appreciate a bug report: {}", BUG_REPORT_URL)];
1084 handler.emit(&MultiSpan::new(),
1086 errors::Level::Note);
1088 if match env::var_os("RUST_BACKTRACE") {
1089 Some(val) => &val != "0",
1092 handler.emit(&MultiSpan::new(),
1093 "run with `RUST_BACKTRACE=1` for a backtrace",
1094 errors::Level::Note);
1097 println!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
1104 fn exit_on_err() -> ! {
1105 // Panic so the process returns a failure code, but don't pollute the
1106 // output with some unnecessary panic messages, we've already
1107 // printed everything that we needed to.
1108 io::set_panic(box io::sink());
1112 pub fn diagnostics_registry() -> errors::registry::Registry {
1113 use errors::registry::Registry;
1115 let mut all_errors = Vec::new();
1116 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1117 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1118 all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
1119 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1120 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1121 all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
1122 all_errors.extend_from_slice(&rustc_const_eval::DIAGNOSTICS);
1124 Registry::new(&all_errors)
1128 let result = run(env::args().collect());
1129 process::exit(result as i32);