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_passes;
42 extern crate rustc_front;
43 extern crate rustc_lint;
44 extern crate rustc_plugin;
45 extern crate rustc_privacy;
46 extern crate rustc_metadata;
47 extern crate rustc_mir;
48 extern crate rustc_resolve;
49 extern crate rustc_trans;
50 extern crate rustc_typeck;
51 extern crate serialize;
52 extern crate rustc_llvm as llvm;
57 extern crate syntax_ext;
59 use driver::CompileController;
60 use pretty::{PpMode, UserIdentifiedItem};
62 use rustc_resolve as resolve;
63 use rustc_trans::back::link;
64 use rustc_trans::save;
65 use rustc::session::{config, Session, build_session};
66 use rustc::session::config::{Input, PrintRequest, OutputType, ErrorOutputType};
67 use rustc::middle::cstore::CrateStore;
68 use rustc::lint::Lint;
70 use rustc_metadata::loader;
71 use rustc_metadata::cstore::CStore;
72 use rustc::util::common::time;
75 use std::cmp::Ordering::Equal;
76 use std::default::Default;
78 use std::io::{self, Read, Write};
79 use std::iter::repeat;
80 use std::path::PathBuf;
84 use std::sync::{Arc, Mutex};
87 use rustc::session::early_error;
92 use syntax::errors::emitter::Emitter;
93 use syntax::diagnostics;
94 use syntax::parse::token;
101 pub mod target_features;
104 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
107 pub fn run(args: Vec<String>) -> isize {
108 monitor(move || run_compiler(&args, &mut RustcDefaultCalls));
112 // Parse args and run the compiler. This is the primary entry point for rustc.
113 // See comments on CompilerCalls below for details about the callbacks argument.
114 pub fn run_compiler<'a>(args: &[String], callbacks: &mut CompilerCalls<'a>) {
115 macro_rules! do_or_return {($expr: expr) => {
117 Compilation::Stop => return,
118 Compilation::Continue => {}
122 let matches = match handle_options(args.to_vec()) {
123 Some(matches) => matches,
127 let sopts = config::build_session_options(&matches);
129 let descriptions = diagnostics_registry();
131 do_or_return!(callbacks.early_callback(&matches, &descriptions, sopts.error_format));
133 let (odir, ofile) = make_output(&matches);
134 let (input, input_file_path) = match make_input(&matches.free) {
135 Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
136 None => match callbacks.no_input(&matches, &sopts, &odir, &ofile, &descriptions) {
137 Some((input, input_file_path)) => (input, input_file_path),
142 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
143 let sess = build_session(sopts, input_file_path, descriptions,
145 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
146 let mut cfg = config::build_configuration(&sess);
147 target_features::add_configuration(&mut cfg, &sess);
149 do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile));
151 // It is somewhat unfortunate that this is hardwired in - this is forced by
152 // the fact that pretty_print_input requires the session by value.
153 let pretty = callbacks.parse_pretty(&sess, &matches);
155 Some((ppm, opt_uii)) => {
156 pretty::pretty_print_input(sess, &cstore, cfg, &input, ppm, opt_uii, ofile);
164 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
165 let control = callbacks.build_controller(&sess);
166 driver::compile_input(sess, &cstore, cfg, &input, &odir, &ofile,
167 Some(plugins), control);
170 // Extract output directory and file from matches.
171 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
172 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
173 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
177 // Extract input (string or file and optional path) from matches.
178 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
179 if free_matches.len() == 1 {
180 let ifile = &free_matches[0][..];
182 let mut src = String::new();
183 io::stdin().read_to_string(&mut src).unwrap();
184 Some((Input::Str(src), None))
186 Some((Input::File(PathBuf::from(ifile)),
187 Some(PathBuf::from(ifile))))
194 // Whether to stop or continue compilation.
195 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
196 pub enum Compilation {
202 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
204 Compilation::Stop => Compilation::Stop,
205 Compilation::Continue => next(),
210 // A trait for customising the compilation process. Offers a number of hooks for
211 // executing custom code or customising input.
212 pub trait CompilerCalls<'a> {
213 // Hook for a callback early in the process of handling arguments. This will
214 // be called straight after options have been parsed but before anything
215 // else (e.g., selecting input and output).
216 fn early_callback(&mut self,
217 _: &getopts::Matches,
218 _: &diagnostics::registry::Registry,
221 Compilation::Continue
224 // Hook for a callback late in the process of handling arguments. This will
225 // be called just before actual compilation starts (and before build_controller
226 // is called), after all arguments etc. have been completely handled.
227 fn late_callback(&mut self,
228 _: &getopts::Matches,
234 Compilation::Continue
237 // Called after we extract the input from the arguments. Gives the implementer
238 // an opportunity to change the inputs or to add some custom input handling.
239 // The default behaviour is to simply pass through the inputs.
240 fn some_input(&mut self,
242 input_path: Option<PathBuf>)
243 -> (Input, Option<PathBuf>) {
247 // Called after we extract the input from the arguments if there is no valid
248 // input. Gives the implementer an opportunity to supply alternate input (by
249 // returning a Some value) or to add custom behaviour for this error such as
250 // emitting error messages. Returning None will cause compilation to stop
252 fn no_input(&mut self,
253 _: &getopts::Matches,
257 _: &diagnostics::registry::Registry)
258 -> Option<(Input, Option<PathBuf>)> {
262 // Parse pretty printing information from the arguments. The implementer can
263 // choose to ignore this (the default will return None) which will skip pretty
264 // printing. If you do want to pretty print, it is recommended to use the
265 // implementation of this method from RustcDefaultCalls.
266 // FIXME, this is a terrible bit of API. Parsing of pretty printing stuff
267 // should be done as part of the framework and the implementor should customise
268 // handling of it. However, that is not possible atm because pretty printing
269 // essentially goes off and takes another path through the compiler which
270 // means the session is either moved or not depending on what parse_pretty
271 // returns (we could fix this by cloning, but it's another hack). The proper
272 // solution is to handle pretty printing as if it were a compiler extension,
273 // extending CompileController to make this work (see for example the treatment
274 // of save-analysis in RustcDefaultCalls::build_controller).
275 fn parse_pretty(&mut self,
277 _matches: &getopts::Matches)
278 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
282 // Create a CompilController struct for controlling the behaviour of
284 fn build_controller(&mut self, &Session) -> CompileController<'a>;
287 // CompilerCalls instance for a regular rustc build.
288 #[derive(Copy, Clone)]
289 pub struct RustcDefaultCalls;
291 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
292 fn early_callback(&mut self,
293 matches: &getopts::Matches,
294 descriptions: &diagnostics::registry::Registry,
295 output: ErrorOutputType)
297 match matches.opt_str("explain") {
299 let normalised = if !code.starts_with("E") {
300 format!("E{0:0>4}", code)
304 match descriptions.find_description(&normalised) {
305 Some(ref description) => {
306 // Slice off the leading newline and print.
307 print!("{}", &description[1..]);
310 early_error(output, &format!("no extended information for {}", code));
313 return Compilation::Stop;
318 return Compilation::Continue;
321 fn no_input(&mut self,
322 matches: &getopts::Matches,
323 sopts: &config::Options,
324 odir: &Option<PathBuf>,
325 ofile: &Option<PathBuf>,
326 descriptions: &diagnostics::registry::Registry)
327 -> Option<(Input, Option<PathBuf>)> {
328 match matches.free.len() {
330 if sopts.describe_lints {
331 let mut ls = lint::LintStore::new();
332 rustc_lint::register_builtins(&mut ls, None);
333 describe_lints(&ls, false);
336 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
337 let sess = build_session(sopts.clone(), None, descriptions.clone(),
339 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
340 let should_stop = RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
341 if should_stop == Compilation::Stop {
344 early_error(sopts.error_format, "no input filename given");
346 1 => panic!("make_input should have provided valid inputs"),
347 _ => early_error(sopts.error_format, "multiple input filenames provided"),
353 fn parse_pretty(&mut self,
355 matches: &getopts::Matches)
356 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
357 let pretty = if sess.opts.debugging_opts.unstable_options {
358 matches.opt_default("pretty", "normal").map(|a| {
359 // stable pretty-print variants only
360 pretty::parse_pretty(sess, &a, false)
365 if pretty.is_none() && sess.unstable_options() {
366 matches.opt_str("unpretty").map(|a| {
367 // extended with unstable pretty-print variants
368 pretty::parse_pretty(sess, &a, true)
375 fn late_callback(&mut self,
376 matches: &getopts::Matches,
379 odir: &Option<PathBuf>,
380 ofile: &Option<PathBuf>)
382 RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
383 .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input))
386 fn build_controller(&mut self, sess: &Session) -> CompileController<'a> {
387 let mut control = CompileController::basic();
389 if sess.opts.parse_only || sess.opts.debugging_opts.show_span.is_some() ||
390 sess.opts.debugging_opts.ast_json_noexpand {
391 control.after_parse.stop = Compilation::Stop;
394 if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
395 control.after_write_deps.stop = Compilation::Stop;
398 if sess.opts.no_trans {
399 control.after_analysis.stop = Compilation::Stop;
402 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe) {
403 control.after_llvm.stop = Compilation::Stop;
406 if sess.opts.debugging_opts.save_analysis {
407 control.after_analysis.callback = box |state| {
408 time(state.session.time_passes(), "save analysis", || {
409 save::process_crate(state.tcx.unwrap(),
411 state.krate.unwrap(),
412 state.analysis.unwrap(),
413 state.crate_name.unwrap(),
417 control.make_glob_map = resolve::MakeGlobMap::Yes;
424 impl RustcDefaultCalls {
425 pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation {
426 let r = matches.opt_strs("Z");
427 if r.contains(&("ls".to_string())) {
429 &Input::File(ref ifile) => {
430 let path = &(*ifile);
431 let mut v = Vec::new();
432 loader::list_file_metadata(&sess.target.target, path, &mut v)
434 println!("{}", String::from_utf8(v).unwrap());
437 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
440 return Compilation::Stop;
443 return Compilation::Continue;
447 fn print_crate_info(sess: &Session,
448 input: Option<&Input>,
449 odir: &Option<PathBuf>,
450 ofile: &Option<PathBuf>)
452 if sess.opts.prints.is_empty() {
453 return Compilation::Continue;
456 let attrs = input.map(|input| parse_crate_attrs(sess, input));
457 for req in &sess.opts.prints {
459 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
460 PrintRequest::FileNames |
461 PrintRequest::CrateName => {
462 let input = match input {
463 Some(input) => input,
464 None => early_error(ErrorOutputType::default(), "no input file provided"),
466 let attrs = attrs.as_ref().unwrap();
467 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
468 let id = link::find_crate_name(Some(sess), attrs, input);
469 if *req == PrintRequest::CrateName {
473 let crate_types = driver::collect_crate_types(sess, attrs);
474 let metadata = driver::collect_crate_metadata(sess, attrs);
475 *sess.crate_metadata.borrow_mut() = metadata;
476 for &style in &crate_types {
477 let fname = link::filename_for_input(sess, style, &id, &t_outputs);
486 return Compilation::Stop;
490 /// Returns a version string such as "0.12.0-dev".
491 pub fn release_str() -> Option<&'static str> {
492 option_env!("CFG_RELEASE")
495 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
496 pub fn commit_hash_str() -> Option<&'static str> {
497 option_env!("CFG_VER_HASH")
500 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
501 pub fn commit_date_str() -> Option<&'static str> {
502 option_env!("CFG_VER_DATE")
505 /// Prints version information
506 pub fn version(binary: &str, matches: &getopts::Matches) {
507 let verbose = matches.opt_present("verbose");
511 option_env!("CFG_VERSION").unwrap_or("unknown version"));
513 fn unw(x: Option<&str>) -> &str {
514 x.unwrap_or("unknown")
516 println!("binary: {}", binary);
517 println!("commit-hash: {}", unw(commit_hash_str()));
518 println!("commit-date: {}", unw(commit_date_str()));
519 println!("host: {}", config::host_triple());
520 println!("release: {}", unw(release_str()));
524 fn usage(verbose: bool, include_unstable_options: bool) {
525 let groups = if verbose {
526 config::rustc_optgroups()
528 config::rustc_short_optgroups()
530 let groups: Vec<_> = groups.into_iter()
531 .filter(|x| include_unstable_options || x.is_stable())
532 .map(|x| x.opt_group)
534 let message = format!("Usage: rustc [OPTIONS] INPUT");
535 let extra_help = if verbose {
538 "\n --help -v Print the full set of options rustc accepts"
540 println!("{}\nAdditional help:
541 -C help Print codegen options
543 Print 'lint' options and default settings
544 -Z help Print internal \
545 options for debugging rustc{}\n",
546 getopts::usage(&message, &groups),
550 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
552 Available lint options:
553 -W <foo> Warn about <foo>
557 -F <foo> Forbid <foo> \
558 (deny, and deny all overrides)
562 fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
563 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
564 lints.sort_by(|x: &&Lint, y: &&Lint| {
565 match x.default_level.cmp(&y.default_level) {
566 // The sort doesn't case-fold but it's doubtful we care.
567 Equal => x.name.cmp(y.name),
574 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
575 -> Vec<(&'static str, Vec<lint::LintId>)> {
576 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
577 lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
578 &(y, _): &(&'static str, Vec<lint::LintId>)| {
584 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
587 .partition(|&(_, p)| p);
588 let plugin = sort_lints(plugin);
589 let builtin = sort_lints(builtin);
591 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
594 .partition(|&(_, _, p)| p);
595 let plugin_groups = sort_lint_groups(plugin_groups);
596 let builtin_groups = sort_lint_groups(builtin_groups);
598 let max_name_len = plugin.iter()
600 .map(|&s| s.name.chars().count())
603 let padded = |x: &str| {
604 let mut s = repeat(" ")
605 .take(max_name_len - x.chars().count())
606 .collect::<String>();
611 println!("Lint checks provided by rustc:\n");
612 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
613 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
615 let print_lints = |lints: Vec<&Lint>| {
617 let name = lint.name_lower().replace("_", "-");
618 println!(" {} {:7.7} {}",
620 lint.default_level.as_str(),
626 print_lints(builtin);
630 let max_name_len = max("warnings".len(),
632 .chain(&builtin_groups)
633 .map(|&(s, _)| s.chars().count())
637 let padded = |x: &str| {
638 let mut s = repeat(" ")
639 .take(max_name_len - x.chars().count())
640 .collect::<String>();
645 println!("Lint groups provided by rustc:\n");
646 println!(" {} {}", padded("name"), "sub-lints");
647 println!(" {} {}", padded("----"), "---------");
648 println!(" {} {}", padded("warnings"), "all built-in lints");
650 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
651 for (name, to) in lints {
652 let name = name.to_lowercase().replace("_", "-");
653 let desc = to.into_iter()
654 .map(|x| x.as_str().replace("_", "-"))
655 .collect::<Vec<String>>()
657 println!(" {} {}", padded(&name[..]), desc);
662 print_lint_groups(builtin_groups);
664 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
665 (false, 0, _) | (false, _, 0) => {
666 println!("Compiler plugins can provide additional lints and lint groups. To see a \
667 listing of these, re-run `rustc -W help` with a crate filename.");
669 (false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
670 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
673 println!("Lint checks provided by plugins loaded by this crate:\n");
677 println!("Lint groups provided by plugins loaded by this crate:\n");
678 print_lint_groups(plugin_groups);
684 fn describe_debug_flags() {
685 println!("\nAvailable debug options:\n");
686 print_flag_list("-Z", config::DB_OPTIONS);
689 fn describe_codegen_flags() {
690 println!("\nAvailable codegen options:\n");
691 print_flag_list("-C", config::CG_OPTIONS);
694 fn print_flag_list<T>(cmdline_opt: &str,
695 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
696 let max_len = flag_list.iter()
697 .map(|&(name, _, opt_type_desc, _)| {
698 let extra_len = match opt_type_desc {
702 name.chars().count() + extra_len
707 for &(name, _, opt_type_desc, desc) in flag_list {
708 let (width, extra) = match opt_type_desc {
709 Some(..) => (max_len - 4, "=val"),
710 None => (max_len, ""),
712 println!(" {} {:>width$}{} -- {}",
714 name.replace("_", "-"),
721 /// Process command line options. Emits messages as appropriate. If compilation
722 /// should continue, returns a getopts::Matches object parsed from args, otherwise
724 pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
725 // Throw away the first argument, the name of the binary
726 let _binary = args.remove(0);
729 // user did not write `-v` nor `-Z unstable-options`, so do not
730 // include that extra information.
735 fn allows_unstable_options(matches: &getopts::Matches) -> bool {
736 let r = matches.opt_strs("Z");
737 r.iter().any(|x| *x == "unstable-options")
740 fn parse_all_options(args: &Vec<String>) -> getopts::Matches {
741 let all_groups: Vec<getopts::OptGroup> = config::rustc_optgroups()
743 .map(|x| x.opt_group)
745 match getopts::getopts(&args[..], &all_groups) {
747 if !allows_unstable_options(&m) {
748 // If -Z unstable-options was not specified, verify that
749 // no unstable options were present.
750 for opt in config::rustc_optgroups().into_iter().filter(|x| !x.is_stable()) {
751 let opt_name = if !opt.opt_group.long_name.is_empty() {
752 &opt.opt_group.long_name
754 &opt.opt_group.short_name
756 if m.opt_present(opt_name) {
757 early_error(ErrorOutputType::default(),
758 &format!("use of unstable option '{}' requires -Z \
766 Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
770 // As a speed optimization, first try to parse the command-line using just
771 // the stable options.
772 let matches = match getopts::getopts(&args[..], &config::optgroups()) {
773 Ok(ref m) if allows_unstable_options(m) => {
774 // If -Z unstable-options was specified, redo parsing with the
775 // unstable options to ensure that unstable options are defined
776 // in the returned getopts::Matches.
777 parse_all_options(&args)
781 // redo option parsing, including unstable options this time,
782 // in anticipation that the mishandled option was one of the
784 parse_all_options(&args)
788 if matches.opt_present("h") || matches.opt_present("help") {
789 usage(matches.opt_present("verbose"),
790 allows_unstable_options(&matches));
794 // Don't handle -W help here, because we might first load plugins.
796 let r = matches.opt_strs("Z");
797 if r.iter().any(|x| *x == "help") {
798 describe_debug_flags();
802 let cg_flags = matches.opt_strs("C");
803 if cg_flags.iter().any(|x| *x == "help") {
804 describe_codegen_flags();
808 if cg_flags.contains(&"passes=list".to_string()) {
810 ::llvm::LLVMRustPrintPasses();
815 if matches.opt_present("version") {
816 version("rustc", &matches);
823 fn parse_crate_attrs(sess: &Session, input: &Input) -> Vec<ast::Attribute> {
824 let result = match *input {
825 Input::File(ref ifile) => {
826 parse::parse_crate_attrs_from_file(ifile, Vec::new(), &sess.parse_sess)
828 Input::Str(ref src) => {
829 parse::parse_crate_attrs_from_source_str(driver::anon_src().to_string(),
835 result.into_iter().collect()
838 /// Run a procedure which will detect panics in the compiler and print nicer
839 /// error messages rather than just failing the test.
841 /// The diagnostic emitter yielded to the procedure should be used for reporting
842 /// errors of the compiler.
843 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
844 const STACK_SIZE: usize = 8 * 1024 * 1024; // 8MB
846 struct Sink(Arc<Mutex<Vec<u8>>>);
847 impl Write for Sink {
848 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
849 Write::write(&mut *self.0.lock().unwrap(), data)
851 fn flush(&mut self) -> io::Result<()> {
856 let data = Arc::new(Mutex::new(Vec::new()));
857 let err = Sink(data.clone());
859 let mut cfg = thread::Builder::new().name("rustc".to_string());
861 // FIXME: Hacks on hacks. If the env is trying to override the stack size
862 // then *don't* set it explicitly.
863 if env::var_os("RUST_MIN_STACK").is_none() {
864 cfg = cfg.stack_size(STACK_SIZE);
867 match cfg.spawn(move || {
868 io::set_panic(box err);
877 // Thread panicked without emitting a fatal diagnostic
878 if !value.is::<errors::FatalError>() {
879 let mut emitter = errors::emitter::BasicEmitter::stderr(errors::ColorConfig::Auto);
881 // a .span_bug or .bug call has already printed what
882 // it wants to print.
883 if !value.is::<errors::ExplicitBug>() {
884 emitter.emit(None, "unexpected panic", None, errors::Level::Bug);
887 let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
888 format!("we would appreciate a bug report: {}", BUG_REPORT_URL)];
890 emitter.emit(None, ¬e[..], None, errors::Level::Note)
892 if let None = env::var_os("RUST_BACKTRACE") {
894 "run with `RUST_BACKTRACE=1` for a backtrace",
896 errors::Level::Note);
899 println!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
902 // Panic so the process returns a failure code, but don't pollute the
903 // output with some unnecessary panic messages, we've already
904 // printed everything that we needed to.
905 io::set_panic(box io::sink());
911 pub fn diagnostics_registry() -> diagnostics::registry::Registry {
912 use syntax::diagnostics::registry::Registry;
914 let mut all_errors = Vec::new();
915 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
916 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
917 all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
918 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
919 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
920 all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
922 Registry::new(&*all_errors)
926 let result = run(env::args().collect());
927 process::exit(result as i32);