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 pub use syntax::diagnostic;
64 use driver::CompileController;
65 use pretty::{PpMode, UserIdentifiedItem};
67 use rustc_resolve as resolve;
68 use rustc_trans::back::link;
69 use rustc_trans::save;
70 use rustc::session::{config, Session, build_session};
71 use rustc::session::config::{Input, PrintRequest, OutputType};
72 use rustc::middle::cstore::CrateStore;
73 use rustc::lint::Lint;
75 use rustc_metadata::loader;
76 use rustc_metadata::cstore::CStore;
77 use rustc::util::common::time;
79 use std::cmp::Ordering::Equal;
81 use std::io::{self, Read, Write};
82 use std::iter::repeat;
83 use std::path::PathBuf;
87 use std::sync::{Arc, Mutex};
90 use rustc::session::early_error;
94 use syntax::diagnostic::Emitter;
95 use syntax::diagnostics;
96 use syntax::parse::token;
103 pub mod target_features;
106 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
110 // This is a terrible hack. Our stage0 is older than 1.4 and does not
111 // support DST coercions, so this function performs the corecion
112 // manually. This should go away.
113 pub fn cstore_to_cratestore(a: Rc<CStore>) -> Rc<for<'s> CrateStore<'s>>
116 use std::raw::TraitObject;
118 let TraitObject { vtable, .. } =
119 mem::transmute::<&for<'s> CrateStore<'s>, TraitObject>(&*a);
120 mem::transmute(TraitObject {
121 data: mem::transmute(a),
127 pub fn run(args: Vec<String>) -> isize {
128 monitor(move || run_compiler(&args, &mut RustcDefaultCalls));
132 // Parse args and run the compiler. This is the primary entry point for rustc.
133 // See comments on CompilerCalls below for details about the callbacks argument.
134 pub fn run_compiler<'a>(args: &[String], callbacks: &mut CompilerCalls<'a>) {
135 macro_rules! do_or_return {($expr: expr) => {
137 Compilation::Stop => return,
138 Compilation::Continue => {}
142 let matches = match handle_options(args.to_vec()) {
143 Some(matches) => matches,
147 let sopts = config::build_session_options(&matches);
149 let descriptions = diagnostics_registry();
151 do_or_return!(callbacks.early_callback(&matches, &descriptions, sopts.color));
153 let (odir, ofile) = make_output(&matches);
154 let (input, input_file_path) = match make_input(&matches.free) {
155 Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
156 None => match callbacks.no_input(&matches, &sopts, &odir, &ofile, &descriptions) {
157 Some((input, input_file_path)) => (input, input_file_path),
162 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
163 let cstore_ = cstore_to_cratestore(cstore.clone());
164 let mut sess = build_session(sopts, input_file_path, descriptions, cstore_);
165 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
166 if sess.unstable_options() {
167 sess.opts.show_span = matches.opt_str("show-span");
169 let mut cfg = config::build_configuration(&sess);
170 target_features::add_configuration(&mut cfg, &sess);
172 do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile));
174 // It is somewhat unfortunate that this is hardwired in - this is forced by
175 // the fact that pretty_print_input requires the session by value.
176 let pretty = callbacks.parse_pretty(&sess, &matches);
178 Some((ppm, opt_uii)) => {
179 pretty::pretty_print_input(sess, &cstore, cfg, &input, ppm, opt_uii, ofile);
187 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
188 let control = callbacks.build_controller(&sess);
189 driver::compile_input(sess, &cstore, cfg, &input, &odir, &ofile,
190 Some(plugins), control);
193 // Extract output directory and file from matches.
194 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
195 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
196 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
200 // Extract input (string or file and optional path) from matches.
201 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
202 if free_matches.len() == 1 {
203 let ifile = &free_matches[0][..];
205 let mut src = String::new();
206 io::stdin().read_to_string(&mut src).unwrap();
207 Some((Input::Str(src), None))
209 Some((Input::File(PathBuf::from(ifile)),
210 Some(PathBuf::from(ifile))))
217 // Whether to stop or continue compilation.
218 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
219 pub enum Compilation {
225 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
227 Compilation::Stop => Compilation::Stop,
228 Compilation::Continue => next(),
233 // A trait for customising the compilation process. Offers a number of hooks for
234 // executing custom code or customising input.
235 pub trait CompilerCalls<'a> {
236 // Hook for a callback early in the process of handling arguments. This will
237 // be called straight after options have been parsed but before anything
238 // else (e.g., selecting input and output).
239 fn early_callback(&mut self,
240 _: &getopts::Matches,
241 _: &diagnostics::registry::Registry,
242 _: diagnostic::ColorConfig)
244 Compilation::Continue
247 // Hook for a callback late in the process of handling arguments. This will
248 // be called just before actual compilation starts (and before build_controller
249 // is called), after all arguments etc. have been completely handled.
250 fn late_callback(&mut self,
251 _: &getopts::Matches,
257 Compilation::Continue
260 // Called after we extract the input from the arguments. Gives the implementer
261 // an opportunity to change the inputs or to add some custom input handling.
262 // The default behaviour is to simply pass through the inputs.
263 fn some_input(&mut self,
265 input_path: Option<PathBuf>)
266 -> (Input, Option<PathBuf>) {
270 // Called after we extract the input from the arguments if there is no valid
271 // input. Gives the implementer an opportunity to supply alternate input (by
272 // returning a Some value) or to add custom behaviour for this error such as
273 // emitting error messages. Returning None will cause compilation to stop
275 fn no_input(&mut self,
276 _: &getopts::Matches,
280 _: &diagnostics::registry::Registry)
281 -> Option<(Input, Option<PathBuf>)> {
285 // Parse pretty printing information from the arguments. The implementer can
286 // choose to ignore this (the default will return None) which will skip pretty
287 // printing. If you do want to pretty print, it is recommended to use the
288 // implementation of this method from RustcDefaultCalls.
289 // FIXME, this is a terrible bit of API. Parsing of pretty printing stuff
290 // should be done as part of the framework and the implementor should customise
291 // handling of it. However, that is not possible atm because pretty printing
292 // essentially goes off and takes another path through the compiler which
293 // means the session is either moved or not depending on what parse_pretty
294 // returns (we could fix this by cloning, but it's another hack). The proper
295 // solution is to handle pretty printing as if it were a compiler extension,
296 // extending CompileController to make this work (see for example the treatment
297 // of save-analysis in RustcDefaultCalls::build_controller).
298 fn parse_pretty(&mut self,
300 _matches: &getopts::Matches)
301 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
305 // Create a CompilController struct for controlling the behaviour of
307 fn build_controller(&mut self, &Session) -> CompileController<'a>;
310 // CompilerCalls instance for a regular rustc build.
311 #[derive(Copy, Clone)]
312 pub struct RustcDefaultCalls;
314 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
315 fn early_callback(&mut self,
316 matches: &getopts::Matches,
317 descriptions: &diagnostics::registry::Registry,
318 color: diagnostic::ColorConfig)
320 match matches.opt_str("explain") {
322 let normalised = if !code.starts_with("E") {
323 format!("E{0:0>4}", code)
327 match descriptions.find_description(&normalised) {
328 Some(ref description) => {
329 // Slice off the leading newline and print.
330 print!("{}", &description[1..]);
333 early_error(color, &format!("no extended information for {}", code));
336 return Compilation::Stop;
341 return Compilation::Continue;
344 fn no_input(&mut self,
345 matches: &getopts::Matches,
346 sopts: &config::Options,
347 odir: &Option<PathBuf>,
348 ofile: &Option<PathBuf>,
349 descriptions: &diagnostics::registry::Registry)
350 -> Option<(Input, Option<PathBuf>)> {
351 match matches.free.len() {
353 if sopts.describe_lints {
354 let mut ls = lint::LintStore::new();
355 rustc_lint::register_builtins(&mut ls, None);
356 describe_lints(&ls, false);
359 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
360 let cstore_ = cstore_to_cratestore(cstore.clone());
361 let sess = build_session(sopts.clone(), None, descriptions.clone(), cstore_);
362 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
363 let should_stop = RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
364 if should_stop == Compilation::Stop {
367 early_error(sopts.color, "no input filename given");
369 1 => panic!("make_input should have provided valid inputs"),
370 _ => early_error(sopts.color, "multiple input filenames provided"),
376 fn parse_pretty(&mut self,
378 matches: &getopts::Matches)
379 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
380 let pretty = if sess.opts.debugging_opts.unstable_options {
381 matches.opt_default("pretty", "normal").map(|a| {
382 // stable pretty-print variants only
383 pretty::parse_pretty(sess, &a, false)
388 if pretty.is_none() && sess.unstable_options() {
389 matches.opt_str("unpretty").map(|a| {
390 // extended with unstable pretty-print variants
391 pretty::parse_pretty(sess, &a, true)
398 fn late_callback(&mut self,
399 matches: &getopts::Matches,
402 odir: &Option<PathBuf>,
403 ofile: &Option<PathBuf>)
405 RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
406 .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input))
409 fn build_controller(&mut self, sess: &Session) -> CompileController<'a> {
410 let mut control = CompileController::basic();
412 if sess.opts.parse_only || sess.opts.show_span.is_some() ||
413 sess.opts.debugging_opts.ast_json_noexpand {
414 control.after_parse.stop = Compilation::Stop;
417 if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
418 control.after_write_deps.stop = Compilation::Stop;
421 if sess.opts.no_trans {
422 control.after_analysis.stop = Compilation::Stop;
425 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe) {
426 control.after_llvm.stop = Compilation::Stop;
429 if sess.opts.debugging_opts.save_analysis {
430 control.after_analysis.callback = box |state| {
431 time(state.session.time_passes(), "save analysis", || {
432 save::process_crate(state.tcx.unwrap(),
434 state.krate.unwrap(),
435 state.analysis.unwrap(),
436 state.crate_name.unwrap(),
440 control.make_glob_map = resolve::MakeGlobMap::Yes;
447 impl RustcDefaultCalls {
448 pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation {
449 let r = matches.opt_strs("Z");
450 if r.contains(&("ls".to_string())) {
452 &Input::File(ref ifile) => {
453 let path = &(*ifile);
454 let mut v = Vec::new();
455 loader::list_file_metadata(&sess.target.target, path, &mut v)
457 println!("{}", String::from_utf8(v).unwrap());
460 early_error(sess.opts.color, "cannot list metadata for stdin");
463 return Compilation::Stop;
466 return Compilation::Continue;
470 fn print_crate_info(sess: &Session,
471 input: Option<&Input>,
472 odir: &Option<PathBuf>,
473 ofile: &Option<PathBuf>)
475 if sess.opts.prints.is_empty() {
476 return Compilation::Continue;
479 let attrs = input.map(|input| parse_crate_attrs(sess, input));
480 for req in &sess.opts.prints {
482 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
483 PrintRequest::FileNames |
484 PrintRequest::CrateName => {
485 let input = match input {
486 Some(input) => input,
487 None => early_error(sess.opts.color, "no input file provided"),
489 let attrs = attrs.as_ref().unwrap();
490 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
491 let id = link::find_crate_name(Some(sess), attrs, input);
492 if *req == PrintRequest::CrateName {
496 let crate_types = driver::collect_crate_types(sess, attrs);
497 let metadata = driver::collect_crate_metadata(sess, attrs);
498 *sess.crate_metadata.borrow_mut() = metadata;
499 for &style in &crate_types {
500 let fname = link::filename_for_input(sess, style, &id, &t_outputs);
509 return Compilation::Stop;
513 /// Returns a version string such as "0.12.0-dev".
514 pub fn release_str() -> Option<&'static str> {
515 option_env!("CFG_RELEASE")
518 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
519 pub fn commit_hash_str() -> Option<&'static str> {
520 option_env!("CFG_VER_HASH")
523 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
524 pub fn commit_date_str() -> Option<&'static str> {
525 option_env!("CFG_VER_DATE")
528 /// Prints version information
529 pub fn version(binary: &str, matches: &getopts::Matches) {
530 let verbose = matches.opt_present("verbose");
534 option_env!("CFG_VERSION").unwrap_or("unknown version"));
536 fn unw(x: Option<&str>) -> &str {
537 x.unwrap_or("unknown")
539 println!("binary: {}", binary);
540 println!("commit-hash: {}", unw(commit_hash_str()));
541 println!("commit-date: {}", unw(commit_date_str()));
542 println!("host: {}", config::host_triple());
543 println!("release: {}", unw(release_str()));
547 fn usage(verbose: bool, include_unstable_options: bool) {
548 let groups = if verbose {
549 config::rustc_optgroups()
551 config::rustc_short_optgroups()
553 let groups: Vec<_> = groups.into_iter()
554 .filter(|x| include_unstable_options || x.is_stable())
555 .map(|x| x.opt_group)
557 let message = format!("Usage: rustc [OPTIONS] INPUT");
558 let extra_help = if verbose {
561 "\n --help -v Print the full set of options rustc accepts"
563 println!("{}\nAdditional help:
564 -C help Print codegen options
566 Print 'lint' options and default settings
567 -Z help Print internal \
568 options for debugging rustc{}\n",
569 getopts::usage(&message, &groups),
573 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
575 Available lint options:
576 -W <foo> Warn about <foo>
580 -F <foo> Forbid <foo> \
581 (deny, and deny all overrides)
585 fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
586 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
587 lints.sort_by(|x: &&Lint, y: &&Lint| {
588 match x.default_level.cmp(&y.default_level) {
589 // The sort doesn't case-fold but it's doubtful we care.
590 Equal => x.name.cmp(y.name),
597 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
598 -> Vec<(&'static str, Vec<lint::LintId>)> {
599 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
600 lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
601 &(y, _): &(&'static str, Vec<lint::LintId>)| {
607 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
610 .partition(|&(_, p)| p);
611 let plugin = sort_lints(plugin);
612 let builtin = sort_lints(builtin);
614 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
617 .partition(|&(_, _, p)| p);
618 let plugin_groups = sort_lint_groups(plugin_groups);
619 let builtin_groups = sort_lint_groups(builtin_groups);
621 let max_name_len = plugin.iter()
623 .map(|&s| s.name.chars().count())
626 let padded = |x: &str| {
627 let mut s = repeat(" ")
628 .take(max_name_len - x.chars().count())
629 .collect::<String>();
634 println!("Lint checks provided by rustc:\n");
635 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
636 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
638 let print_lints = |lints: Vec<&Lint>| {
640 let name = lint.name_lower().replace("_", "-");
641 println!(" {} {:7.7} {}",
643 lint.default_level.as_str(),
649 print_lints(builtin);
653 let max_name_len = plugin_groups.iter()
654 .chain(&builtin_groups)
655 .map(|&(s, _)| s.chars().count())
658 let padded = |x: &str| {
659 let mut s = repeat(" ")
660 .take(max_name_len - x.chars().count())
661 .collect::<String>();
666 println!("Lint groups provided by rustc:\n");
667 println!(" {} {}", padded("name"), "sub-lints");
668 println!(" {} {}", padded("----"), "---------");
670 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
671 for (name, to) in lints {
672 let name = name.to_lowercase().replace("_", "-");
673 let desc = to.into_iter()
674 .map(|x| x.as_str().replace("_", "-"))
675 .collect::<Vec<String>>()
677 println!(" {} {}", padded(&name[..]), desc);
682 print_lint_groups(builtin_groups);
684 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
685 (false, 0, _) | (false, _, 0) => {
686 println!("Compiler plugins can provide additional lints and lint groups. To see a \
687 listing of these, re-run `rustc -W help` with a crate filename.");
689 (false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
690 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
693 println!("Lint checks provided by plugins loaded by this crate:\n");
697 println!("Lint groups provided by plugins loaded by this crate:\n");
698 print_lint_groups(plugin_groups);
704 fn describe_debug_flags() {
705 println!("\nAvailable debug options:\n");
706 print_flag_list("-Z", config::DB_OPTIONS);
709 fn describe_codegen_flags() {
710 println!("\nAvailable codegen options:\n");
711 print_flag_list("-C", config::CG_OPTIONS);
714 fn print_flag_list<T>(cmdline_opt: &str,
715 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
716 let max_len = flag_list.iter()
717 .map(|&(name, _, opt_type_desc, _)| {
718 let extra_len = match opt_type_desc {
722 name.chars().count() + extra_len
727 for &(name, _, opt_type_desc, desc) in flag_list {
728 let (width, extra) = match opt_type_desc {
729 Some(..) => (max_len - 4, "=val"),
730 None => (max_len, ""),
732 println!(" {} {:>width$}{} -- {}",
734 name.replace("_", "-"),
741 /// Process command line options. Emits messages as appropriate. If compilation
742 /// should continue, returns a getopts::Matches object parsed from args, otherwise
744 pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
745 // Throw away the first argument, the name of the binary
746 let _binary = args.remove(0);
749 // user did not write `-v` nor `-Z unstable-options`, so do not
750 // include that extra information.
755 fn allows_unstable_options(matches: &getopts::Matches) -> bool {
756 let r = matches.opt_strs("Z");
757 r.iter().any(|x| *x == "unstable-options")
760 fn parse_all_options(args: &Vec<String>) -> getopts::Matches {
761 let all_groups: Vec<getopts::OptGroup> = config::rustc_optgroups()
763 .map(|x| x.opt_group)
765 match getopts::getopts(&args[..], &all_groups) {
767 if !allows_unstable_options(&m) {
768 // If -Z unstable-options was not specified, verify that
769 // no unstable options were present.
770 for opt in config::rustc_optgroups().into_iter().filter(|x| !x.is_stable()) {
771 let opt_name = if !opt.opt_group.long_name.is_empty() {
772 &opt.opt_group.long_name
774 &opt.opt_group.short_name
776 if m.opt_present(opt_name) {
777 early_error(diagnostic::Auto,
778 &format!("use of unstable option '{}' requires -Z \
786 Err(f) => early_error(diagnostic::Auto, &f.to_string()),
790 // As a speed optimization, first try to parse the command-line using just
791 // the stable options.
792 let matches = match getopts::getopts(&args[..], &config::optgroups()) {
793 Ok(ref m) if allows_unstable_options(m) => {
794 // If -Z unstable-options was specified, redo parsing with the
795 // unstable options to ensure that unstable options are defined
796 // in the returned getopts::Matches.
797 parse_all_options(&args)
801 // redo option parsing, including unstable options this time,
802 // in anticipation that the mishandled option was one of the
804 parse_all_options(&args)
808 if matches.opt_present("h") || matches.opt_present("help") {
809 usage(matches.opt_present("verbose"),
810 allows_unstable_options(&matches));
814 // Don't handle -W help here, because we might first load plugins.
816 let r = matches.opt_strs("Z");
817 if r.iter().any(|x| *x == "help") {
818 describe_debug_flags();
822 let cg_flags = matches.opt_strs("C");
823 if cg_flags.iter().any(|x| *x == "help") {
824 describe_codegen_flags();
828 if cg_flags.contains(&"passes=list".to_string()) {
830 ::llvm::LLVMRustPrintPasses();
835 if matches.opt_present("version") {
836 version("rustc", &matches);
843 fn parse_crate_attrs(sess: &Session, input: &Input) -> Vec<ast::Attribute> {
844 let result = match *input {
845 Input::File(ref ifile) => {
846 parse::parse_crate_attrs_from_file(ifile, Vec::new(), &sess.parse_sess)
848 Input::Str(ref src) => {
849 parse::parse_crate_attrs_from_source_str(driver::anon_src().to_string(),
855 result.into_iter().collect()
858 /// Run a procedure which will detect panics in the compiler and print nicer
859 /// error messages rather than just failing the test.
861 /// The diagnostic emitter yielded to the procedure should be used for reporting
862 /// errors of the compiler.
863 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
864 const STACK_SIZE: usize = 8 * 1024 * 1024; // 8MB
866 struct Sink(Arc<Mutex<Vec<u8>>>);
867 impl Write for Sink {
868 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
869 Write::write(&mut *self.0.lock().unwrap(), data)
871 fn flush(&mut self) -> io::Result<()> {
876 let data = Arc::new(Mutex::new(Vec::new()));
877 let err = Sink(data.clone());
879 let mut cfg = thread::Builder::new().name("rustc".to_string());
881 // FIXME: Hacks on hacks. If the env is trying to override the stack size
882 // then *don't* set it explicitly.
883 if env::var_os("RUST_MIN_STACK").is_none() {
884 cfg = cfg.stack_size(STACK_SIZE);
887 match cfg.spawn(move || {
888 io::set_panic(box err);
897 // Thread panicked without emitting a fatal diagnostic
898 if !value.is::<diagnostic::FatalError>() {
899 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
901 // a .span_bug or .bug call has already printed what
902 // it wants to print.
903 if !value.is::<diagnostic::ExplicitBug>() {
904 emitter.emit(None, "unexpected panic", None, diagnostic::Bug);
907 let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
908 format!("we would appreciate a bug report: {}", BUG_REPORT_URL)];
910 emitter.emit(None, ¬e[..], None, diagnostic::Note)
912 if let None = env::var_os("RUST_BACKTRACE") {
914 "run with `RUST_BACKTRACE=1` for a backtrace",
919 println!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
922 // Panic so the process returns a failure code, but don't pollute the
923 // output with some unnecessary panic messages, we've already
924 // printed everything that we needed to.
925 io::set_panic(box io::sink());
931 pub fn diagnostics_registry() -> diagnostics::registry::Registry {
932 use syntax::diagnostics::registry::Registry;
934 let mut all_errors = Vec::new();
935 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
936 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
937 all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
938 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
939 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
940 all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
942 Registry::new(&*all_errors)
946 let result = run(env::args().collect());
947 process::exit(result as i32);