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/")]
25 #![feature(box_syntax)]
28 #![feature(rustc_diagnostic_macros)]
29 #![feature(rustc_private)]
30 #![feature(set_stdio)]
31 #![feature(staged_api)]
36 extern crate graphviz;
39 extern crate rustc_back;
40 extern crate rustc_borrowck;
41 extern crate rustc_front;
42 extern crate rustc_lint;
43 extern crate rustc_plugin;
44 extern crate rustc_privacy;
45 extern crate rustc_metadata;
46 extern crate rustc_mir;
47 extern crate rustc_resolve;
48 extern crate rustc_trans;
49 extern crate rustc_typeck;
50 extern crate serialize;
51 extern crate rustc_llvm as llvm;
56 extern crate syntax_ext;
58 use driver::CompileController;
59 use pretty::{PpMode, UserIdentifiedItem};
61 use rustc_resolve as resolve;
62 use rustc_trans::back::link;
63 use rustc_trans::save;
64 use rustc::session::{config, Session, build_session};
65 use rustc::session::config::{Input, PrintRequest, OutputType, ErrorOutputType};
66 use rustc::middle::cstore::CrateStore;
67 use rustc::lint::Lint;
69 use rustc_metadata::loader;
70 use rustc_metadata::cstore::CStore;
71 use rustc::util::common::time;
74 use std::cmp::Ordering::Equal;
75 use std::default::Default;
77 use std::io::{self, Read, Write};
78 use std::iter::repeat;
79 use std::path::PathBuf;
83 use std::sync::{Arc, Mutex};
86 use rustc::session::early_error;
91 use syntax::errors::emitter::Emitter;
92 use syntax::diagnostics;
93 use syntax::parse::token;
100 pub mod target_features;
103 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
106 pub fn run(args: Vec<String>) -> isize {
107 monitor(move || run_compiler(&args, &mut RustcDefaultCalls));
111 // Parse args and run the compiler. This is the primary entry point for rustc.
112 // See comments on CompilerCalls below for details about the callbacks argument.
113 pub fn run_compiler<'a>(args: &[String], callbacks: &mut CompilerCalls<'a>) {
114 macro_rules! do_or_return {($expr: expr) => {
116 Compilation::Stop => return,
117 Compilation::Continue => {}
121 let matches = match handle_options(args.to_vec()) {
122 Some(matches) => matches,
126 let sopts = config::build_session_options(&matches);
128 let descriptions = diagnostics_registry();
130 do_or_return!(callbacks.early_callback(&matches, &descriptions, sopts.output));
132 let (odir, ofile) = make_output(&matches);
133 let (input, input_file_path) = match make_input(&matches.free) {
134 Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
135 None => match callbacks.no_input(&matches, &sopts, &odir, &ofile, &descriptions) {
136 Some((input, input_file_path)) => (input, input_file_path),
141 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
142 let sess = build_session(sopts, input_file_path, descriptions,
144 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
145 let mut cfg = config::build_configuration(&sess);
146 target_features::add_configuration(&mut cfg, &sess);
148 do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile));
150 // It is somewhat unfortunate that this is hardwired in - this is forced by
151 // the fact that pretty_print_input requires the session by value.
152 let pretty = callbacks.parse_pretty(&sess, &matches);
154 Some((ppm, opt_uii)) => {
155 pretty::pretty_print_input(sess, &cstore, cfg, &input, ppm, opt_uii, ofile);
163 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
164 let control = callbacks.build_controller(&sess);
165 driver::compile_input(sess, &cstore, cfg, &input, &odir, &ofile,
166 Some(plugins), control);
169 // Extract output directory and file from matches.
170 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
171 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
172 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
176 // Extract input (string or file and optional path) from matches.
177 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
178 if free_matches.len() == 1 {
179 let ifile = &free_matches[0][..];
181 let mut src = String::new();
182 io::stdin().read_to_string(&mut src).unwrap();
183 Some((Input::Str(src), None))
185 Some((Input::File(PathBuf::from(ifile)),
186 Some(PathBuf::from(ifile))))
193 // Whether to stop or continue compilation.
194 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
195 pub enum Compilation {
201 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
203 Compilation::Stop => Compilation::Stop,
204 Compilation::Continue => next(),
209 // A trait for customising the compilation process. Offers a number of hooks for
210 // executing custom code or customising input.
211 pub trait CompilerCalls<'a> {
212 // Hook for a callback early in the process of handling arguments. This will
213 // be called straight after options have been parsed but before anything
214 // else (e.g., selecting input and output).
215 fn early_callback(&mut self,
216 _: &getopts::Matches,
217 _: &diagnostics::registry::Registry,
220 Compilation::Continue
223 // Hook for a callback late in the process of handling arguments. This will
224 // be called just before actual compilation starts (and before build_controller
225 // is called), after all arguments etc. have been completely handled.
226 fn late_callback(&mut self,
227 _: &getopts::Matches,
233 Compilation::Continue
236 // Called after we extract the input from the arguments. Gives the implementer
237 // an opportunity to change the inputs or to add some custom input handling.
238 // The default behaviour is to simply pass through the inputs.
239 fn some_input(&mut self,
241 input_path: Option<PathBuf>)
242 -> (Input, Option<PathBuf>) {
246 // Called after we extract the input from the arguments if there is no valid
247 // input. Gives the implementer an opportunity to supply alternate input (by
248 // returning a Some value) or to add custom behaviour for this error such as
249 // emitting error messages. Returning None will cause compilation to stop
251 fn no_input(&mut self,
252 _: &getopts::Matches,
256 _: &diagnostics::registry::Registry)
257 -> Option<(Input, Option<PathBuf>)> {
261 // Parse pretty printing information from the arguments. The implementer can
262 // choose to ignore this (the default will return None) which will skip pretty
263 // printing. If you do want to pretty print, it is recommended to use the
264 // implementation of this method from RustcDefaultCalls.
265 // FIXME, this is a terrible bit of API. Parsing of pretty printing stuff
266 // should be done as part of the framework and the implementor should customise
267 // handling of it. However, that is not possible atm because pretty printing
268 // essentially goes off and takes another path through the compiler which
269 // means the session is either moved or not depending on what parse_pretty
270 // returns (we could fix this by cloning, but it's another hack). The proper
271 // solution is to handle pretty printing as if it were a compiler extension,
272 // extending CompileController to make this work (see for example the treatment
273 // of save-analysis in RustcDefaultCalls::build_controller).
274 fn parse_pretty(&mut self,
276 _matches: &getopts::Matches)
277 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
281 // Create a CompilController struct for controlling the behaviour of
283 fn build_controller(&mut self, &Session) -> CompileController<'a>;
286 // CompilerCalls instance for a regular rustc build.
287 #[derive(Copy, Clone)]
288 pub struct RustcDefaultCalls;
290 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
291 fn early_callback(&mut self,
292 matches: &getopts::Matches,
293 descriptions: &diagnostics::registry::Registry,
294 output: ErrorOutputType)
296 match matches.opt_str("explain") {
298 let normalised = if !code.starts_with("E") {
299 format!("E{0:0>4}", code)
303 match descriptions.find_description(&normalised) {
304 Some(ref description) => {
305 // Slice off the leading newline and print.
306 print!("{}", &description[1..]);
309 early_error(output, &format!("no extended information for {}", code));
312 return Compilation::Stop;
317 return Compilation::Continue;
320 fn no_input(&mut self,
321 matches: &getopts::Matches,
322 sopts: &config::Options,
323 odir: &Option<PathBuf>,
324 ofile: &Option<PathBuf>,
325 descriptions: &diagnostics::registry::Registry)
326 -> Option<(Input, Option<PathBuf>)> {
327 match matches.free.len() {
329 if sopts.describe_lints {
330 let mut ls = lint::LintStore::new();
331 rustc_lint::register_builtins(&mut ls, None);
332 describe_lints(&ls, false);
335 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
336 let sess = build_session(sopts.clone(), None, descriptions.clone(),
338 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
339 let should_stop = RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
340 if should_stop == Compilation::Stop {
343 early_error(sopts.output, "no input filename given");
345 1 => panic!("make_input should have provided valid inputs"),
346 _ => early_error(sopts.output, "multiple input filenames provided"),
352 fn parse_pretty(&mut self,
354 matches: &getopts::Matches)
355 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
356 let pretty = if sess.opts.debugging_opts.unstable_options {
357 matches.opt_default("pretty", "normal").map(|a| {
358 // stable pretty-print variants only
359 pretty::parse_pretty(sess, &a, false)
364 if pretty.is_none() && sess.unstable_options() {
365 matches.opt_str("unpretty").map(|a| {
366 // extended with unstable pretty-print variants
367 pretty::parse_pretty(sess, &a, true)
374 fn late_callback(&mut self,
375 matches: &getopts::Matches,
378 odir: &Option<PathBuf>,
379 ofile: &Option<PathBuf>)
381 RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
382 .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input))
385 fn build_controller(&mut self, sess: &Session) -> CompileController<'a> {
386 let mut control = CompileController::basic();
388 if sess.opts.parse_only || sess.opts.debugging_opts.show_span.is_some() ||
389 sess.opts.debugging_opts.ast_json_noexpand {
390 control.after_parse.stop = Compilation::Stop;
393 if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
394 control.after_write_deps.stop = Compilation::Stop;
397 if sess.opts.no_trans {
398 control.after_analysis.stop = Compilation::Stop;
401 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe) {
402 control.after_llvm.stop = Compilation::Stop;
405 if sess.opts.debugging_opts.save_analysis {
406 control.after_analysis.callback = box |state| {
407 time(state.session.time_passes(), "save analysis", || {
408 save::process_crate(state.tcx.unwrap(),
410 state.krate.unwrap(),
411 state.analysis.unwrap(),
412 state.crate_name.unwrap(),
416 control.make_glob_map = resolve::MakeGlobMap::Yes;
423 impl RustcDefaultCalls {
424 pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation {
425 let r = matches.opt_strs("Z");
426 if r.contains(&("ls".to_string())) {
428 &Input::File(ref ifile) => {
429 let path = &(*ifile);
430 let mut v = Vec::new();
431 loader::list_file_metadata(&sess.target.target, path, &mut v)
433 println!("{}", String::from_utf8(v).unwrap());
436 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
439 return Compilation::Stop;
442 return Compilation::Continue;
446 fn print_crate_info(sess: &Session,
447 input: Option<&Input>,
448 odir: &Option<PathBuf>,
449 ofile: &Option<PathBuf>)
451 if sess.opts.prints.is_empty() {
452 return Compilation::Continue;
455 let attrs = input.map(|input| parse_crate_attrs(sess, input));
456 for req in &sess.opts.prints {
458 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
459 PrintRequest::FileNames |
460 PrintRequest::CrateName => {
461 let input = match input {
462 Some(input) => input,
463 None => early_error(ErrorOutputType::default(), "no input file provided"),
465 let attrs = attrs.as_ref().unwrap();
466 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
467 let id = link::find_crate_name(Some(sess), attrs, input);
468 if *req == PrintRequest::CrateName {
472 let crate_types = driver::collect_crate_types(sess, attrs);
473 let metadata = driver::collect_crate_metadata(sess, attrs);
474 *sess.crate_metadata.borrow_mut() = metadata;
475 for &style in &crate_types {
476 let fname = link::filename_for_input(sess, style, &id, &t_outputs);
485 return Compilation::Stop;
489 /// Returns a version string such as "0.12.0-dev".
490 pub fn release_str() -> Option<&'static str> {
491 option_env!("CFG_RELEASE")
494 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
495 pub fn commit_hash_str() -> Option<&'static str> {
496 option_env!("CFG_VER_HASH")
499 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
500 pub fn commit_date_str() -> Option<&'static str> {
501 option_env!("CFG_VER_DATE")
504 /// Prints version information
505 pub fn version(binary: &str, matches: &getopts::Matches) {
506 let verbose = matches.opt_present("verbose");
510 option_env!("CFG_VERSION").unwrap_or("unknown version"));
512 fn unw(x: Option<&str>) -> &str {
513 x.unwrap_or("unknown")
515 println!("binary: {}", binary);
516 println!("commit-hash: {}", unw(commit_hash_str()));
517 println!("commit-date: {}", unw(commit_date_str()));
518 println!("host: {}", config::host_triple());
519 println!("release: {}", unw(release_str()));
523 fn usage(verbose: bool, include_unstable_options: bool) {
524 let groups = if verbose {
525 config::rustc_optgroups()
527 config::rustc_short_optgroups()
529 let groups: Vec<_> = groups.into_iter()
530 .filter(|x| include_unstable_options || x.is_stable())
531 .map(|x| x.opt_group)
533 let message = format!("Usage: rustc [OPTIONS] INPUT");
534 let extra_help = if verbose {
537 "\n --help -v Print the full set of options rustc accepts"
539 println!("{}\nAdditional help:
540 -C help Print codegen options
542 Print 'lint' options and default settings
543 -Z help Print internal \
544 options for debugging rustc{}\n",
545 getopts::usage(&message, &groups),
549 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
551 Available lint options:
552 -W <foo> Warn about <foo>
556 -F <foo> Forbid <foo> \
557 (deny, and deny all overrides)
561 fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
562 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
563 lints.sort_by(|x: &&Lint, y: &&Lint| {
564 match x.default_level.cmp(&y.default_level) {
565 // The sort doesn't case-fold but it's doubtful we care.
566 Equal => x.name.cmp(y.name),
573 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
574 -> Vec<(&'static str, Vec<lint::LintId>)> {
575 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
576 lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
577 &(y, _): &(&'static str, Vec<lint::LintId>)| {
583 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
586 .partition(|&(_, p)| p);
587 let plugin = sort_lints(plugin);
588 let builtin = sort_lints(builtin);
590 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
593 .partition(|&(_, _, p)| p);
594 let plugin_groups = sort_lint_groups(plugin_groups);
595 let builtin_groups = sort_lint_groups(builtin_groups);
597 let max_name_len = plugin.iter()
599 .map(|&s| s.name.chars().count())
602 let padded = |x: &str| {
603 let mut s = repeat(" ")
604 .take(max_name_len - x.chars().count())
605 .collect::<String>();
610 println!("Lint checks provided by rustc:\n");
611 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
612 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
614 let print_lints = |lints: Vec<&Lint>| {
616 let name = lint.name_lower().replace("_", "-");
617 println!(" {} {:7.7} {}",
619 lint.default_level.as_str(),
625 print_lints(builtin);
629 let max_name_len = max("warnings".len(),
631 .chain(&builtin_groups)
632 .map(|&(s, _)| s.chars().count())
636 let padded = |x: &str| {
637 let mut s = repeat(" ")
638 .take(max_name_len - x.chars().count())
639 .collect::<String>();
644 println!("Lint groups provided by rustc:\n");
645 println!(" {} {}", padded("name"), "sub-lints");
646 println!(" {} {}", padded("----"), "---------");
647 println!(" {} {}", padded("warnings"), "all built-in lints");
649 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
650 for (name, to) in lints {
651 let name = name.to_lowercase().replace("_", "-");
652 let desc = to.into_iter()
653 .map(|x| x.as_str().replace("_", "-"))
654 .collect::<Vec<String>>()
656 println!(" {} {}", padded(&name[..]), desc);
661 print_lint_groups(builtin_groups);
663 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
664 (false, 0, _) | (false, _, 0) => {
665 println!("Compiler plugins can provide additional lints and lint groups. To see a \
666 listing of these, re-run `rustc -W help` with a crate filename.");
668 (false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
669 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
672 println!("Lint checks provided by plugins loaded by this crate:\n");
676 println!("Lint groups provided by plugins loaded by this crate:\n");
677 print_lint_groups(plugin_groups);
683 fn describe_debug_flags() {
684 println!("\nAvailable debug options:\n");
685 print_flag_list("-Z", config::DB_OPTIONS);
688 fn describe_codegen_flags() {
689 println!("\nAvailable codegen options:\n");
690 print_flag_list("-C", config::CG_OPTIONS);
693 fn print_flag_list<T>(cmdline_opt: &str,
694 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
695 let max_len = flag_list.iter()
696 .map(|&(name, _, opt_type_desc, _)| {
697 let extra_len = match opt_type_desc {
701 name.chars().count() + extra_len
706 for &(name, _, opt_type_desc, desc) in flag_list {
707 let (width, extra) = match opt_type_desc {
708 Some(..) => (max_len - 4, "=val"),
709 None => (max_len, ""),
711 println!(" {} {:>width$}{} -- {}",
713 name.replace("_", "-"),
720 /// Process command line options. Emits messages as appropriate. If compilation
721 /// should continue, returns a getopts::Matches object parsed from args, otherwise
723 pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
724 // Throw away the first argument, the name of the binary
725 let _binary = args.remove(0);
728 // user did not write `-v` nor `-Z unstable-options`, so do not
729 // include that extra information.
734 fn allows_unstable_options(matches: &getopts::Matches) -> bool {
735 let r = matches.opt_strs("Z");
736 r.iter().any(|x| *x == "unstable-options")
739 fn parse_all_options(args: &Vec<String>) -> getopts::Matches {
740 let all_groups: Vec<getopts::OptGroup> = config::rustc_optgroups()
742 .map(|x| x.opt_group)
744 match getopts::getopts(&args[..], &all_groups) {
746 if !allows_unstable_options(&m) {
747 // If -Z unstable-options was not specified, verify that
748 // no unstable options were present.
749 for opt in config::rustc_optgroups().into_iter().filter(|x| !x.is_stable()) {
750 let opt_name = if !opt.opt_group.long_name.is_empty() {
751 &opt.opt_group.long_name
753 &opt.opt_group.short_name
755 if m.opt_present(opt_name) {
756 early_error(ErrorOutputType::default(),
757 &format!("use of unstable option '{}' requires -Z \
765 Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
769 // As a speed optimization, first try to parse the command-line using just
770 // the stable options.
771 let matches = match getopts::getopts(&args[..], &config::optgroups()) {
772 Ok(ref m) if allows_unstable_options(m) => {
773 // If -Z unstable-options was specified, redo parsing with the
774 // unstable options to ensure that unstable options are defined
775 // in the returned getopts::Matches.
776 parse_all_options(&args)
780 // redo option parsing, including unstable options this time,
781 // in anticipation that the mishandled option was one of the
783 parse_all_options(&args)
787 if matches.opt_present("h") || matches.opt_present("help") {
788 usage(matches.opt_present("verbose"),
789 allows_unstable_options(&matches));
793 // Don't handle -W help here, because we might first load plugins.
795 let r = matches.opt_strs("Z");
796 if r.iter().any(|x| *x == "help") {
797 describe_debug_flags();
801 let cg_flags = matches.opt_strs("C");
802 if cg_flags.iter().any(|x| *x == "help") {
803 describe_codegen_flags();
807 if cg_flags.contains(&"passes=list".to_string()) {
809 ::llvm::LLVMRustPrintPasses();
814 if matches.opt_present("version") {
815 version("rustc", &matches);
822 fn parse_crate_attrs(sess: &Session, input: &Input) -> Vec<ast::Attribute> {
823 let result = match *input {
824 Input::File(ref ifile) => {
825 parse::parse_crate_attrs_from_file(ifile, Vec::new(), &sess.parse_sess)
827 Input::Str(ref src) => {
828 parse::parse_crate_attrs_from_source_str(driver::anon_src().to_string(),
834 result.into_iter().collect()
837 /// Run a procedure which will detect panics in the compiler and print nicer
838 /// error messages rather than just failing the test.
840 /// The diagnostic emitter yielded to the procedure should be used for reporting
841 /// errors of the compiler.
842 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
843 const STACK_SIZE: usize = 8 * 1024 * 1024; // 8MB
845 struct Sink(Arc<Mutex<Vec<u8>>>);
846 impl Write for Sink {
847 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
848 Write::write(&mut *self.0.lock().unwrap(), data)
850 fn flush(&mut self) -> io::Result<()> {
855 let data = Arc::new(Mutex::new(Vec::new()));
856 let err = Sink(data.clone());
858 let mut cfg = thread::Builder::new().name("rustc".to_string());
860 // FIXME: Hacks on hacks. If the env is trying to override the stack size
861 // then *don't* set it explicitly.
862 if env::var_os("RUST_MIN_STACK").is_none() {
863 cfg = cfg.stack_size(STACK_SIZE);
866 match cfg.spawn(move || {
867 io::set_panic(box err);
876 // Thread panicked without emitting a fatal diagnostic
877 if !value.is::<errors::FatalError>() {
878 let mut emitter = errors::emitter::BasicEmitter::stderr(errors::ColorConfig::Auto);
880 // a .span_bug or .bug call has already printed what
881 // it wants to print.
882 if !value.is::<errors::ExplicitBug>() {
883 emitter.emit(None, "unexpected panic", None, errors::Level::Bug);
886 let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
887 format!("we would appreciate a bug report: {}", BUG_REPORT_URL)];
889 emitter.emit(None, ¬e[..], None, errors::Level::Note)
891 if let None = env::var_os("RUST_BACKTRACE") {
893 "run with `RUST_BACKTRACE=1` for a backtrace",
895 errors::Level::Note);
898 println!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
901 // Panic so the process returns a failure code, but don't pollute the
902 // output with some unnecessary panic messages, we've already
903 // printed everything that we needed to.
904 io::set_panic(box io::sink());
910 pub fn diagnostics_registry() -> diagnostics::registry::Registry {
911 use syntax::diagnostics::registry::Registry;
913 let mut all_errors = Vec::new();
914 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
915 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
916 all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
917 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
918 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
919 all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
921 Registry::new(&*all_errors)
925 let result = run(env::args().collect());
926 process::exit(result as i32);