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_passes;
44 extern crate rustc_front;
45 extern crate rustc_lint;
46 extern crate rustc_plugin;
47 extern crate rustc_privacy;
48 extern crate rustc_metadata;
49 extern crate rustc_mir;
50 extern crate rustc_resolve;
51 extern crate rustc_trans;
52 extern crate rustc_typeck;
53 extern crate serialize;
54 extern crate rustc_llvm as llvm;
59 extern crate syntax_ext;
61 use driver::CompileController;
62 use pretty::{PpMode, UserIdentifiedItem};
64 use rustc_resolve as resolve;
65 use rustc_trans::back::link;
66 use rustc_trans::save;
67 use rustc::session::{config, Session, build_session, CompileResult};
68 use rustc::session::config::{Input, PrintRequest, OutputType, ErrorOutputType};
69 use rustc::session::config::{get_unstable_features_setting, OptionStability};
70 use rustc::middle::cstore::CrateStore;
71 use rustc::lint::Lint;
73 use rustc_metadata::loader;
74 use rustc_metadata::cstore::CStore;
75 use rustc::util::common::time;
78 use std::cmp::Ordering::Equal;
79 use std::default::Default;
81 use std::io::{self, Read, Write};
82 use std::iter::repeat;
83 use std::path::PathBuf;
87 use std::sync::{Arc, Mutex};
90 use rustc::session::{early_error, early_warn};
93 use syntax::parse::{self, PResult};
95 use syntax::errors::emitter::Emitter;
96 use syntax::diagnostics;
97 use syntax::parse::token;
98 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
105 pub mod target_features;
108 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
112 fn abort_msg(err_count: usize) -> String {
114 0 => "aborting with no errors (maybe a bug?)".to_owned(),
115 1 => "aborting due to previous error".to_owned(),
116 e => format!("aborting due to {} previous errors", e),
120 pub fn abort_on_err<T>(result: Result<T, usize>, sess: &Session) -> T {
123 sess.fatal(&abort_msg(err_count));
129 pub fn run(args: Vec<String>) -> isize {
131 let (result, session) = run_compiler(&args, &mut RustcDefaultCalls);
132 if let Err(err_count) = result {
135 Some(sess) => sess.fatal(&abort_msg(err_count)),
138 errors::emitter::BasicEmitter::stderr(errors::ColorConfig::Auto);
139 emitter.emit(None, &abort_msg(err_count), None, errors::Level::Fatal);
149 // Parse args and run the compiler. This is the primary entry point for rustc.
150 // See comments on CompilerCalls below for details about the callbacks argument.
151 pub fn run_compiler<'a>(args: &[String],
152 callbacks: &mut CompilerCalls<'a>)
153 -> (CompileResult, Option<Session>) {
154 macro_rules! do_or_return {($expr: expr, $sess: expr) => {
156 Compilation::Stop => return (Ok(()), $sess),
157 Compilation::Continue => {}
161 let matches = match handle_options(args) {
162 Some(matches) => matches,
163 None => return (Ok(()), None),
166 let sopts = config::build_session_options(&matches);
168 let descriptions = diagnostics_registry();
170 do_or_return!(callbacks.early_callback(&matches,
176 let (odir, ofile) = make_output(&matches);
177 let (input, input_file_path) = match make_input(&matches.free) {
178 Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
179 None => match callbacks.no_input(&matches, &sopts, &odir, &ofile, &descriptions) {
180 Some((input, input_file_path)) => (input, input_file_path),
181 None => return (Ok(()), None),
185 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
186 let sess = build_session(sopts, input_file_path, descriptions, cstore.clone());
187 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
188 let mut cfg = config::build_configuration(&sess);
189 target_features::add_configuration(&mut cfg, &sess);
191 do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile), Some(sess));
193 // It is somewhat unfortunate that this is hardwired in - this is forced by
194 // the fact that pretty_print_input requires the session by value.
195 let pretty = callbacks.parse_pretty(&sess, &matches);
197 Some((ppm, opt_uii)) => {
198 pretty::pretty_print_input(sess, &cstore, cfg, &input, ppm, opt_uii, ofile);
199 return (Ok(()), None);
206 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
207 let control = callbacks.build_controller(&sess);
208 (driver::compile_input(&sess, &cstore, cfg, &input, &odir, &ofile,
209 Some(plugins), &control),
213 // Extract output directory and file from matches.
214 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
215 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
216 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
220 // Extract input (string or file and optional path) from matches.
221 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
222 if free_matches.len() == 1 {
223 let ifile = &free_matches[0][..];
225 let mut src = String::new();
226 io::stdin().read_to_string(&mut src).unwrap();
227 Some((Input::Str { name: driver::anon_src(), input: src },
230 Some((Input::File(PathBuf::from(ifile)),
231 Some(PathBuf::from(ifile))))
238 // Whether to stop or continue compilation.
239 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
240 pub enum Compilation {
246 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
248 Compilation::Stop => Compilation::Stop,
249 Compilation::Continue => next(),
254 // A trait for customising the compilation process. Offers a number of hooks for
255 // executing custom code or customising input.
256 pub trait CompilerCalls<'a> {
257 // Hook for a callback early in the process of handling arguments. This will
258 // be called straight after options have been parsed but before anything
259 // else (e.g., selecting input and output).
260 fn early_callback(&mut self,
261 _: &getopts::Matches,
263 _: &diagnostics::registry::Registry,
266 Compilation::Continue
269 // Hook for a callback late in the process of handling arguments. This will
270 // be called just before actual compilation starts (and before build_controller
271 // is called), after all arguments etc. have been completely handled.
272 fn late_callback(&mut self,
273 _: &getopts::Matches,
279 Compilation::Continue
282 // Called after we extract the input from the arguments. Gives the implementer
283 // an opportunity to change the inputs or to add some custom input handling.
284 // The default behaviour is to simply pass through the inputs.
285 fn some_input(&mut self,
287 input_path: Option<PathBuf>)
288 -> (Input, Option<PathBuf>) {
292 // Called after we extract the input from the arguments if there is no valid
293 // input. Gives the implementer an opportunity to supply alternate input (by
294 // returning a Some value) or to add custom behaviour for this error such as
295 // emitting error messages. Returning None will cause compilation to stop
297 fn no_input(&mut self,
298 _: &getopts::Matches,
302 _: &diagnostics::registry::Registry)
303 -> Option<(Input, Option<PathBuf>)> {
307 // Parse pretty printing information from the arguments. The implementer can
308 // choose to ignore this (the default will return None) which will skip pretty
309 // printing. If you do want to pretty print, it is recommended to use the
310 // implementation of this method from RustcDefaultCalls.
311 // FIXME, this is a terrible bit of API. Parsing of pretty printing stuff
312 // should be done as part of the framework and the implementor should customise
313 // handling of it. However, that is not possible atm because pretty printing
314 // essentially goes off and takes another path through the compiler which
315 // means the session is either moved or not depending on what parse_pretty
316 // returns (we could fix this by cloning, but it's another hack). The proper
317 // solution is to handle pretty printing as if it were a compiler extension,
318 // extending CompileController to make this work (see for example the treatment
319 // of save-analysis in RustcDefaultCalls::build_controller).
320 fn parse_pretty(&mut self,
322 _matches: &getopts::Matches)
323 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
327 // Create a CompilController struct for controlling the behaviour of
329 fn build_controller(&mut self, &Session) -> CompileController<'a>;
332 // CompilerCalls instance for a regular rustc build.
333 #[derive(Copy, Clone)]
334 pub struct RustcDefaultCalls;
336 fn handle_explain(code: &str,
337 descriptions: &diagnostics::registry::Registry,
338 output: ErrorOutputType) {
339 let normalised = if code.starts_with("E") {
342 format!("E{0:0>4}", code)
344 match descriptions.find_description(&normalised) {
345 Some(ref description) => {
346 // Slice off the leading newline and print.
347 print!("{}", &description[1..]);
350 early_error(output, &format!("no extended information for {}", code));
355 fn check_cfg(sopts: &config::Options,
356 output: ErrorOutputType) {
357 let mut emitter: Box<Emitter> = match output {
358 config::ErrorOutputType::HumanReadable(color_config) => {
359 Box::new(errors::emitter::BasicEmitter::stderr(color_config))
361 config::ErrorOutputType::Json => Box::new(errors::json::JsonEmitter::basic()),
364 let mut saw_invalid_predicate = false;
365 for item in sopts.cfg.iter() {
367 ast::MetaItemKind::List(ref pred, _) => {
368 saw_invalid_predicate = true;
370 &format!("invalid predicate in --cfg command line argument: `{}`",
373 errors::Level::Fatal);
379 if saw_invalid_predicate {
380 panic!(errors::FatalError);
384 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
385 fn early_callback(&mut self,
386 matches: &getopts::Matches,
387 sopts: &config::Options,
388 descriptions: &diagnostics::registry::Registry,
389 output: ErrorOutputType)
391 if let Some(ref code) = matches.opt_str("explain") {
392 handle_explain(code, descriptions, output);
393 return Compilation::Stop;
396 check_cfg(sopts, output);
397 Compilation::Continue
400 fn no_input(&mut self,
401 matches: &getopts::Matches,
402 sopts: &config::Options,
403 odir: &Option<PathBuf>,
404 ofile: &Option<PathBuf>,
405 descriptions: &diagnostics::registry::Registry)
406 -> Option<(Input, Option<PathBuf>)> {
407 match matches.free.len() {
409 if sopts.describe_lints {
410 let mut ls = lint::LintStore::new();
411 rustc_lint::register_builtins(&mut ls, None);
412 describe_lints(&ls, false);
415 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
416 let sess = build_session(sopts.clone(), None, descriptions.clone(),
418 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
419 let should_stop = RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
420 if should_stop == Compilation::Stop {
423 early_error(sopts.error_format, "no input filename given");
425 1 => panic!("make_input should have provided valid inputs"),
426 _ => early_error(sopts.error_format, "multiple input filenames provided"),
432 fn parse_pretty(&mut self,
434 matches: &getopts::Matches)
435 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
436 let pretty = if sess.opts.debugging_opts.unstable_options {
437 matches.opt_default("pretty", "normal").map(|a| {
438 // stable pretty-print variants only
439 pretty::parse_pretty(sess, &a, false)
444 if pretty.is_none() && sess.unstable_options() {
445 matches.opt_str("unpretty").map(|a| {
446 // extended with unstable pretty-print variants
447 pretty::parse_pretty(sess, &a, true)
454 fn late_callback(&mut self,
455 matches: &getopts::Matches,
458 odir: &Option<PathBuf>,
459 ofile: &Option<PathBuf>)
461 RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
462 .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input))
465 fn build_controller(&mut self, sess: &Session) -> CompileController<'a> {
466 let mut control = CompileController::basic();
468 if sess.opts.parse_only || sess.opts.debugging_opts.show_span.is_some() ||
469 sess.opts.debugging_opts.ast_json_noexpand {
470 control.after_parse.stop = Compilation::Stop;
473 if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
474 control.after_write_deps.stop = Compilation::Stop;
477 if sess.opts.no_trans {
478 control.after_analysis.stop = Compilation::Stop;
481 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe) {
482 control.after_llvm.stop = Compilation::Stop;
485 if sess.opts.debugging_opts.save_analysis {
486 control.after_analysis.callback = box |state| {
487 time(state.session.time_passes(), "save analysis", || {
488 save::process_crate(state.tcx.unwrap(),
490 state.krate.unwrap(),
491 state.analysis.unwrap(),
492 state.crate_name.unwrap(),
496 control.after_analysis.run_callback_on_error = true;
497 control.make_glob_map = resolve::MakeGlobMap::Yes;
504 impl RustcDefaultCalls {
505 pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation {
506 let r = matches.opt_strs("Z");
507 if r.contains(&("ls".to_string())) {
509 &Input::File(ref ifile) => {
510 let path = &(*ifile);
511 let mut v = Vec::new();
512 loader::list_file_metadata(&sess.target.target, path, &mut v)
514 println!("{}", String::from_utf8(v).unwrap());
516 &Input::Str { .. } => {
517 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
520 return Compilation::Stop;
523 return Compilation::Continue;
527 fn print_crate_info(sess: &Session,
528 input: Option<&Input>,
529 odir: &Option<PathBuf>,
530 ofile: &Option<PathBuf>)
532 if sess.opts.prints.is_empty() {
533 return Compilation::Continue;
536 let attrs = match input {
539 let result = parse_crate_attrs(sess, input);
541 Ok(attrs) => Some(attrs),
542 Err(mut parse_error) => {
544 return Compilation::Stop;
549 for req in &sess.opts.prints {
551 PrintRequest::TargetList => {
552 let mut targets = rustc_back::target::TARGETS.to_vec();
554 println!("{}", targets.join("\n"));
556 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
557 PrintRequest::FileNames |
558 PrintRequest::CrateName => {
559 let input = match input {
560 Some(input) => input,
561 None => early_error(ErrorOutputType::default(), "no input file provided"),
563 let attrs = attrs.as_ref().unwrap();
564 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
565 let id = link::find_crate_name(Some(sess), attrs, input);
566 if *req == PrintRequest::CrateName {
570 let crate_types = driver::collect_crate_types(sess, attrs);
571 for &style in &crate_types {
572 let fname = link::filename_for_input(sess, style, &id, &t_outputs);
579 PrintRequest::Cfg => {
580 let mut cfg = config::build_configuration(&sess);
581 target_features::add_configuration(&mut cfg, &sess);
583 let allow_unstable_cfg = match get_unstable_features_setting() {
584 UnstableFeatures::Disallow => false,
589 if !allow_unstable_cfg && GatedCfg::gate(&*cfg).is_some() {
593 ast::MetaItemKind::Word(ref word) => println!("{}", word),
594 ast::MetaItemKind::NameValue(ref name, ref value) => {
595 println!("{}=\"{}\"", name, match value.node {
596 ast::LitKind::Str(ref s, _) => s,
600 // Right now there are not and should not be any
601 // MetaItemKind::List items in the configuration returned by
602 // `build_configuration`.
603 ast::MetaItemKind::List(..) => {
604 panic!("MetaItemKind::List encountered in default cfg")
611 return Compilation::Stop;
615 /// Returns a version string such as "0.12.0-dev".
616 pub fn release_str() -> Option<&'static str> {
617 option_env!("CFG_RELEASE")
620 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
621 pub fn commit_hash_str() -> Option<&'static str> {
622 option_env!("CFG_VER_HASH")
625 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
626 pub fn commit_date_str() -> Option<&'static str> {
627 option_env!("CFG_VER_DATE")
630 /// Prints version information
631 pub fn version(binary: &str, matches: &getopts::Matches) {
632 let verbose = matches.opt_present("verbose");
636 option_env!("CFG_VERSION").unwrap_or("unknown version"));
638 fn unw(x: Option<&str>) -> &str {
639 x.unwrap_or("unknown")
641 println!("binary: {}", binary);
642 println!("commit-hash: {}", unw(commit_hash_str()));
643 println!("commit-date: {}", unw(commit_date_str()));
644 println!("host: {}", config::host_triple());
645 println!("release: {}", unw(release_str()));
649 fn usage(verbose: bool, include_unstable_options: bool) {
650 let groups = if verbose {
651 config::rustc_optgroups()
653 config::rustc_short_optgroups()
655 let groups: Vec<_> = groups.into_iter()
656 .filter(|x| include_unstable_options || x.is_stable())
657 .map(|x| x.opt_group)
659 let message = format!("Usage: rustc [OPTIONS] INPUT");
660 let extra_help = if verbose {
663 "\n --help -v Print the full set of options rustc accepts"
665 println!("{}\nAdditional help:
666 -C help Print codegen options
668 Print 'lint' options and default settings
669 -Z help Print internal \
670 options for debugging rustc{}\n",
671 getopts::usage(&message, &groups),
675 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
677 Available lint options:
678 -W <foo> Warn about <foo>
682 -F <foo> Forbid <foo> \
683 (deny, and deny all overrides)
687 fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
688 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
689 lints.sort_by(|x: &&Lint, y: &&Lint| {
690 match x.default_level.cmp(&y.default_level) {
691 // The sort doesn't case-fold but it's doubtful we care.
692 Equal => x.name.cmp(y.name),
699 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
700 -> Vec<(&'static str, Vec<lint::LintId>)> {
701 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
702 lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
703 &(y, _): &(&'static str, Vec<lint::LintId>)| {
709 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
712 .partition(|&(_, p)| p);
713 let plugin = sort_lints(plugin);
714 let builtin = sort_lints(builtin);
716 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
719 .partition(|&(_, _, p)| p);
720 let plugin_groups = sort_lint_groups(plugin_groups);
721 let builtin_groups = sort_lint_groups(builtin_groups);
723 let max_name_len = plugin.iter()
725 .map(|&s| s.name.chars().count())
728 let padded = |x: &str| {
729 let mut s = repeat(" ")
730 .take(max_name_len - x.chars().count())
731 .collect::<String>();
736 println!("Lint checks provided by rustc:\n");
737 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
738 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
740 let print_lints = |lints: Vec<&Lint>| {
742 let name = lint.name_lower().replace("_", "-");
743 println!(" {} {:7.7} {}",
745 lint.default_level.as_str(),
751 print_lints(builtin);
755 let max_name_len = max("warnings".len(),
757 .chain(&builtin_groups)
758 .map(|&(s, _)| s.chars().count())
762 let padded = |x: &str| {
763 let mut s = repeat(" ")
764 .take(max_name_len - x.chars().count())
765 .collect::<String>();
770 println!("Lint groups provided by rustc:\n");
771 println!(" {} {}", padded("name"), "sub-lints");
772 println!(" {} {}", padded("----"), "---------");
773 println!(" {} {}", padded("warnings"), "all built-in lints");
775 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
776 for (name, to) in lints {
777 let name = name.to_lowercase().replace("_", "-");
778 let desc = to.into_iter()
779 .map(|x| x.as_str().replace("_", "-"))
780 .collect::<Vec<String>>()
782 println!(" {} {}", padded(&name[..]), desc);
787 print_lint_groups(builtin_groups);
789 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
790 (false, 0, _) | (false, _, 0) => {
791 println!("Compiler plugins can provide additional lints and lint groups. To see a \
792 listing of these, re-run `rustc -W help` with a crate filename.");
794 (false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
795 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
798 println!("Lint checks provided by plugins loaded by this crate:\n");
802 println!("Lint groups provided by plugins loaded by this crate:\n");
803 print_lint_groups(plugin_groups);
809 fn describe_debug_flags() {
810 println!("\nAvailable debug options:\n");
811 print_flag_list("-Z", config::DB_OPTIONS);
814 fn describe_codegen_flags() {
815 println!("\nAvailable codegen options:\n");
816 print_flag_list("-C", config::CG_OPTIONS);
819 fn print_flag_list<T>(cmdline_opt: &str,
820 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
821 let max_len = flag_list.iter()
822 .map(|&(name, _, opt_type_desc, _)| {
823 let extra_len = match opt_type_desc {
827 name.chars().count() + extra_len
832 for &(name, _, opt_type_desc, desc) in flag_list {
833 let (width, extra) = match opt_type_desc {
834 Some(..) => (max_len - 4, "=val"),
835 None => (max_len, ""),
837 println!(" {} {:>width$}{} -- {}",
839 name.replace("_", "-"),
846 /// Process command line options. Emits messages as appropriate. If compilation
847 /// should continue, returns a getopts::Matches object parsed from args,
848 /// otherwise returns None.
850 /// The compiler's handling of options is a little complication as it ties into
851 /// our stability story, and it's even *more* complicated by historical
852 /// accidents. The current intention of each compiler option is to have one of
855 /// 1. An option is stable and can be used everywhere.
856 /// 2. An option is unstable, but was historically allowed on the stable
858 /// 3. An option is unstable, and can only be used on nightly.
860 /// Like unstable library and language features, however, unstable options have
861 /// always required a form of "opt in" to indicate that you're using them. This
862 /// provides the easy ability to scan a code base to check to see if anything
863 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
865 /// All options behind `-Z` are considered unstable by default. Other top-level
866 /// options can also be considered unstable, and they were unlocked through the
867 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
868 /// instability in both cases, though.
870 /// So with all that in mind, the comments below have some more detail about the
871 /// contortions done here to get things to work out correctly.
872 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
873 // Throw away the first argument, the name of the binary
874 let args = &args[1..];
877 // user did not write `-v` nor `-Z unstable-options`, so do not
878 // include that extra information.
883 // Parse with *all* options defined in the compiler, we don't worry about
884 // option stability here we just want to parse as much as possible.
885 let all_groups: Vec<getopts::OptGroup> = config::rustc_optgroups()
887 .map(|x| x.opt_group)
889 let matches = match getopts::getopts(&args[..], &all_groups) {
891 Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
894 // For all options we just parsed, we check a few aspects:
896 // * If the option is stable, we're all good
897 // * If the option wasn't passed, we're all good
898 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
899 // ourselves), then we require the `-Z unstable-options` flag to unlock
900 // this option that was passed.
901 // * If we're a nightly compiler, then unstable options are now unlocked, so
903 // * Otherwise, if we're a truly unstable option then we generate an error
904 // (unstable option being used on stable)
905 // * If we're a historically stable-but-should-be-unstable option then we
906 // emit a warning that we're going to turn this into an error soon.
907 let has_z_unstable_options = matches.opt_strs("Z")
909 .any(|x| *x == "unstable-options");
910 let really_allows_unstable_options = match get_unstable_features_setting() {
911 UnstableFeatures::Disallow => false,
914 for opt in config::rustc_optgroups() {
915 if opt.stability == OptionStability::Stable {
918 let opt_name = if opt.opt_group.long_name.is_empty() {
919 &opt.opt_group.short_name
921 &opt.opt_group.long_name
923 if !matches.opt_present(opt_name) {
926 if opt_name != "Z" && !has_z_unstable_options {
927 let msg = format!("the `-Z unstable-options` flag must also be \
928 passed to enable the flag `{}`", opt_name);
929 early_error(ErrorOutputType::default(), &msg);
931 if really_allows_unstable_options {
934 match opt.stability {
935 OptionStability::Unstable => {
936 let msg = format!("the option `{}` is only accepted on the \
937 nightly compiler", opt_name);
938 early_error(ErrorOutputType::default(), &msg);
940 OptionStability::UnstableButNotReally => {
941 let msg = format!("the option `{}` is is unstable and should \
942 only be used on the nightly compiler, but \
943 it is currently accepted for backwards \
944 compatibility; this will soon change, \
945 see issue #31847 for more details",
947 early_warn(ErrorOutputType::default(), &msg);
949 OptionStability::Stable => {}
953 if matches.opt_present("h") || matches.opt_present("help") {
954 // Only show unstable options in --help if we *really* accept unstable
955 // options, which catches the case where we got `-Z unstable-options` on
956 // the stable channel of Rust which was accidentally allowed
958 usage(matches.opt_present("verbose"),
959 has_z_unstable_options && really_allows_unstable_options);
963 // Don't handle -W help here, because we might first load plugins.
965 let r = matches.opt_strs("Z");
966 if r.iter().any(|x| *x == "help") {
967 describe_debug_flags();
971 let cg_flags = matches.opt_strs("C");
972 if cg_flags.iter().any(|x| *x == "help") {
973 describe_codegen_flags();
977 if cg_flags.contains(&"passes=list".to_string()) {
979 ::llvm::LLVMRustPrintPasses();
984 if matches.opt_present("version") {
985 version("rustc", &matches);
992 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
994 Input::File(ref ifile) => {
995 parse::parse_crate_attrs_from_file(ifile, Vec::new(), &sess.parse_sess)
997 Input::Str { ref name, ref input } => {
998 parse::parse_crate_attrs_from_source_str(name.clone(),
1006 /// Run a procedure which will detect panics in the compiler and print nicer
1007 /// error messages rather than just failing the test.
1009 /// The diagnostic emitter yielded to the procedure should be used for reporting
1010 /// errors of the compiler.
1011 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
1012 const STACK_SIZE: usize = 8 * 1024 * 1024; // 8MB
1014 struct Sink(Arc<Mutex<Vec<u8>>>);
1015 impl Write for Sink {
1016 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1017 Write::write(&mut *self.0.lock().unwrap(), data)
1019 fn flush(&mut self) -> io::Result<()> {
1024 let data = Arc::new(Mutex::new(Vec::new()));
1025 let err = Sink(data.clone());
1027 let mut cfg = thread::Builder::new().name("rustc".to_string());
1029 // FIXME: Hacks on hacks. If the env is trying to override the stack size
1030 // then *don't* set it explicitly.
1031 if env::var_os("RUST_MIN_STACK").is_none() {
1032 cfg = cfg.stack_size(STACK_SIZE);
1035 let thread = cfg.spawn(move || {
1036 io::set_panic(box err);
1040 if let Err(value) = thread.unwrap().join() {
1041 // Thread panicked without emitting a fatal diagnostic
1042 if !value.is::<errors::FatalError>() {
1043 let mut emitter = errors::emitter::BasicEmitter::stderr(errors::ColorConfig::Auto);
1045 // a .span_bug or .bug call has already printed what
1046 // it wants to print.
1047 if !value.is::<errors::ExplicitBug>() {
1048 emitter.emit(None, "unexpected panic", None, errors::Level::Bug);
1051 let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1052 format!("we would appreciate a bug report: {}", BUG_REPORT_URL)];
1054 emitter.emit(None, ¬e[..], None, errors::Level::Note)
1056 if let None = env::var_os("RUST_BACKTRACE") {
1058 "run with `RUST_BACKTRACE=1` for a backtrace",
1060 errors::Level::Note);
1063 println!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
1070 fn exit_on_err() -> ! {
1071 // Panic so the process returns a failure code, but don't pollute the
1072 // output with some unnecessary panic messages, we've already
1073 // printed everything that we needed to.
1074 io::set_panic(box io::sink());
1078 pub fn diagnostics_registry() -> diagnostics::registry::Registry {
1079 use syntax::diagnostics::registry::Registry;
1081 let mut all_errors = Vec::new();
1082 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1083 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1084 all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
1085 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1086 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1087 all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
1089 Registry::new(&all_errors)
1093 let result = run(env::args().collect());
1094 process::exit(result as i32);