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)]
34 #![feature(unboxed_closures)]
39 extern crate graphviz;
42 extern crate rustc_back;
43 extern crate rustc_borrowck;
44 extern crate rustc_const_eval;
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;
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_trans::back::link;
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::codemap::{CodeMap, FileLoader, RealFileLoader};
99 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
100 use syntax::parse::{self, PResult};
101 use syntax_pos::MultiSpan;
102 use errors::emitter::Emitter;
103 use errors::snippet::FormatMode;
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,
146 FormatMode::EnvironmentSelected);
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 pub fn run_compiler<'a>(args: &[String],
161 callbacks: &mut CompilerCalls<'a>)
162 -> (CompileResult, Option<Session>) {
163 run_compiler_with_file_loader(args, callbacks, box RealFileLoader)
166 // Parse args and run the compiler. This is the primary entry point for rustc.
167 // See comments on CompilerCalls below for details about the callbacks argument.
168 // The FileLoader provides a way to load files from sources other than the file system.
169 pub fn run_compiler_with_file_loader<'a, L>(args: &[String],
170 callbacks: &mut CompilerCalls<'a>,
172 -> (CompileResult, Option<Session>)
173 where L: FileLoader + 'static {
174 macro_rules! do_or_return {($expr: expr, $sess: expr) => {
176 Compilation::Stop => return (Ok(()), $sess),
177 Compilation::Continue => {}
181 let matches = match handle_options(args) {
182 Some(matches) => matches,
183 None => return (Ok(()), None),
186 let sopts = config::build_session_options(&matches);
188 if sopts.debugging_opts.debug_llvm {
189 unsafe { llvm::LLVMSetDebug(1); }
192 let descriptions = diagnostics_registry();
194 do_or_return!(callbacks.early_callback(&matches,
200 let (odir, ofile) = make_output(&matches);
201 let (input, input_file_path) = match make_input(&matches.free) {
202 Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
203 None => match callbacks.no_input(&matches, &sopts, &odir, &ofile, &descriptions) {
204 Some((input, input_file_path)) => (input, input_file_path),
205 None => return (Ok(()), None),
209 let dep_graph = DepGraph::new(sopts.build_dep_graph());
210 let cstore = Rc::new(CStore::new(&dep_graph));
211 let codemap = Rc::new(CodeMap::with_file_loader(loader));
212 let sess = session::build_session_with_codemap(sopts,
218 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
219 let mut cfg = config::build_configuration(&sess);
220 target_features::add_configuration(&mut cfg, &sess);
222 do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile), Some(sess));
224 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
225 let control = callbacks.build_controller(&sess, &matches);
226 (driver::compile_input(&sess, &cstore, cfg, &input, &odir, &ofile,
227 Some(plugins), &control),
231 // Extract output directory and file from matches.
232 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
233 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
234 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
238 // Extract input (string or file and optional path) from matches.
239 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
240 if free_matches.len() == 1 {
241 let ifile = &free_matches[0][..];
243 let mut src = String::new();
244 io::stdin().read_to_string(&mut src).unwrap();
245 Some((Input::Str { name: driver::anon_src(), input: src },
248 Some((Input::File(PathBuf::from(ifile)),
249 Some(PathBuf::from(ifile))))
256 fn parse_pretty(sess: &Session,
257 matches: &getopts::Matches)
258 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
259 let pretty = if sess.opts.debugging_opts.unstable_options {
260 matches.opt_default("pretty", "normal").map(|a| {
261 // stable pretty-print variants only
262 pretty::parse_pretty(sess, &a, false)
267 if pretty.is_none() && sess.unstable_options() {
268 matches.opt_str("unpretty").map(|a| {
269 // extended with unstable pretty-print variants
270 pretty::parse_pretty(sess, &a, true)
277 // Whether to stop or continue compilation.
278 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
279 pub enum Compilation {
285 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
287 Compilation::Stop => Compilation::Stop,
288 Compilation::Continue => next(),
293 // A trait for customising the compilation process. Offers a number of hooks for
294 // executing custom code or customising input.
295 pub trait CompilerCalls<'a> {
296 // Hook for a callback early in the process of handling arguments. This will
297 // be called straight after options have been parsed but before anything
298 // else (e.g., selecting input and output).
299 fn early_callback(&mut self,
300 _: &getopts::Matches,
302 _: &errors::registry::Registry,
305 Compilation::Continue
308 // Hook for a callback late in the process of handling arguments. This will
309 // be called just before actual compilation starts (and before build_controller
310 // is called), after all arguments etc. have been completely handled.
311 fn late_callback(&mut self,
312 _: &getopts::Matches,
318 Compilation::Continue
321 // Called after we extract the input from the arguments. Gives the implementer
322 // an opportunity to change the inputs or to add some custom input handling.
323 // The default behaviour is to simply pass through the inputs.
324 fn some_input(&mut self,
326 input_path: Option<PathBuf>)
327 -> (Input, Option<PathBuf>) {
331 // Called after we extract the input from the arguments if there is no valid
332 // input. Gives the implementer an opportunity to supply alternate input (by
333 // returning a Some value) or to add custom behaviour for this error such as
334 // emitting error messages. Returning None will cause compilation to stop
336 fn no_input(&mut self,
337 _: &getopts::Matches,
341 _: &errors::registry::Registry)
342 -> Option<(Input, Option<PathBuf>)> {
346 // Create a CompilController struct for controlling the behaviour of
348 fn build_controller(&mut self, &Session, &getopts::Matches) -> CompileController<'a>;
351 // CompilerCalls instance for a regular rustc build.
352 #[derive(Copy, Clone)]
353 pub struct RustcDefaultCalls;
355 fn handle_explain(code: &str,
356 descriptions: &errors::registry::Registry,
357 output: ErrorOutputType) {
358 let normalised = if code.starts_with("E") {
361 format!("E{0:0>4}", code)
363 match descriptions.find_description(&normalised) {
364 Some(ref description) => {
365 // Slice off the leading newline and print.
366 print!("{}", &(&description[1..]).split("\n").map(|x| {
367 format!("{}\n", if x.starts_with("```") {
372 }).collect::<String>());
375 early_error(output, &format!("no extended information for {}", code));
380 fn check_cfg(sopts: &config::Options,
381 output: ErrorOutputType) {
382 let emitter: Box<Emitter> = match output {
383 config::ErrorOutputType::HumanReadable(color_config) => {
384 Box::new(errors::emitter::EmitterWriter::stderr(color_config,
387 FormatMode::EnvironmentSelected))
389 config::ErrorOutputType::Json => Box::new(json::JsonEmitter::basic()),
391 let handler = errors::Handler::with_emitter(true, false, emitter);
393 let mut saw_invalid_predicate = false;
394 for item in sopts.cfg.iter() {
396 ast::MetaItemKind::List(ref pred, _) => {
397 saw_invalid_predicate = true;
398 handler.emit(&MultiSpan::new(),
399 &format!("invalid predicate in --cfg command line argument: `{}`",
401 errors::Level::Fatal);
407 if saw_invalid_predicate {
408 panic!(errors::FatalError);
412 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
413 fn early_callback(&mut self,
414 matches: &getopts::Matches,
415 sopts: &config::Options,
416 descriptions: &errors::registry::Registry,
417 output: ErrorOutputType)
419 if let Some(ref code) = matches.opt_str("explain") {
420 handle_explain(code, descriptions, output);
421 return Compilation::Stop;
424 check_cfg(sopts, output);
425 Compilation::Continue
428 fn no_input(&mut self,
429 matches: &getopts::Matches,
430 sopts: &config::Options,
431 odir: &Option<PathBuf>,
432 ofile: &Option<PathBuf>,
433 descriptions: &errors::registry::Registry)
434 -> Option<(Input, Option<PathBuf>)> {
435 match matches.free.len() {
437 if sopts.describe_lints {
438 let mut ls = lint::LintStore::new();
439 rustc_lint::register_builtins(&mut ls, None);
440 describe_lints(&ls, false);
443 let dep_graph = DepGraph::new(sopts.build_dep_graph());
444 let cstore = Rc::new(CStore::new(&dep_graph));
445 let sess = build_session(sopts.clone(),
448 descriptions.clone(),
450 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
451 let should_stop = RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
452 if should_stop == Compilation::Stop {
455 early_error(sopts.error_format, "no input filename given");
457 1 => panic!("make_input should have provided valid inputs"),
458 _ => early_error(sopts.error_format, "multiple input filenames provided"),
464 fn late_callback(&mut self,
465 matches: &getopts::Matches,
468 odir: &Option<PathBuf>,
469 ofile: &Option<PathBuf>)
471 RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
472 .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input))
475 fn build_controller(&mut self,
477 matches: &getopts::Matches)
478 -> CompileController<'a> {
479 let mut control = CompileController::basic();
481 if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
482 if ppm.needs_ast_map(&opt_uii) {
483 control.after_hir_lowering.stop = Compilation::Stop;
485 control.after_parse.callback = box move |state| {
486 state.krate = Some(pretty::fold_crate(state.krate.take().unwrap(), ppm));
488 control.after_hir_lowering.callback = box move |state| {
489 pretty::print_after_hir_lowering(state.session,
490 state.ast_map.unwrap(),
491 state.analysis.unwrap(),
492 state.resolutions.unwrap(),
494 &state.expanded_crate.take().unwrap(),
495 state.crate_name.unwrap(),
497 state.arenas.unwrap(),
502 control.after_parse.stop = Compilation::Stop;
504 control.after_parse.callback = box move |state| {
505 let krate = pretty::fold_crate(state.krate.take().unwrap(), ppm);
506 pretty::print_after_parsing(state.session,
517 if sess.opts.parse_only || sess.opts.debugging_opts.show_span.is_some() ||
518 sess.opts.debugging_opts.ast_json_noexpand {
519 control.after_parse.stop = Compilation::Stop;
522 if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
523 control.after_hir_lowering.stop = Compilation::Stop;
526 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe) {
527 control.after_llvm.stop = Compilation::Stop;
530 if save_analysis(sess) {
531 control.after_analysis.callback = box |state| {
532 time(state.session.time_passes(), "save analysis", || {
533 save::process_crate(state.tcx.unwrap(),
534 state.expanded_crate.unwrap(),
535 state.analysis.unwrap(),
536 state.crate_name.unwrap(),
538 save_analysis_format(state.session))
541 control.after_analysis.run_callback_on_error = true;
542 control.make_glob_map = resolve::MakeGlobMap::Yes;
549 fn save_analysis(sess: &Session) -> bool {
550 sess.opts.debugging_opts.save_analysis ||
551 sess.opts.debugging_opts.save_analysis_csv
554 fn save_analysis_format(sess: &Session) -> save::Format {
555 if sess.opts.debugging_opts.save_analysis {
557 } else if sess.opts.debugging_opts.save_analysis_csv {
564 impl RustcDefaultCalls {
565 pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation {
566 let r = matches.opt_strs("Z");
567 if r.contains(&("ls".to_string())) {
569 &Input::File(ref ifile) => {
570 let path = &(*ifile);
571 let mut v = Vec::new();
572 loader::list_file_metadata(&sess.target.target, path, &mut v)
574 println!("{}", String::from_utf8(v).unwrap());
576 &Input::Str { .. } => {
577 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
580 return Compilation::Stop;
583 return Compilation::Continue;
587 fn print_crate_info(sess: &Session,
588 input: Option<&Input>,
589 odir: &Option<PathBuf>,
590 ofile: &Option<PathBuf>)
592 if sess.opts.prints.is_empty() {
593 return Compilation::Continue;
596 let attrs = match input {
599 let result = parse_crate_attrs(sess, input);
601 Ok(attrs) => Some(attrs),
602 Err(mut parse_error) => {
604 return Compilation::Stop;
609 for req in &sess.opts.prints {
611 PrintRequest::TargetList => {
612 let mut targets = rustc_back::target::TARGETS.to_vec();
614 println!("{}", targets.join("\n"));
616 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
617 PrintRequest::FileNames |
618 PrintRequest::CrateName => {
619 let input = match input {
620 Some(input) => input,
621 None => early_error(ErrorOutputType::default(), "no input file provided"),
623 let attrs = attrs.as_ref().unwrap();
624 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
625 let id = link::find_crate_name(Some(sess), attrs, input);
626 if *req == PrintRequest::CrateName {
630 let crate_types = driver::collect_crate_types(sess, attrs);
631 for &style in &crate_types {
632 let fname = link::filename_for_input(sess, style, &id, &t_outputs);
639 PrintRequest::Cfg => {
640 let mut cfg = config::build_configuration(&sess);
641 target_features::add_configuration(&mut cfg, &sess);
643 let allow_unstable_cfg = match get_unstable_features_setting() {
644 UnstableFeatures::Disallow => false,
649 if !allow_unstable_cfg && GatedCfg::gate(&*cfg).is_some() {
653 ast::MetaItemKind::Word(ref word) => println!("{}", word),
654 ast::MetaItemKind::NameValue(ref name, ref value) => {
655 println!("{}=\"{}\"", name, match value.node {
656 ast::LitKind::Str(ref s, _) => s,
660 // Right now there are not and should not be any
661 // MetaItemKind::List items in the configuration returned by
662 // `build_configuration`.
663 ast::MetaItemKind::List(..) => {
664 panic!("MetaItemKind::List encountered in default cfg")
671 return Compilation::Stop;
675 /// Returns a version string such as "0.12.0-dev".
676 pub fn release_str() -> Option<&'static str> {
677 option_env!("CFG_RELEASE")
680 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
681 pub fn commit_hash_str() -> Option<&'static str> {
682 option_env!("CFG_VER_HASH")
685 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
686 pub fn commit_date_str() -> Option<&'static str> {
687 option_env!("CFG_VER_DATE")
690 /// Prints version information
691 pub fn version(binary: &str, matches: &getopts::Matches) {
692 let verbose = matches.opt_present("verbose");
696 option_env!("CFG_VERSION").unwrap_or("unknown version"));
698 fn unw(x: Option<&str>) -> &str {
699 x.unwrap_or("unknown")
701 println!("binary: {}", binary);
702 println!("commit-hash: {}", unw(commit_hash_str()));
703 println!("commit-date: {}", unw(commit_date_str()));
704 println!("host: {}", config::host_triple());
705 println!("release: {}", unw(release_str()));
709 fn usage(verbose: bool, include_unstable_options: bool) {
710 let groups = if verbose {
711 config::rustc_optgroups()
713 config::rustc_short_optgroups()
715 let groups: Vec<_> = groups.into_iter()
716 .filter(|x| include_unstable_options || x.is_stable())
717 .map(|x| x.opt_group)
719 let message = format!("Usage: rustc [OPTIONS] INPUT");
720 let extra_help = if verbose {
723 "\n --help -v Print the full set of options rustc accepts"
725 println!("{}\nAdditional help:
726 -C help Print codegen options
728 Print 'lint' options and default settings
729 -Z help Print internal \
730 options for debugging rustc{}\n",
731 getopts::usage(&message, &groups),
735 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
737 Available lint options:
738 -W <foo> Warn about <foo>
742 -F <foo> Forbid <foo> \
743 (deny, and deny all overrides)
747 fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
748 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
749 lints.sort_by(|x: &&Lint, y: &&Lint| {
750 match x.default_level.cmp(&y.default_level) {
751 // The sort doesn't case-fold but it's doubtful we care.
752 Equal => x.name.cmp(y.name),
759 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
760 -> Vec<(&'static str, Vec<lint::LintId>)> {
761 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
762 lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
763 &(y, _): &(&'static str, Vec<lint::LintId>)| {
769 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
772 .partition(|&(_, p)| p);
773 let plugin = sort_lints(plugin);
774 let builtin = sort_lints(builtin);
776 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
779 .partition(|&(_, _, p)| p);
780 let plugin_groups = sort_lint_groups(plugin_groups);
781 let builtin_groups = sort_lint_groups(builtin_groups);
783 let max_name_len = plugin.iter()
785 .map(|&s| s.name.chars().count())
788 let padded = |x: &str| {
789 let mut s = repeat(" ")
790 .take(max_name_len - x.chars().count())
791 .collect::<String>();
796 println!("Lint checks provided by rustc:\n");
797 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
798 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
800 let print_lints = |lints: Vec<&Lint>| {
802 let name = lint.name_lower().replace("_", "-");
803 println!(" {} {:7.7} {}",
805 lint.default_level.as_str(),
811 print_lints(builtin);
815 let max_name_len = max("warnings".len(),
817 .chain(&builtin_groups)
818 .map(|&(s, _)| s.chars().count())
822 let padded = |x: &str| {
823 let mut s = repeat(" ")
824 .take(max_name_len - x.chars().count())
825 .collect::<String>();
830 println!("Lint groups provided by rustc:\n");
831 println!(" {} {}", padded("name"), "sub-lints");
832 println!(" {} {}", padded("----"), "---------");
833 println!(" {} {}", padded("warnings"), "all built-in lints");
835 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
836 for (name, to) in lints {
837 let name = name.to_lowercase().replace("_", "-");
838 let desc = to.into_iter()
839 .map(|x| x.as_str().replace("_", "-"))
840 .collect::<Vec<String>>()
842 println!(" {} {}", padded(&name[..]), desc);
847 print_lint_groups(builtin_groups);
849 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
850 (false, 0, _) | (false, _, 0) => {
851 println!("Compiler plugins can provide additional lints and lint groups. To see a \
852 listing of these, re-run `rustc -W help` with a crate filename.");
854 (false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
855 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
858 println!("Lint checks provided by plugins loaded by this crate:\n");
862 println!("Lint groups provided by plugins loaded by this crate:\n");
863 print_lint_groups(plugin_groups);
869 fn describe_debug_flags() {
870 println!("\nAvailable debug options:\n");
871 print_flag_list("-Z", config::DB_OPTIONS);
874 fn describe_codegen_flags() {
875 println!("\nAvailable codegen options:\n");
876 print_flag_list("-C", config::CG_OPTIONS);
879 fn print_flag_list<T>(cmdline_opt: &str,
880 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
881 let max_len = flag_list.iter()
882 .map(|&(name, _, opt_type_desc, _)| {
883 let extra_len = match opt_type_desc {
887 name.chars().count() + extra_len
892 for &(name, _, opt_type_desc, desc) in flag_list {
893 let (width, extra) = match opt_type_desc {
894 Some(..) => (max_len - 4, "=val"),
895 None => (max_len, ""),
897 println!(" {} {:>width$}{} -- {}",
899 name.replace("_", "-"),
906 /// Process command line options. Emits messages as appropriate. If compilation
907 /// should continue, returns a getopts::Matches object parsed from args,
908 /// otherwise returns None.
910 /// The compiler's handling of options is a little complication as it ties into
911 /// our stability story, and it's even *more* complicated by historical
912 /// accidents. The current intention of each compiler option is to have one of
915 /// 1. An option is stable and can be used everywhere.
916 /// 2. An option is unstable, but was historically allowed on the stable
918 /// 3. An option is unstable, and can only be used on nightly.
920 /// Like unstable library and language features, however, unstable options have
921 /// always required a form of "opt in" to indicate that you're using them. This
922 /// provides the easy ability to scan a code base to check to see if anything
923 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
925 /// All options behind `-Z` are considered unstable by default. Other top-level
926 /// options can also be considered unstable, and they were unlocked through the
927 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
928 /// instability in both cases, though.
930 /// So with all that in mind, the comments below have some more detail about the
931 /// contortions done here to get things to work out correctly.
932 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
933 // Throw away the first argument, the name of the binary
934 let args = &args[1..];
937 // user did not write `-v` nor `-Z unstable-options`, so do not
938 // include that extra information.
943 // Parse with *all* options defined in the compiler, we don't worry about
944 // option stability here we just want to parse as much as possible.
945 let all_groups: Vec<getopts::OptGroup> = config::rustc_optgroups()
947 .map(|x| x.opt_group)
949 let matches = match getopts::getopts(&args[..], &all_groups) {
951 Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
954 // For all options we just parsed, we check a few aspects:
956 // * If the option is stable, we're all good
957 // * If the option wasn't passed, we're all good
958 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
959 // ourselves), then we require the `-Z unstable-options` flag to unlock
960 // this option that was passed.
961 // * If we're a nightly compiler, then unstable options are now unlocked, so
963 // * Otherwise, if we're a truly unstable option then we generate an error
964 // (unstable option being used on stable)
965 // * If we're a historically stable-but-should-be-unstable option then we
966 // emit a warning that we're going to turn this into an error soon.
967 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
969 if matches.opt_present("h") || matches.opt_present("help") {
970 // Only show unstable options in --help if we *really* accept unstable
971 // options, which catches the case where we got `-Z unstable-options` on
972 // the stable channel of Rust which was accidentally allowed
974 usage(matches.opt_present("verbose"),
975 nightly_options::is_unstable_enabled(&matches));
979 // Don't handle -W help here, because we might first load plugins.
980 let r = matches.opt_strs("Z");
981 if r.iter().any(|x| *x == "help") {
982 describe_debug_flags();
986 let cg_flags = matches.opt_strs("C");
987 if cg_flags.iter().any(|x| *x == "help") {
988 describe_codegen_flags();
992 if cg_flags.contains(&"passes=list".to_string()) {
994 ::llvm::LLVMRustPrintPasses();
999 if matches.opt_present("version") {
1000 version("rustc", &matches);
1007 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1009 Input::File(ref ifile) => {
1010 parse::parse_crate_attrs_from_file(ifile, Vec::new(), &sess.parse_sess)
1012 Input::Str { ref name, ref input } => {
1013 parse::parse_crate_attrs_from_source_str(name.clone(),
1021 /// Run a procedure which will detect panics in the compiler and print nicer
1022 /// error messages rather than just failing the test.
1024 /// The diagnostic emitter yielded to the procedure should be used for reporting
1025 /// errors of the compiler.
1026 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
1027 const STACK_SIZE: usize = 8 * 1024 * 1024; // 8MB
1029 struct Sink(Arc<Mutex<Vec<u8>>>);
1030 impl Write for Sink {
1031 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1032 Write::write(&mut *self.0.lock().unwrap(), data)
1034 fn flush(&mut self) -> io::Result<()> {
1039 let data = Arc::new(Mutex::new(Vec::new()));
1040 let err = Sink(data.clone());
1042 let mut cfg = thread::Builder::new().name("rustc".to_string());
1044 // FIXME: Hacks on hacks. If the env is trying to override the stack size
1045 // then *don't* set it explicitly.
1046 if env::var_os("RUST_MIN_STACK").is_none() {
1047 cfg = cfg.stack_size(STACK_SIZE);
1050 let thread = cfg.spawn(move || {
1051 io::set_panic(box err);
1055 if let Err(value) = thread.unwrap().join() {
1056 // Thread panicked without emitting a fatal diagnostic
1057 if !value.is::<errors::FatalError>() {
1059 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
1062 FormatMode::EnvironmentSelected));
1063 let handler = errors::Handler::with_emitter(true, false, emitter);
1065 // a .span_bug or .bug call has already printed what
1066 // it wants to print.
1067 if !value.is::<errors::ExplicitBug>() {
1068 handler.emit(&MultiSpan::new(),
1070 errors::Level::Bug);
1073 let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1074 format!("we would appreciate a bug report: {}", BUG_REPORT_URL)];
1076 handler.emit(&MultiSpan::new(),
1078 errors::Level::Note);
1080 if match env::var_os("RUST_BACKTRACE") {
1081 Some(val) => &val != "0",
1084 handler.emit(&MultiSpan::new(),
1085 "run with `RUST_BACKTRACE=1` for a backtrace",
1086 errors::Level::Note);
1089 println!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
1096 fn exit_on_err() -> ! {
1097 // Panic so the process returns a failure code, but don't pollute the
1098 // output with some unnecessary panic messages, we've already
1099 // printed everything that we needed to.
1100 io::set_panic(box io::sink());
1104 pub fn diagnostics_registry() -> errors::registry::Registry {
1105 use errors::registry::Registry;
1107 let mut all_errors = Vec::new();
1108 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1109 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1110 all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
1111 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1112 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1113 all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
1114 all_errors.extend_from_slice(&rustc_const_eval::DIAGNOSTICS);
1116 Registry::new(&all_errors)
1120 let result = run(env::args().collect());
1121 process::exit(result as i32);