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 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
18 #![cfg_attr(stage0, feature(custom_attribute))]
19 #![crate_name = "rustc_driver"]
20 #![unstable(feature = "rustc_private", issue = "27812")]
21 #![cfg_attr(stage0, staged_api)]
22 #![crate_type = "dylib"]
23 #![crate_type = "rlib"]
24 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
25 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
26 html_root_url = "https://doc.rust-lang.org/nightly/")]
28 #![feature(box_syntax)]
31 #![feature(rustc_diagnostic_macros)]
32 #![feature(rustc_private)]
33 #![feature(set_stdio)]
34 #![feature(staged_api)]
35 #![feature(raw)] // remove after snapshot
40 extern crate graphviz;
43 extern crate rustc_back;
44 extern crate rustc_borrowck;
45 extern crate rustc_front;
46 extern crate rustc_lint;
47 extern crate rustc_plugin;
48 extern crate rustc_privacy;
49 extern crate rustc_metadata;
50 extern crate rustc_mir;
51 extern crate rustc_resolve;
52 extern crate rustc_trans;
53 extern crate rustc_typeck;
54 extern crate serialize;
55 extern crate rustc_llvm as llvm;
60 extern crate syntax_ext;
62 use driver::CompileController;
63 use pretty::{PpMode, UserIdentifiedItem};
65 use rustc_resolve as resolve;
66 use rustc_trans::back::link;
67 use rustc_trans::save;
68 use rustc::session::{config, Session, build_session};
69 use rustc::session::config::{Input, PrintRequest, OutputType};
70 use rustc::middle::cstore::CrateStore;
71 use rustc::lint::Lint;
73 use rustc_metadata::loader;
74 use rustc_metadata::cstore::CStore;
75 use rustc::util::common::time;
77 use std::cmp::Ordering::Equal;
79 use std::io::{self, Read, Write};
80 use std::iter::repeat;
81 use std::path::PathBuf;
85 use std::sync::{Arc, Mutex};
88 use rustc::session::early_error;
93 use syntax::errors::emitter::Emitter;
94 use syntax::diagnostics;
95 use syntax::parse::token;
102 pub mod target_features;
105 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
109 // This is a terrible hack. Our stage0 is older than 1.4 and does not
110 // support DST coercions, so this function performs the corecion
111 // manually. This should go away.
112 pub fn cstore_to_cratestore(a: Rc<CStore>) -> Rc<for<'s> CrateStore<'s>>
115 use std::raw::TraitObject;
117 let TraitObject { vtable, .. } =
118 mem::transmute::<&for<'s> CrateStore<'s>, TraitObject>(&*a);
119 mem::transmute(TraitObject {
120 data: mem::transmute(a),
126 pub fn run(args: Vec<String>) -> isize {
127 monitor(move || run_compiler(&args, &mut RustcDefaultCalls));
131 // Parse args and run the compiler. This is the primary entry point for rustc.
132 // See comments on CompilerCalls below for details about the callbacks argument.
133 pub fn run_compiler<'a>(args: &[String], callbacks: &mut CompilerCalls<'a>) {
134 macro_rules! do_or_return {($expr: expr) => {
136 Compilation::Stop => return,
137 Compilation::Continue => {}
141 let matches = match handle_options(args.to_vec()) {
142 Some(matches) => matches,
146 let sopts = config::build_session_options(&matches);
148 let descriptions = diagnostics_registry();
150 do_or_return!(callbacks.early_callback(&matches, &descriptions, sopts.color));
152 let (odir, ofile) = make_output(&matches);
153 let (input, input_file_path) = match make_input(&matches.free) {
154 Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
155 None => match callbacks.no_input(&matches, &sopts, &odir, &ofile, &descriptions) {
156 Some((input, input_file_path)) => (input, input_file_path),
161 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
162 let cstore_ = cstore_to_cratestore(cstore.clone());
163 let mut sess = build_session(sopts, input_file_path, descriptions, cstore_);
164 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
165 if sess.unstable_options() {
166 sess.opts.show_span = matches.opt_str("show-span");
168 let mut cfg = config::build_configuration(&sess);
169 target_features::add_configuration(&mut cfg, &sess);
171 do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile));
173 // It is somewhat unfortunate that this is hardwired in - this is forced by
174 // the fact that pretty_print_input requires the session by value.
175 let pretty = callbacks.parse_pretty(&sess, &matches);
177 Some((ppm, opt_uii)) => {
178 pretty::pretty_print_input(sess, &cstore, cfg, &input, ppm, opt_uii, ofile);
186 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
187 let control = callbacks.build_controller(&sess);
188 driver::compile_input(sess, &cstore, cfg, &input, &odir, &ofile,
189 Some(plugins), control);
192 // Extract output directory and file from matches.
193 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
194 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
195 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
199 // Extract input (string or file and optional path) from matches.
200 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
201 if free_matches.len() == 1 {
202 let ifile = &free_matches[0][..];
204 let mut src = String::new();
205 io::stdin().read_to_string(&mut src).unwrap();
206 Some((Input::Str(src), None))
208 Some((Input::File(PathBuf::from(ifile)),
209 Some(PathBuf::from(ifile))))
216 // Whether to stop or continue compilation.
217 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
218 pub enum Compilation {
224 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
226 Compilation::Stop => Compilation::Stop,
227 Compilation::Continue => next(),
232 // A trait for customising the compilation process. Offers a number of hooks for
233 // executing custom code or customising input.
234 pub trait CompilerCalls<'a> {
235 // Hook for a callback early in the process of handling arguments. This will
236 // be called straight after options have been parsed but before anything
237 // else (e.g., selecting input and output).
238 fn early_callback(&mut self,
239 _: &getopts::Matches,
240 _: &diagnostics::registry::Registry,
241 _: errors::ColorConfig)
243 Compilation::Continue
246 // Hook for a callback late in the process of handling arguments. This will
247 // be called just before actual compilation starts (and before build_controller
248 // is called), after all arguments etc. have been completely handled.
249 fn late_callback(&mut self,
250 _: &getopts::Matches,
256 Compilation::Continue
259 // Called after we extract the input from the arguments. Gives the implementer
260 // an opportunity to change the inputs or to add some custom input handling.
261 // The default behaviour is to simply pass through the inputs.
262 fn some_input(&mut self,
264 input_path: Option<PathBuf>)
265 -> (Input, Option<PathBuf>) {
269 // Called after we extract the input from the arguments if there is no valid
270 // input. Gives the implementer an opportunity to supply alternate input (by
271 // returning a Some value) or to add custom behaviour for this error such as
272 // emitting error messages. Returning None will cause compilation to stop
274 fn no_input(&mut self,
275 _: &getopts::Matches,
279 _: &diagnostics::registry::Registry)
280 -> Option<(Input, Option<PathBuf>)> {
284 // Parse pretty printing information from the arguments. The implementer can
285 // choose to ignore this (the default will return None) which will skip pretty
286 // printing. If you do want to pretty print, it is recommended to use the
287 // implementation of this method from RustcDefaultCalls.
288 // FIXME, this is a terrible bit of API. Parsing of pretty printing stuff
289 // should be done as part of the framework and the implementor should customise
290 // handling of it. However, that is not possible atm because pretty printing
291 // essentially goes off and takes another path through the compiler which
292 // means the session is either moved or not depending on what parse_pretty
293 // returns (we could fix this by cloning, but it's another hack). The proper
294 // solution is to handle pretty printing as if it were a compiler extension,
295 // extending CompileController to make this work (see for example the treatment
296 // of save-analysis in RustcDefaultCalls::build_controller).
297 fn parse_pretty(&mut self,
299 _matches: &getopts::Matches)
300 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
304 // Create a CompilController struct for controlling the behaviour of
306 fn build_controller(&mut self, &Session) -> CompileController<'a>;
309 // CompilerCalls instance for a regular rustc build.
310 #[derive(Copy, Clone)]
311 pub struct RustcDefaultCalls;
313 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
314 fn early_callback(&mut self,
315 matches: &getopts::Matches,
316 descriptions: &diagnostics::registry::Registry,
317 color: errors::ColorConfig)
319 match matches.opt_str("explain") {
321 let normalised = if !code.starts_with("E") {
322 format!("E{0:0>4}", code)
326 match descriptions.find_description(&normalised) {
327 Some(ref description) => {
328 // Slice off the leading newline and print.
329 print!("{}", &description[1..]);
332 early_error(color, &format!("no extended information for {}", code));
335 return Compilation::Stop;
340 return Compilation::Continue;
343 fn no_input(&mut self,
344 matches: &getopts::Matches,
345 sopts: &config::Options,
346 odir: &Option<PathBuf>,
347 ofile: &Option<PathBuf>,
348 descriptions: &diagnostics::registry::Registry)
349 -> Option<(Input, Option<PathBuf>)> {
350 match matches.free.len() {
352 if sopts.describe_lints {
353 let mut ls = lint::LintStore::new();
354 rustc_lint::register_builtins(&mut ls, None);
355 describe_lints(&ls, false);
358 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
359 let cstore_ = cstore_to_cratestore(cstore.clone());
360 let sess = build_session(sopts.clone(), None, descriptions.clone(), cstore_);
361 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
362 let should_stop = RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
363 if should_stop == Compilation::Stop {
366 early_error(sopts.color, "no input filename given");
368 1 => panic!("make_input should have provided valid inputs"),
369 _ => early_error(sopts.color, "multiple input filenames provided"),
375 fn parse_pretty(&mut self,
377 matches: &getopts::Matches)
378 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
379 let pretty = if sess.opts.debugging_opts.unstable_options {
380 matches.opt_default("pretty", "normal").map(|a| {
381 // stable pretty-print variants only
382 pretty::parse_pretty(sess, &a, false)
387 if pretty.is_none() && sess.unstable_options() {
388 matches.opt_str("unpretty").map(|a| {
389 // extended with unstable pretty-print variants
390 pretty::parse_pretty(sess, &a, true)
397 fn late_callback(&mut self,
398 matches: &getopts::Matches,
401 odir: &Option<PathBuf>,
402 ofile: &Option<PathBuf>)
404 RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
405 .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input))
408 fn build_controller(&mut self, sess: &Session) -> CompileController<'a> {
409 let mut control = CompileController::basic();
411 if sess.opts.parse_only || sess.opts.show_span.is_some() ||
412 sess.opts.debugging_opts.ast_json_noexpand {
413 control.after_parse.stop = Compilation::Stop;
416 if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
417 control.after_write_deps.stop = Compilation::Stop;
420 if sess.opts.no_trans {
421 control.after_analysis.stop = Compilation::Stop;
424 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe) {
425 control.after_llvm.stop = Compilation::Stop;
428 if sess.opts.debugging_opts.save_analysis {
429 control.after_analysis.callback = box |state| {
430 time(state.session.time_passes(), "save analysis", || {
431 save::process_crate(state.tcx.unwrap(),
433 state.krate.unwrap(),
434 state.analysis.unwrap(),
435 state.crate_name.unwrap(),
439 control.make_glob_map = resolve::MakeGlobMap::Yes;
446 impl RustcDefaultCalls {
447 pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation {
448 let r = matches.opt_strs("Z");
449 if r.contains(&("ls".to_string())) {
451 &Input::File(ref ifile) => {
452 let path = &(*ifile);
453 let mut v = Vec::new();
454 loader::list_file_metadata(&sess.target.target, path, &mut v)
456 println!("{}", String::from_utf8(v).unwrap());
459 early_error(sess.opts.color, "cannot list metadata for stdin");
462 return Compilation::Stop;
465 return Compilation::Continue;
469 fn print_crate_info(sess: &Session,
470 input: Option<&Input>,
471 odir: &Option<PathBuf>,
472 ofile: &Option<PathBuf>)
474 if sess.opts.prints.is_empty() {
475 return Compilation::Continue;
478 let attrs = input.map(|input| parse_crate_attrs(sess, input));
479 for req in &sess.opts.prints {
481 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
482 PrintRequest::FileNames |
483 PrintRequest::CrateName => {
484 let input = match input {
485 Some(input) => input,
486 None => early_error(sess.opts.color, "no input file provided"),
488 let attrs = attrs.as_ref().unwrap();
489 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
490 let id = link::find_crate_name(Some(sess), attrs, input);
491 if *req == PrintRequest::CrateName {
495 let crate_types = driver::collect_crate_types(sess, attrs);
496 let metadata = driver::collect_crate_metadata(sess, attrs);
497 *sess.crate_metadata.borrow_mut() = metadata;
498 for &style in &crate_types {
499 let fname = link::filename_for_input(sess, style, &id, &t_outputs);
508 return Compilation::Stop;
512 /// Returns a version string such as "0.12.0-dev".
513 pub fn release_str() -> Option<&'static str> {
514 option_env!("CFG_RELEASE")
517 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
518 pub fn commit_hash_str() -> Option<&'static str> {
519 option_env!("CFG_VER_HASH")
522 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
523 pub fn commit_date_str() -> Option<&'static str> {
524 option_env!("CFG_VER_DATE")
527 /// Prints version information
528 pub fn version(binary: &str, matches: &getopts::Matches) {
529 let verbose = matches.opt_present("verbose");
533 option_env!("CFG_VERSION").unwrap_or("unknown version"));
535 fn unw(x: Option<&str>) -> &str {
536 x.unwrap_or("unknown")
538 println!("binary: {}", binary);
539 println!("commit-hash: {}", unw(commit_hash_str()));
540 println!("commit-date: {}", unw(commit_date_str()));
541 println!("host: {}", config::host_triple());
542 println!("release: {}", unw(release_str()));
546 fn usage(verbose: bool, include_unstable_options: bool) {
547 let groups = if verbose {
548 config::rustc_optgroups()
550 config::rustc_short_optgroups()
552 let groups: Vec<_> = groups.into_iter()
553 .filter(|x| include_unstable_options || x.is_stable())
554 .map(|x| x.opt_group)
556 let message = format!("Usage: rustc [OPTIONS] INPUT");
557 let extra_help = if verbose {
560 "\n --help -v Print the full set of options rustc accepts"
562 println!("{}\nAdditional help:
563 -C help Print codegen options
565 Print 'lint' options and default settings
566 -Z help Print internal \
567 options for debugging rustc{}\n",
568 getopts::usage(&message, &groups),
572 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
574 Available lint options:
575 -W <foo> Warn about <foo>
579 -F <foo> Forbid <foo> \
580 (deny, and deny all overrides)
584 fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
585 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
586 lints.sort_by(|x: &&Lint, y: &&Lint| {
587 match x.default_level.cmp(&y.default_level) {
588 // The sort doesn't case-fold but it's doubtful we care.
589 Equal => x.name.cmp(y.name),
596 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
597 -> Vec<(&'static str, Vec<lint::LintId>)> {
598 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
599 lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
600 &(y, _): &(&'static str, Vec<lint::LintId>)| {
606 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
609 .partition(|&(_, p)| p);
610 let plugin = sort_lints(plugin);
611 let builtin = sort_lints(builtin);
613 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
616 .partition(|&(_, _, p)| p);
617 let plugin_groups = sort_lint_groups(plugin_groups);
618 let builtin_groups = sort_lint_groups(builtin_groups);
620 let max_name_len = plugin.iter()
622 .map(|&s| s.name.chars().count())
625 let padded = |x: &str| {
626 let mut s = repeat(" ")
627 .take(max_name_len - x.chars().count())
628 .collect::<String>();
633 println!("Lint checks provided by rustc:\n");
634 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
635 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
637 let print_lints = |lints: Vec<&Lint>| {
639 let name = lint.name_lower().replace("_", "-");
640 println!(" {} {:7.7} {}",
642 lint.default_level.as_str(),
648 print_lints(builtin);
652 let max_name_len = plugin_groups.iter()
653 .chain(&builtin_groups)
654 .map(|&(s, _)| s.chars().count())
657 let padded = |x: &str| {
658 let mut s = repeat(" ")
659 .take(max_name_len - x.chars().count())
660 .collect::<String>();
665 println!("Lint groups provided by rustc:\n");
666 println!(" {} {}", padded("name"), "sub-lints");
667 println!(" {} {}", padded("----"), "---------");
669 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
670 for (name, to) in lints {
671 let name = name.to_lowercase().replace("_", "-");
672 let desc = to.into_iter()
673 .map(|x| x.as_str().replace("_", "-"))
674 .collect::<Vec<String>>()
676 println!(" {} {}", padded(&name[..]), desc);
681 print_lint_groups(builtin_groups);
683 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
684 (false, 0, _) | (false, _, 0) => {
685 println!("Compiler plugins can provide additional lints and lint groups. To see a \
686 listing of these, re-run `rustc -W help` with a crate filename.");
688 (false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
689 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
692 println!("Lint checks provided by plugins loaded by this crate:\n");
696 println!("Lint groups provided by plugins loaded by this crate:\n");
697 print_lint_groups(plugin_groups);
703 fn describe_debug_flags() {
704 println!("\nAvailable debug options:\n");
705 print_flag_list("-Z", config::DB_OPTIONS);
708 fn describe_codegen_flags() {
709 println!("\nAvailable codegen options:\n");
710 print_flag_list("-C", config::CG_OPTIONS);
713 fn print_flag_list<T>(cmdline_opt: &str,
714 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
715 let max_len = flag_list.iter()
716 .map(|&(name, _, opt_type_desc, _)| {
717 let extra_len = match opt_type_desc {
721 name.chars().count() + extra_len
726 for &(name, _, opt_type_desc, desc) in flag_list {
727 let (width, extra) = match opt_type_desc {
728 Some(..) => (max_len - 4, "=val"),
729 None => (max_len, ""),
731 println!(" {} {:>width$}{} -- {}",
733 name.replace("_", "-"),
740 /// Process command line options. Emits messages as appropriate. If compilation
741 /// should continue, returns a getopts::Matches object parsed from args, otherwise
743 pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
744 // Throw away the first argument, the name of the binary
745 let _binary = args.remove(0);
748 // user did not write `-v` nor `-Z unstable-options`, so do not
749 // include that extra information.
754 fn allows_unstable_options(matches: &getopts::Matches) -> bool {
755 let r = matches.opt_strs("Z");
756 r.iter().any(|x| *x == "unstable-options")
759 fn parse_all_options(args: &Vec<String>) -> getopts::Matches {
760 let all_groups: Vec<getopts::OptGroup> = config::rustc_optgroups()
762 .map(|x| x.opt_group)
764 match getopts::getopts(&args[..], &all_groups) {
766 if !allows_unstable_options(&m) {
767 // If -Z unstable-options was not specified, verify that
768 // no unstable options were present.
769 for opt in config::rustc_optgroups().into_iter().filter(|x| !x.is_stable()) {
770 let opt_name = if !opt.opt_group.long_name.is_empty() {
771 &opt.opt_group.long_name
773 &opt.opt_group.short_name
775 if m.opt_present(opt_name) {
776 early_error(errors::ColorConfig::Auto,
777 &format!("use of unstable option '{}' requires -Z \
785 Err(f) => early_error(errors::ColorConfig::Auto, &f.to_string()),
789 // As a speed optimization, first try to parse the command-line using just
790 // the stable options.
791 let matches = match getopts::getopts(&args[..], &config::optgroups()) {
792 Ok(ref m) if allows_unstable_options(m) => {
793 // If -Z unstable-options was specified, redo parsing with the
794 // unstable options to ensure that unstable options are defined
795 // in the returned getopts::Matches.
796 parse_all_options(&args)
800 // redo option parsing, including unstable options this time,
801 // in anticipation that the mishandled option was one of the
803 parse_all_options(&args)
807 if matches.opt_present("h") || matches.opt_present("help") {
808 usage(matches.opt_present("verbose"),
809 allows_unstable_options(&matches));
813 // Don't handle -W help here, because we might first load plugins.
815 let r = matches.opt_strs("Z");
816 if r.iter().any(|x| *x == "help") {
817 describe_debug_flags();
821 let cg_flags = matches.opt_strs("C");
822 if cg_flags.iter().any(|x| *x == "help") {
823 describe_codegen_flags();
827 if cg_flags.contains(&"passes=list".to_string()) {
829 ::llvm::LLVMRustPrintPasses();
834 if matches.opt_present("version") {
835 version("rustc", &matches);
842 fn parse_crate_attrs(sess: &Session, input: &Input) -> Vec<ast::Attribute> {
843 let result = match *input {
844 Input::File(ref ifile) => {
845 parse::parse_crate_attrs_from_file(ifile, Vec::new(), &sess.parse_sess)
847 Input::Str(ref src) => {
848 parse::parse_crate_attrs_from_source_str(driver::anon_src().to_string(),
854 result.into_iter().collect()
857 /// Run a procedure which will detect panics in the compiler and print nicer
858 /// error messages rather than just failing the test.
860 /// The diagnostic emitter yielded to the procedure should be used for reporting
861 /// errors of the compiler.
862 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
863 const STACK_SIZE: usize = 8 * 1024 * 1024; // 8MB
865 struct Sink(Arc<Mutex<Vec<u8>>>);
866 impl Write for Sink {
867 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
868 Write::write(&mut *self.0.lock().unwrap(), data)
870 fn flush(&mut self) -> io::Result<()> {
875 let data = Arc::new(Mutex::new(Vec::new()));
876 let err = Sink(data.clone());
878 let mut cfg = thread::Builder::new().name("rustc".to_string());
880 // FIXME: Hacks on hacks. If the env is trying to override the stack size
881 // then *don't* set it explicitly.
882 if env::var_os("RUST_MIN_STACK").is_none() {
883 cfg = cfg.stack_size(STACK_SIZE);
886 match cfg.spawn(move || {
887 io::set_panic(box err);
896 // Thread panicked without emitting a fatal diagnostic
897 if !value.is::<errors::FatalError>() {
898 let mut emitter = errors::emitter::BasicEmitter::stderr(errors::ColorConfig::Auto);
900 // a .span_bug or .bug call has already printed what
901 // it wants to print.
902 if !value.is::<errors::ExplicitBug>() {
903 emitter.emit(None, "unexpected panic", None, errors::Level::Bug);
906 let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
907 format!("we would appreciate a bug report: {}", BUG_REPORT_URL)];
909 emitter.emit(None, ¬e[..], None, errors::Level::Note)
911 if let None = env::var_os("RUST_BACKTRACE") {
913 "run with `RUST_BACKTRACE=1` for a backtrace",
915 errors::Level::Note);
918 println!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
921 // Panic so the process returns a failure code, but don't pollute the
922 // output with some unnecessary panic messages, we've already
923 // printed everything that we needed to.
924 io::set_panic(box io::sink());
930 pub fn diagnostics_registry() -> diagnostics::registry::Registry {
931 use syntax::diagnostics::registry::Registry;
933 let mut all_errors = Vec::new();
934 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
935 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
936 all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
937 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
938 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
939 all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
941 Registry::new(&*all_errors)
945 let result = run(env::args().collect());
946 process::exit(result as i32);