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/")]
24 #![cfg_attr(not(stage0), deny(warnings))]
26 #![feature(box_syntax)]
29 #![feature(rustc_diagnostic_macros)]
30 #![feature(rustc_private)]
31 #![feature(set_stdio)]
32 #![feature(staged_api)]
37 extern crate graphviz;
40 extern crate rustc_back;
41 extern crate rustc_borrowck;
42 extern crate rustc_passes;
43 extern crate rustc_front;
44 extern crate rustc_lint;
45 extern crate rustc_plugin;
46 extern crate rustc_privacy;
47 extern crate rustc_metadata;
48 extern crate rustc_mir;
49 extern crate rustc_resolve;
50 extern crate rustc_trans;
51 extern crate rustc_typeck;
52 extern crate serialize;
53 extern crate rustc_llvm as llvm;
58 extern crate syntax_ext;
60 use driver::CompileController;
61 use pretty::{PpMode, UserIdentifiedItem};
63 use rustc_resolve as resolve;
64 use rustc_trans::back::link;
65 use rustc_trans::save;
66 use rustc::session::{config, Session, build_session};
67 use rustc::session::config::{Input, PrintRequest, OutputType, ErrorOutputType};
68 use rustc::middle::cstore::CrateStore;
69 use rustc::lint::Lint;
71 use rustc_metadata::loader;
72 use rustc_metadata::cstore::CStore;
73 use rustc::util::common::time;
76 use std::cmp::Ordering::Equal;
77 use std::default::Default;
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.\
108 // Err(0) means compilation was stopped, but no errors were found.
109 // This would be better as a dedicated enum, but using try! is so convenient.
110 pub type CompileResult = Result<(), usize>;
112 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
121 fn abort_msg(err_count: usize) -> String {
123 0 => "aborting with no errors (maybe a bug?)".to_owned(),
124 1 => "aborting due to previous error".to_owned(),
125 e => format!("aborting due to {} previous errors", e),
129 pub fn abort_on_err<T>(result: Result<T, usize>, sess: &Session) -> T {
132 sess.fatal(&abort_msg(err_count));
138 pub fn run(args: Vec<String>) -> isize {
140 let (result, session) = run_compiler(&args, &mut RustcDefaultCalls);
141 if let Err(err_count) = result {
144 Some(sess) => sess.fatal(&abort_msg(err_count)),
147 errors::emitter::BasicEmitter::stderr(errors::ColorConfig::Auto);
148 emitter.emit(None, &abort_msg(err_count), None, errors::Level::Fatal);
149 panic!(errors::FatalError);
158 // Parse args and run the compiler. This is the primary entry point for rustc.
159 // See comments on CompilerCalls below for details about the callbacks argument.
160 pub fn run_compiler<'a>(args: &[String],
161 callbacks: &mut CompilerCalls<'a>)
162 -> (CompileResult, Option<Session>) {
163 macro_rules! do_or_return {($expr: expr, $sess: expr) => {
165 Compilation::Stop => return (Ok(()), $sess),
166 Compilation::Continue => {}
170 let matches = match handle_options(args.to_vec()) {
171 Some(matches) => matches,
172 None => return (Ok(()), None),
175 let sopts = config::build_session_options(&matches);
177 let descriptions = diagnostics_registry();
179 do_or_return!(callbacks.early_callback(&matches, &descriptions, sopts.error_format), None);
181 let (odir, ofile) = make_output(&matches);
182 let (input, input_file_path) = match make_input(&matches.free) {
183 Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
184 None => match callbacks.no_input(&matches, &sopts, &odir, &ofile, &descriptions) {
185 Some((input, input_file_path)) => (input, input_file_path),
186 None => return (Ok(()), None),
190 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
191 let sess = build_session(sopts, input_file_path, descriptions, cstore.clone());
192 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
193 let mut cfg = config::build_configuration(&sess);
194 target_features::add_configuration(&mut cfg, &sess);
196 do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile), Some(sess));
198 // It is somewhat unfortunate that this is hardwired in - this is forced by
199 // the fact that pretty_print_input requires the session by value.
200 let pretty = callbacks.parse_pretty(&sess, &matches);
202 Some((ppm, opt_uii)) => {
203 pretty::pretty_print_input(sess, &cstore, cfg, &input, ppm, opt_uii, ofile);
204 return (Ok(()), None);
211 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
212 let control = callbacks.build_controller(&sess);
213 (driver::compile_input(&sess, &cstore, cfg, &input, &odir, &ofile,
214 Some(plugins), control),
218 // Extract output directory and file from matches.
219 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
220 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
221 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
225 // Extract input (string or file and optional path) from matches.
226 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
227 if free_matches.len() == 1 {
228 let ifile = &free_matches[0][..];
230 let mut src = String::new();
231 io::stdin().read_to_string(&mut src).unwrap();
232 Some((Input::Str(src), None))
234 Some((Input::File(PathBuf::from(ifile)),
235 Some(PathBuf::from(ifile))))
242 // Whether to stop or continue compilation.
243 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
244 pub enum Compilation {
250 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
252 Compilation::Stop => Compilation::Stop,
253 Compilation::Continue => next(),
258 // A trait for customising the compilation process. Offers a number of hooks for
259 // executing custom code or customising input.
260 pub trait CompilerCalls<'a> {
261 // Hook for a callback early in the process of handling arguments. This will
262 // be called straight after options have been parsed but before anything
263 // else (e.g., selecting input and output).
264 fn early_callback(&mut self,
265 _: &getopts::Matches,
266 _: &diagnostics::registry::Registry,
269 Compilation::Continue
272 // Hook for a callback late in the process of handling arguments. This will
273 // be called just before actual compilation starts (and before build_controller
274 // is called), after all arguments etc. have been completely handled.
275 fn late_callback(&mut self,
276 _: &getopts::Matches,
282 Compilation::Continue
285 // Called after we extract the input from the arguments. Gives the implementer
286 // an opportunity to change the inputs or to add some custom input handling.
287 // The default behaviour is to simply pass through the inputs.
288 fn some_input(&mut self,
290 input_path: Option<PathBuf>)
291 -> (Input, Option<PathBuf>) {
295 // Called after we extract the input from the arguments if there is no valid
296 // input. Gives the implementer an opportunity to supply alternate input (by
297 // returning a Some value) or to add custom behaviour for this error such as
298 // emitting error messages. Returning None will cause compilation to stop
300 fn no_input(&mut self,
301 _: &getopts::Matches,
305 _: &diagnostics::registry::Registry)
306 -> Option<(Input, Option<PathBuf>)> {
310 // Parse pretty printing information from the arguments. The implementer can
311 // choose to ignore this (the default will return None) which will skip pretty
312 // printing. If you do want to pretty print, it is recommended to use the
313 // implementation of this method from RustcDefaultCalls.
314 // FIXME, this is a terrible bit of API. Parsing of pretty printing stuff
315 // should be done as part of the framework and the implementor should customise
316 // handling of it. However, that is not possible atm because pretty printing
317 // essentially goes off and takes another path through the compiler which
318 // means the session is either moved or not depending on what parse_pretty
319 // returns (we could fix this by cloning, but it's another hack). The proper
320 // solution is to handle pretty printing as if it were a compiler extension,
321 // extending CompileController to make this work (see for example the treatment
322 // of save-analysis in RustcDefaultCalls::build_controller).
323 fn parse_pretty(&mut self,
325 _matches: &getopts::Matches)
326 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
330 // Create a CompilController struct for controlling the behaviour of
332 fn build_controller(&mut self, &Session) -> CompileController<'a>;
335 // CompilerCalls instance for a regular rustc build.
336 #[derive(Copy, Clone)]
337 pub struct RustcDefaultCalls;
339 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
340 fn early_callback(&mut self,
341 matches: &getopts::Matches,
342 descriptions: &diagnostics::registry::Registry,
343 output: ErrorOutputType)
345 match matches.opt_str("explain") {
347 let normalised = if !code.starts_with("E") {
348 format!("E{0:0>4}", code)
352 match descriptions.find_description(&normalised) {
353 Some(ref description) => {
354 // Slice off the leading newline and print.
355 print!("{}", &description[1..]);
358 early_error(output, &format!("no extended information for {}", code));
361 return Compilation::Stop;
366 return Compilation::Continue;
369 fn no_input(&mut self,
370 matches: &getopts::Matches,
371 sopts: &config::Options,
372 odir: &Option<PathBuf>,
373 ofile: &Option<PathBuf>,
374 descriptions: &diagnostics::registry::Registry)
375 -> Option<(Input, Option<PathBuf>)> {
376 match matches.free.len() {
378 if sopts.describe_lints {
379 let mut ls = lint::LintStore::new();
380 rustc_lint::register_builtins(&mut ls, None);
381 describe_lints(&ls, false);
384 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
385 let sess = build_session(sopts.clone(), None, descriptions.clone(),
387 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
388 let should_stop = RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
389 if should_stop == Compilation::Stop {
392 early_error(sopts.error_format, "no input filename given");
394 1 => panic!("make_input should have provided valid inputs"),
395 _ => early_error(sopts.error_format, "multiple input filenames provided"),
401 fn parse_pretty(&mut self,
403 matches: &getopts::Matches)
404 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
405 let pretty = if sess.opts.debugging_opts.unstable_options {
406 matches.opt_default("pretty", "normal").map(|a| {
407 // stable pretty-print variants only
408 pretty::parse_pretty(sess, &a, false)
413 if pretty.is_none() && sess.unstable_options() {
414 matches.opt_str("unpretty").map(|a| {
415 // extended with unstable pretty-print variants
416 pretty::parse_pretty(sess, &a, true)
423 fn late_callback(&mut self,
424 matches: &getopts::Matches,
427 odir: &Option<PathBuf>,
428 ofile: &Option<PathBuf>)
430 RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
431 .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input))
434 fn build_controller(&mut self, sess: &Session) -> CompileController<'a> {
435 let mut control = CompileController::basic();
437 if sess.opts.parse_only || sess.opts.debugging_opts.show_span.is_some() ||
438 sess.opts.debugging_opts.ast_json_noexpand {
439 control.after_parse.stop = Compilation::Stop;
442 if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
443 control.after_write_deps.stop = Compilation::Stop;
446 if sess.opts.no_trans {
447 control.after_analysis.stop = Compilation::Stop;
450 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe) {
451 control.after_llvm.stop = Compilation::Stop;
454 if sess.opts.debugging_opts.save_analysis {
455 control.after_analysis.callback = box |state| {
456 time(state.session.time_passes(), "save analysis", || {
457 save::process_crate(state.tcx.unwrap(),
459 state.krate.unwrap(),
460 state.analysis.unwrap(),
461 state.crate_name.unwrap(),
465 control.make_glob_map = resolve::MakeGlobMap::Yes;
472 impl RustcDefaultCalls {
473 pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation {
474 let r = matches.opt_strs("Z");
475 if r.contains(&("ls".to_string())) {
477 &Input::File(ref ifile) => {
478 let path = &(*ifile);
479 let mut v = Vec::new();
480 loader::list_file_metadata(&sess.target.target, path, &mut v)
482 println!("{}", String::from_utf8(v).unwrap());
485 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
488 return Compilation::Stop;
491 return Compilation::Continue;
495 fn print_crate_info(sess: &Session,
496 input: Option<&Input>,
497 odir: &Option<PathBuf>,
498 ofile: &Option<PathBuf>)
500 if sess.opts.prints.is_empty() {
501 return Compilation::Continue;
504 let attrs = input.map(|input| parse_crate_attrs(sess, input));
505 for req in &sess.opts.prints {
507 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
508 PrintRequest::FileNames |
509 PrintRequest::CrateName => {
510 let input = match input {
511 Some(input) => input,
512 None => early_error(ErrorOutputType::default(), "no input file provided"),
514 let attrs = attrs.as_ref().unwrap();
515 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
516 let id = link::find_crate_name(Some(sess), attrs, input);
517 if *req == PrintRequest::CrateName {
521 let crate_types = driver::collect_crate_types(sess, attrs);
522 let metadata = driver::collect_crate_metadata(sess, attrs);
523 *sess.crate_metadata.borrow_mut() = metadata;
524 for &style in &crate_types {
525 let fname = link::filename_for_input(sess, style, &id, &t_outputs);
534 return Compilation::Stop;
538 /// Returns a version string such as "0.12.0-dev".
539 pub fn release_str() -> Option<&'static str> {
540 option_env!("CFG_RELEASE")
543 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
544 pub fn commit_hash_str() -> Option<&'static str> {
545 option_env!("CFG_VER_HASH")
548 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
549 pub fn commit_date_str() -> Option<&'static str> {
550 option_env!("CFG_VER_DATE")
553 /// Prints version information
554 pub fn version(binary: &str, matches: &getopts::Matches) {
555 let verbose = matches.opt_present("verbose");
559 option_env!("CFG_VERSION").unwrap_or("unknown version"));
561 fn unw(x: Option<&str>) -> &str {
562 x.unwrap_or("unknown")
564 println!("binary: {}", binary);
565 println!("commit-hash: {}", unw(commit_hash_str()));
566 println!("commit-date: {}", unw(commit_date_str()));
567 println!("host: {}", config::host_triple());
568 println!("release: {}", unw(release_str()));
572 fn usage(verbose: bool, include_unstable_options: bool) {
573 let groups = if verbose {
574 config::rustc_optgroups()
576 config::rustc_short_optgroups()
578 let groups: Vec<_> = groups.into_iter()
579 .filter(|x| include_unstable_options || x.is_stable())
580 .map(|x| x.opt_group)
582 let message = format!("Usage: rustc [OPTIONS] INPUT");
583 let extra_help = if verbose {
586 "\n --help -v Print the full set of options rustc accepts"
588 println!("{}\nAdditional help:
589 -C help Print codegen options
591 Print 'lint' options and default settings
592 -Z help Print internal \
593 options for debugging rustc{}\n",
594 getopts::usage(&message, &groups),
598 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
600 Available lint options:
601 -W <foo> Warn about <foo>
605 -F <foo> Forbid <foo> \
606 (deny, and deny all overrides)
610 fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
611 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
612 lints.sort_by(|x: &&Lint, y: &&Lint| {
613 match x.default_level.cmp(&y.default_level) {
614 // The sort doesn't case-fold but it's doubtful we care.
615 Equal => x.name.cmp(y.name),
622 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
623 -> Vec<(&'static str, Vec<lint::LintId>)> {
624 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
625 lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
626 &(y, _): &(&'static str, Vec<lint::LintId>)| {
632 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
635 .partition(|&(_, p)| p);
636 let plugin = sort_lints(plugin);
637 let builtin = sort_lints(builtin);
639 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
642 .partition(|&(_, _, p)| p);
643 let plugin_groups = sort_lint_groups(plugin_groups);
644 let builtin_groups = sort_lint_groups(builtin_groups);
646 let max_name_len = plugin.iter()
648 .map(|&s| s.name.chars().count())
651 let padded = |x: &str| {
652 let mut s = repeat(" ")
653 .take(max_name_len - x.chars().count())
654 .collect::<String>();
659 println!("Lint checks provided by rustc:\n");
660 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
661 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
663 let print_lints = |lints: Vec<&Lint>| {
665 let name = lint.name_lower().replace("_", "-");
666 println!(" {} {:7.7} {}",
668 lint.default_level.as_str(),
674 print_lints(builtin);
678 let max_name_len = max("warnings".len(),
680 .chain(&builtin_groups)
681 .map(|&(s, _)| s.chars().count())
685 let padded = |x: &str| {
686 let mut s = repeat(" ")
687 .take(max_name_len - x.chars().count())
688 .collect::<String>();
693 println!("Lint groups provided by rustc:\n");
694 println!(" {} {}", padded("name"), "sub-lints");
695 println!(" {} {}", padded("----"), "---------");
696 println!(" {} {}", padded("warnings"), "all built-in lints");
698 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
699 for (name, to) in lints {
700 let name = name.to_lowercase().replace("_", "-");
701 let desc = to.into_iter()
702 .map(|x| x.as_str().replace("_", "-"))
703 .collect::<Vec<String>>()
705 println!(" {} {}", padded(&name[..]), desc);
710 print_lint_groups(builtin_groups);
712 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
713 (false, 0, _) | (false, _, 0) => {
714 println!("Compiler plugins can provide additional lints and lint groups. To see a \
715 listing of these, re-run `rustc -W help` with a crate filename.");
717 (false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
718 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
721 println!("Lint checks provided by plugins loaded by this crate:\n");
725 println!("Lint groups provided by plugins loaded by this crate:\n");
726 print_lint_groups(plugin_groups);
732 fn describe_debug_flags() {
733 println!("\nAvailable debug options:\n");
734 print_flag_list("-Z", config::DB_OPTIONS);
737 fn describe_codegen_flags() {
738 println!("\nAvailable codegen options:\n");
739 print_flag_list("-C", config::CG_OPTIONS);
742 fn print_flag_list<T>(cmdline_opt: &str,
743 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
744 let max_len = flag_list.iter()
745 .map(|&(name, _, opt_type_desc, _)| {
746 let extra_len = match opt_type_desc {
750 name.chars().count() + extra_len
755 for &(name, _, opt_type_desc, desc) in flag_list {
756 let (width, extra) = match opt_type_desc {
757 Some(..) => (max_len - 4, "=val"),
758 None => (max_len, ""),
760 println!(" {} {:>width$}{} -- {}",
762 name.replace("_", "-"),
769 /// Process command line options. Emits messages as appropriate. If compilation
770 /// should continue, returns a getopts::Matches object parsed from args, otherwise
772 pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
773 // Throw away the first argument, the name of the binary
774 let _binary = args.remove(0);
777 // user did not write `-v` nor `-Z unstable-options`, so do not
778 // include that extra information.
783 fn allows_unstable_options(matches: &getopts::Matches) -> bool {
784 let r = matches.opt_strs("Z");
785 r.iter().any(|x| *x == "unstable-options")
788 fn parse_all_options(args: &Vec<String>) -> getopts::Matches {
789 let all_groups: Vec<getopts::OptGroup> = config::rustc_optgroups()
791 .map(|x| x.opt_group)
793 match getopts::getopts(&args[..], &all_groups) {
795 if !allows_unstable_options(&m) {
796 // If -Z unstable-options was not specified, verify that
797 // no unstable options were present.
798 for opt in config::rustc_optgroups().into_iter().filter(|x| !x.is_stable()) {
799 let opt_name = if !opt.opt_group.long_name.is_empty() {
800 &opt.opt_group.long_name
802 &opt.opt_group.short_name
804 if m.opt_present(opt_name) {
805 early_error(ErrorOutputType::default(),
806 &format!("use of unstable option '{}' requires -Z \
814 Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
818 // As a speed optimization, first try to parse the command-line using just
819 // the stable options.
820 let matches = match getopts::getopts(&args[..], &config::optgroups()) {
821 Ok(ref m) if allows_unstable_options(m) => {
822 // If -Z unstable-options was specified, redo parsing with the
823 // unstable options to ensure that unstable options are defined
824 // in the returned getopts::Matches.
825 parse_all_options(&args)
829 // redo option parsing, including unstable options this time,
830 // in anticipation that the mishandled option was one of the
832 parse_all_options(&args)
836 if matches.opt_present("h") || matches.opt_present("help") {
837 usage(matches.opt_present("verbose"),
838 allows_unstable_options(&matches));
842 // Don't handle -W help here, because we might first load plugins.
844 let r = matches.opt_strs("Z");
845 if r.iter().any(|x| *x == "help") {
846 describe_debug_flags();
850 let cg_flags = matches.opt_strs("C");
851 if cg_flags.iter().any(|x| *x == "help") {
852 describe_codegen_flags();
856 if cg_flags.contains(&"passes=list".to_string()) {
858 ::llvm::LLVMRustPrintPasses();
863 if matches.opt_present("version") {
864 version("rustc", &matches);
871 fn parse_crate_attrs(sess: &Session, input: &Input) -> Vec<ast::Attribute> {
872 let result = match *input {
873 Input::File(ref ifile) => {
874 parse::parse_crate_attrs_from_file(ifile, Vec::new(), &sess.parse_sess)
876 Input::Str(ref src) => {
877 parse::parse_crate_attrs_from_source_str(driver::anon_src().to_string(),
883 result.into_iter().collect()
886 /// Run a procedure which will detect panics in the compiler and print nicer
887 /// error messages rather than just failing the test.
889 /// The diagnostic emitter yielded to the procedure should be used for reporting
890 /// errors of the compiler.
891 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
892 const STACK_SIZE: usize = 8 * 1024 * 1024; // 8MB
894 struct Sink(Arc<Mutex<Vec<u8>>>);
895 impl Write for Sink {
896 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
897 Write::write(&mut *self.0.lock().unwrap(), data)
899 fn flush(&mut self) -> io::Result<()> {
904 let data = Arc::new(Mutex::new(Vec::new()));
905 let err = Sink(data.clone());
907 let mut cfg = thread::Builder::new().name("rustc".to_string());
909 // FIXME: Hacks on hacks. If the env is trying to override the stack size
910 // then *don't* set it explicitly.
911 if env::var_os("RUST_MIN_STACK").is_none() {
912 cfg = cfg.stack_size(STACK_SIZE);
915 match cfg.spawn(move || {
916 io::set_panic(box err);
925 // Thread panicked without emitting a fatal diagnostic
926 if !value.is::<errors::FatalError>() {
927 let mut emitter = errors::emitter::BasicEmitter::stderr(errors::ColorConfig::Auto);
929 // a .span_bug or .bug call has already printed what
930 // it wants to print.
931 if !value.is::<errors::ExplicitBug>() {
932 emitter.emit(None, "unexpected panic", None, errors::Level::Bug);
935 let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
936 format!("we would appreciate a bug report: {}", BUG_REPORT_URL)];
938 emitter.emit(None, ¬e[..], None, errors::Level::Note)
940 if let None = env::var_os("RUST_BACKTRACE") {
942 "run with `RUST_BACKTRACE=1` for a backtrace",
944 errors::Level::Note);
947 println!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
950 // Panic so the process returns a failure code, but don't pollute the
951 // output with some unnecessary panic messages, we've already
952 // printed everything that we needed to.
953 io::set_panic(box io::sink());
959 pub fn diagnostics_registry() -> diagnostics::registry::Registry {
960 use syntax::diagnostics::registry::Registry;
962 let mut all_errors = Vec::new();
963 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
964 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
965 all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
966 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
967 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
968 all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
970 Registry::new(&*all_errors)
974 let result = run(env::args().collect());
975 process::exit(result as i32);