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};
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;
76 use std::io::{self, Read, Write};
77 use std::iter::repeat;
78 use std::path::PathBuf;
82 use std::sync::{Arc, Mutex};
85 use rustc::session::early_error;
90 use syntax::errors::emitter::Emitter;
91 use syntax::diagnostics;
92 use syntax::parse::token;
99 pub mod target_features;
102 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
105 pub fn run(args: Vec<String>) -> isize {
106 monitor(move || run_compiler(&args, &mut RustcDefaultCalls));
110 // Parse args and run the compiler. This is the primary entry point for rustc.
111 // See comments on CompilerCalls below for details about the callbacks argument.
112 pub fn run_compiler<'a>(args: &[String], callbacks: &mut CompilerCalls<'a>) {
113 macro_rules! do_or_return {($expr: expr) => {
115 Compilation::Stop => return,
116 Compilation::Continue => {}
120 let matches = match handle_options(args.to_vec()) {
121 Some(matches) => matches,
125 let sopts = config::build_session_options(&matches);
127 let descriptions = diagnostics_registry();
129 do_or_return!(callbacks.early_callback(&matches, &descriptions, sopts.color));
131 let (odir, ofile) = make_output(&matches);
132 let (input, input_file_path) = match make_input(&matches.free) {
133 Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
134 None => match callbacks.no_input(&matches, &sopts, &odir, &ofile, &descriptions) {
135 Some((input, input_file_path)) => (input, input_file_path),
140 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
141 let sess = build_session(sopts, input_file_path, descriptions,
143 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
144 let mut cfg = config::build_configuration(&sess);
145 target_features::add_configuration(&mut cfg, &sess);
147 do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile));
149 // It is somewhat unfortunate that this is hardwired in - this is forced by
150 // the fact that pretty_print_input requires the session by value.
151 let pretty = callbacks.parse_pretty(&sess, &matches);
153 Some((ppm, opt_uii)) => {
154 pretty::pretty_print_input(sess, &cstore, cfg, &input, ppm, opt_uii, ofile);
162 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
163 let control = callbacks.build_controller(&sess);
164 driver::compile_input(sess, &cstore, cfg, &input, &odir, &ofile,
165 Some(plugins), control);
168 // Extract output directory and file from matches.
169 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
170 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
171 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
175 // Extract input (string or file and optional path) from matches.
176 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
177 if free_matches.len() == 1 {
178 let ifile = &free_matches[0][..];
180 let mut src = String::new();
181 io::stdin().read_to_string(&mut src).unwrap();
182 Some((Input::Str(src), None))
184 Some((Input::File(PathBuf::from(ifile)),
185 Some(PathBuf::from(ifile))))
192 // Whether to stop or continue compilation.
193 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
194 pub enum Compilation {
200 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
202 Compilation::Stop => Compilation::Stop,
203 Compilation::Continue => next(),
208 // A trait for customising the compilation process. Offers a number of hooks for
209 // executing custom code or customising input.
210 pub trait CompilerCalls<'a> {
211 // Hook for a callback early in the process of handling arguments. This will
212 // be called straight after options have been parsed but before anything
213 // else (e.g., selecting input and output).
214 fn early_callback(&mut self,
215 _: &getopts::Matches,
216 _: &diagnostics::registry::Registry,
217 _: errors::ColorConfig)
219 Compilation::Continue
222 // Hook for a callback late in the process of handling arguments. This will
223 // be called just before actual compilation starts (and before build_controller
224 // is called), after all arguments etc. have been completely handled.
225 fn late_callback(&mut self,
226 _: &getopts::Matches,
232 Compilation::Continue
235 // Called after we extract the input from the arguments. Gives the implementer
236 // an opportunity to change the inputs or to add some custom input handling.
237 // The default behaviour is to simply pass through the inputs.
238 fn some_input(&mut self,
240 input_path: Option<PathBuf>)
241 -> (Input, Option<PathBuf>) {
245 // Called after we extract the input from the arguments if there is no valid
246 // input. Gives the implementer an opportunity to supply alternate input (by
247 // returning a Some value) or to add custom behaviour for this error such as
248 // emitting error messages. Returning None will cause compilation to stop
250 fn no_input(&mut self,
251 _: &getopts::Matches,
255 _: &diagnostics::registry::Registry)
256 -> Option<(Input, Option<PathBuf>)> {
260 // Parse pretty printing information from the arguments. The implementer can
261 // choose to ignore this (the default will return None) which will skip pretty
262 // printing. If you do want to pretty print, it is recommended to use the
263 // implementation of this method from RustcDefaultCalls.
264 // FIXME, this is a terrible bit of API. Parsing of pretty printing stuff
265 // should be done as part of the framework and the implementor should customise
266 // handling of it. However, that is not possible atm because pretty printing
267 // essentially goes off and takes another path through the compiler which
268 // means the session is either moved or not depending on what parse_pretty
269 // returns (we could fix this by cloning, but it's another hack). The proper
270 // solution is to handle pretty printing as if it were a compiler extension,
271 // extending CompileController to make this work (see for example the treatment
272 // of save-analysis in RustcDefaultCalls::build_controller).
273 fn parse_pretty(&mut self,
275 _matches: &getopts::Matches)
276 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
280 // Create a CompilController struct for controlling the behaviour of
282 fn build_controller(&mut self, &Session) -> CompileController<'a>;
285 // CompilerCalls instance for a regular rustc build.
286 #[derive(Copy, Clone)]
287 pub struct RustcDefaultCalls;
289 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
290 fn early_callback(&mut self,
291 matches: &getopts::Matches,
292 descriptions: &diagnostics::registry::Registry,
293 color: errors::ColorConfig)
295 match matches.opt_str("explain") {
297 let normalised = if !code.starts_with("E") {
298 format!("E{0:0>4}", code)
302 match descriptions.find_description(&normalised) {
303 Some(ref description) => {
304 // Slice off the leading newline and print.
305 print!("{}", &description[1..]);
308 early_error(color, &format!("no extended information for {}", code));
311 return Compilation::Stop;
316 return Compilation::Continue;
319 fn no_input(&mut self,
320 matches: &getopts::Matches,
321 sopts: &config::Options,
322 odir: &Option<PathBuf>,
323 ofile: &Option<PathBuf>,
324 descriptions: &diagnostics::registry::Registry)
325 -> Option<(Input, Option<PathBuf>)> {
326 match matches.free.len() {
328 if sopts.describe_lints {
329 let mut ls = lint::LintStore::new();
330 rustc_lint::register_builtins(&mut ls, None);
331 describe_lints(&ls, false);
334 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
335 let sess = build_session(sopts.clone(), None, descriptions.clone(),
337 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
338 let should_stop = RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
339 if should_stop == Compilation::Stop {
342 early_error(sopts.color, "no input filename given");
344 1 => panic!("make_input should have provided valid inputs"),
345 _ => early_error(sopts.color, "multiple input filenames provided"),
351 fn parse_pretty(&mut self,
353 matches: &getopts::Matches)
354 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
355 let pretty = if sess.opts.debugging_opts.unstable_options {
356 matches.opt_default("pretty", "normal").map(|a| {
357 // stable pretty-print variants only
358 pretty::parse_pretty(sess, &a, false)
363 if pretty.is_none() && sess.unstable_options() {
364 matches.opt_str("unpretty").map(|a| {
365 // extended with unstable pretty-print variants
366 pretty::parse_pretty(sess, &a, true)
373 fn late_callback(&mut self,
374 matches: &getopts::Matches,
377 odir: &Option<PathBuf>,
378 ofile: &Option<PathBuf>)
380 RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
381 .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input))
384 fn build_controller(&mut self, sess: &Session) -> CompileController<'a> {
385 let mut control = CompileController::basic();
387 if sess.opts.parse_only || sess.opts.debugging_opts.show_span.is_some() ||
388 sess.opts.debugging_opts.ast_json_noexpand {
389 control.after_parse.stop = Compilation::Stop;
392 if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
393 control.after_write_deps.stop = Compilation::Stop;
396 if sess.opts.no_trans {
397 control.after_analysis.stop = Compilation::Stop;
400 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe) {
401 control.after_llvm.stop = Compilation::Stop;
404 if sess.opts.debugging_opts.save_analysis {
405 control.after_analysis.callback = box |state| {
406 time(state.session.time_passes(), "save analysis", || {
407 save::process_crate(state.tcx.unwrap(),
409 state.krate.unwrap(),
410 state.analysis.unwrap(),
411 state.crate_name.unwrap(),
415 control.make_glob_map = resolve::MakeGlobMap::Yes;
422 impl RustcDefaultCalls {
423 pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation {
424 let r = matches.opt_strs("Z");
425 if r.contains(&("ls".to_string())) {
427 &Input::File(ref ifile) => {
428 let path = &(*ifile);
429 let mut v = Vec::new();
430 loader::list_file_metadata(&sess.target.target, path, &mut v)
432 println!("{}", String::from_utf8(v).unwrap());
435 early_error(sess.opts.color, "cannot list metadata for stdin");
438 return Compilation::Stop;
441 return Compilation::Continue;
445 fn print_crate_info(sess: &Session,
446 input: Option<&Input>,
447 odir: &Option<PathBuf>,
448 ofile: &Option<PathBuf>)
450 if sess.opts.prints.is_empty() {
451 return Compilation::Continue;
454 let attrs = input.map(|input| parse_crate_attrs(sess, input));
455 for req in &sess.opts.prints {
457 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
458 PrintRequest::FileNames |
459 PrintRequest::CrateName => {
460 let input = match input {
461 Some(input) => input,
462 None => early_error(sess.opts.color, "no input file provided"),
464 let attrs = attrs.as_ref().unwrap();
465 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
466 let id = link::find_crate_name(Some(sess), attrs, input);
467 if *req == PrintRequest::CrateName {
471 let crate_types = driver::collect_crate_types(sess, attrs);
472 let metadata = driver::collect_crate_metadata(sess, attrs);
473 *sess.crate_metadata.borrow_mut() = metadata;
474 for &style in &crate_types {
475 let fname = link::filename_for_input(sess, style, &id, &t_outputs);
484 return Compilation::Stop;
488 /// Returns a version string such as "0.12.0-dev".
489 pub fn release_str() -> Option<&'static str> {
490 option_env!("CFG_RELEASE")
493 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
494 pub fn commit_hash_str() -> Option<&'static str> {
495 option_env!("CFG_VER_HASH")
498 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
499 pub fn commit_date_str() -> Option<&'static str> {
500 option_env!("CFG_VER_DATE")
503 /// Prints version information
504 pub fn version(binary: &str, matches: &getopts::Matches) {
505 let verbose = matches.opt_present("verbose");
509 option_env!("CFG_VERSION").unwrap_or("unknown version"));
511 fn unw(x: Option<&str>) -> &str {
512 x.unwrap_or("unknown")
514 println!("binary: {}", binary);
515 println!("commit-hash: {}", unw(commit_hash_str()));
516 println!("commit-date: {}", unw(commit_date_str()));
517 println!("host: {}", config::host_triple());
518 println!("release: {}", unw(release_str()));
522 fn usage(verbose: bool, include_unstable_options: bool) {
523 let groups = if verbose {
524 config::rustc_optgroups()
526 config::rustc_short_optgroups()
528 let groups: Vec<_> = groups.into_iter()
529 .filter(|x| include_unstable_options || x.is_stable())
530 .map(|x| x.opt_group)
532 let message = format!("Usage: rustc [OPTIONS] INPUT");
533 let extra_help = if verbose {
536 "\n --help -v Print the full set of options rustc accepts"
538 println!("{}\nAdditional help:
539 -C help Print codegen options
541 Print 'lint' options and default settings
542 -Z help Print internal \
543 options for debugging rustc{}\n",
544 getopts::usage(&message, &groups),
548 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
550 Available lint options:
551 -W <foo> Warn about <foo>
555 -F <foo> Forbid <foo> \
556 (deny, and deny all overrides)
560 fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
561 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
562 lints.sort_by(|x: &&Lint, y: &&Lint| {
563 match x.default_level.cmp(&y.default_level) {
564 // The sort doesn't case-fold but it's doubtful we care.
565 Equal => x.name.cmp(y.name),
572 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
573 -> Vec<(&'static str, Vec<lint::LintId>)> {
574 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
575 lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
576 &(y, _): &(&'static str, Vec<lint::LintId>)| {
582 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
585 .partition(|&(_, p)| p);
586 let plugin = sort_lints(plugin);
587 let builtin = sort_lints(builtin);
589 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
592 .partition(|&(_, _, p)| p);
593 let plugin_groups = sort_lint_groups(plugin_groups);
594 let builtin_groups = sort_lint_groups(builtin_groups);
596 let max_name_len = plugin.iter()
598 .map(|&s| s.name.chars().count())
601 let padded = |x: &str| {
602 let mut s = repeat(" ")
603 .take(max_name_len - x.chars().count())
604 .collect::<String>();
609 println!("Lint checks provided by rustc:\n");
610 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
611 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
613 let print_lints = |lints: Vec<&Lint>| {
615 let name = lint.name_lower().replace("_", "-");
616 println!(" {} {:7.7} {}",
618 lint.default_level.as_str(),
624 print_lints(builtin);
628 let max_name_len = max("warnings".len(),
630 .chain(&builtin_groups)
631 .map(|&(s, _)| s.chars().count())
635 let padded = |x: &str| {
636 let mut s = repeat(" ")
637 .take(max_name_len - x.chars().count())
638 .collect::<String>();
643 println!("Lint groups provided by rustc:\n");
644 println!(" {} {}", padded("name"), "sub-lints");
645 println!(" {} {}", padded("----"), "---------");
646 println!(" {} {}", padded("warnings"), "all built-in lints");
648 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
649 for (name, to) in lints {
650 let name = name.to_lowercase().replace("_", "-");
651 let desc = to.into_iter()
652 .map(|x| x.as_str().replace("_", "-"))
653 .collect::<Vec<String>>()
655 println!(" {} {}", padded(&name[..]), desc);
660 print_lint_groups(builtin_groups);
662 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
663 (false, 0, _) | (false, _, 0) => {
664 println!("Compiler plugins can provide additional lints and lint groups. To see a \
665 listing of these, re-run `rustc -W help` with a crate filename.");
667 (false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
668 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
671 println!("Lint checks provided by plugins loaded by this crate:\n");
675 println!("Lint groups provided by plugins loaded by this crate:\n");
676 print_lint_groups(plugin_groups);
682 fn describe_debug_flags() {
683 println!("\nAvailable debug options:\n");
684 print_flag_list("-Z", config::DB_OPTIONS);
687 fn describe_codegen_flags() {
688 println!("\nAvailable codegen options:\n");
689 print_flag_list("-C", config::CG_OPTIONS);
692 fn print_flag_list<T>(cmdline_opt: &str,
693 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
694 let max_len = flag_list.iter()
695 .map(|&(name, _, opt_type_desc, _)| {
696 let extra_len = match opt_type_desc {
700 name.chars().count() + extra_len
705 for &(name, _, opt_type_desc, desc) in flag_list {
706 let (width, extra) = match opt_type_desc {
707 Some(..) => (max_len - 4, "=val"),
708 None => (max_len, ""),
710 println!(" {} {:>width$}{} -- {}",
712 name.replace("_", "-"),
719 /// Process command line options. Emits messages as appropriate. If compilation
720 /// should continue, returns a getopts::Matches object parsed from args, otherwise
722 pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
723 // Throw away the first argument, the name of the binary
724 let _binary = args.remove(0);
727 // user did not write `-v` nor `-Z unstable-options`, so do not
728 // include that extra information.
733 fn allows_unstable_options(matches: &getopts::Matches) -> bool {
734 let r = matches.opt_strs("Z");
735 r.iter().any(|x| *x == "unstable-options")
738 fn parse_all_options(args: &Vec<String>) -> getopts::Matches {
739 let all_groups: Vec<getopts::OptGroup> = config::rustc_optgroups()
741 .map(|x| x.opt_group)
743 match getopts::getopts(&args[..], &all_groups) {
745 if !allows_unstable_options(&m) {
746 // If -Z unstable-options was not specified, verify that
747 // no unstable options were present.
748 for opt in config::rustc_optgroups().into_iter().filter(|x| !x.is_stable()) {
749 let opt_name = if !opt.opt_group.long_name.is_empty() {
750 &opt.opt_group.long_name
752 &opt.opt_group.short_name
754 if m.opt_present(opt_name) {
755 early_error(errors::ColorConfig::Auto,
756 &format!("use of unstable option '{}' requires -Z \
764 Err(f) => early_error(errors::ColorConfig::Auto, &f.to_string()),
768 // As a speed optimization, first try to parse the command-line using just
769 // the stable options.
770 let matches = match getopts::getopts(&args[..], &config::optgroups()) {
771 Ok(ref m) if allows_unstable_options(m) => {
772 // If -Z unstable-options was specified, redo parsing with the
773 // unstable options to ensure that unstable options are defined
774 // in the returned getopts::Matches.
775 parse_all_options(&args)
779 // redo option parsing, including unstable options this time,
780 // in anticipation that the mishandled option was one of the
782 parse_all_options(&args)
786 if matches.opt_present("h") || matches.opt_present("help") {
787 usage(matches.opt_present("verbose"),
788 allows_unstable_options(&matches));
792 // Don't handle -W help here, because we might first load plugins.
794 let r = matches.opt_strs("Z");
795 if r.iter().any(|x| *x == "help") {
796 describe_debug_flags();
800 let cg_flags = matches.opt_strs("C");
801 if cg_flags.iter().any(|x| *x == "help") {
802 describe_codegen_flags();
806 if cg_flags.contains(&"passes=list".to_string()) {
808 ::llvm::LLVMRustPrintPasses();
813 if matches.opt_present("version") {
814 version("rustc", &matches);
821 fn parse_crate_attrs(sess: &Session, input: &Input) -> Vec<ast::Attribute> {
822 let result = match *input {
823 Input::File(ref ifile) => {
824 parse::parse_crate_attrs_from_file(ifile, Vec::new(), &sess.parse_sess)
826 Input::Str(ref src) => {
827 parse::parse_crate_attrs_from_source_str(driver::anon_src().to_string(),
833 result.into_iter().collect()
836 /// Run a procedure which will detect panics in the compiler and print nicer
837 /// error messages rather than just failing the test.
839 /// The diagnostic emitter yielded to the procedure should be used for reporting
840 /// errors of the compiler.
841 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
842 const STACK_SIZE: usize = 8 * 1024 * 1024; // 8MB
844 struct Sink(Arc<Mutex<Vec<u8>>>);
845 impl Write for Sink {
846 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
847 Write::write(&mut *self.0.lock().unwrap(), data)
849 fn flush(&mut self) -> io::Result<()> {
854 let data = Arc::new(Mutex::new(Vec::new()));
855 let err = Sink(data.clone());
857 let mut cfg = thread::Builder::new().name("rustc".to_string());
859 // FIXME: Hacks on hacks. If the env is trying to override the stack size
860 // then *don't* set it explicitly.
861 if env::var_os("RUST_MIN_STACK").is_none() {
862 cfg = cfg.stack_size(STACK_SIZE);
865 match cfg.spawn(move || {
866 io::set_panic(box err);
875 // Thread panicked without emitting a fatal diagnostic
876 if !value.is::<errors::FatalError>() {
877 let mut emitter = errors::emitter::BasicEmitter::stderr(errors::ColorConfig::Auto);
879 // a .span_bug or .bug call has already printed what
880 // it wants to print.
881 if !value.is::<errors::ExplicitBug>() {
882 emitter.emit(None, "unexpected panic", None, errors::Level::Bug);
885 let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
886 format!("we would appreciate a bug report: {}", BUG_REPORT_URL)];
888 emitter.emit(None, ¬e[..], None, errors::Level::Note)
890 if let None = env::var_os("RUST_BACKTRACE") {
892 "run with `RUST_BACKTRACE=1` for a backtrace",
894 errors::Level::Note);
897 println!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
900 // Panic so the process returns a failure code, but don't pollute the
901 // output with some unnecessary panic messages, we've already
902 // printed everything that we needed to.
903 io::set_panic(box io::sink());
909 pub fn diagnostics_registry() -> diagnostics::registry::Registry {
910 use syntax::diagnostics::registry::Registry;
912 let mut all_errors = Vec::new();
913 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
914 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
915 all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
916 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
917 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
918 all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
920 Registry::new(&*all_errors)
924 let result = run(env::args().collect());
925 process::exit(result as i32);