]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/lib.rs
Fix hotplug backend and add test
[rust.git] / src / librustc_driver / lib.rs
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.
4 //
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.
10
11 //! The Rust compiler.
12 //!
13 //! # Note
14 //!
15 //! This API is completely unstable and subject to change.
16
17 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
18       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
19       html_root_url = "https://doc.rust-lang.org/nightly/")]
20 #![deny(warnings)]
21
22 #![feature(box_syntax)]
23 #![cfg_attr(unix, feature(libc))]
24 #![feature(quote)]
25 #![feature(rustc_diagnostic_macros)]
26 #![feature(set_stdio)]
27
28 extern crate arena;
29 extern crate getopts;
30 extern crate graphviz;
31 extern crate env_logger;
32 #[cfg(unix)]
33 extern crate libc;
34 extern crate rustc;
35 extern crate rustc_allocator;
36 extern crate rustc_back;
37 extern crate rustc_borrowck;
38 extern crate rustc_const_eval;
39 extern crate rustc_data_structures;
40 extern crate rustc_errors as errors;
41 extern crate rustc_passes;
42 extern crate rustc_lint;
43 extern crate rustc_plugin;
44 extern crate rustc_privacy;
45 extern crate rustc_incremental;
46 extern crate rustc_metadata;
47 extern crate rustc_mir;
48 extern crate rustc_resolve;
49 extern crate rustc_save_analysis;
50 #[cfg(feature="llvm")]
51 pub extern crate rustc_trans;
52 extern crate rustc_trans_utils;
53 extern crate rustc_typeck;
54 extern crate serialize;
55 #[macro_use]
56 extern crate log;
57 extern crate syntax;
58 extern crate syntax_ext;
59 extern crate syntax_pos;
60
61 use driver::CompileController;
62 use pretty::{PpMode, UserIdentifiedItem};
63
64 use rustc_resolve as resolve;
65 use rustc_save_analysis as save;
66 use rustc_save_analysis::DumpHandler;
67 use rustc::session::{self, config, Session, build_session, CompileResult};
68 use rustc::session::CompileIncomplete;
69 use rustc::session::config::{Input, PrintRequest, ErrorOutputType};
70 use rustc::session::config::nightly_options;
71 use rustc::session::{early_error, early_warn};
72 use rustc::lint::Lint;
73 use rustc::lint;
74 use rustc::middle::cstore::CrateStore;
75 use rustc_metadata::locator;
76 use rustc_metadata::cstore::CStore;
77 use rustc::util::common::{time, ErrorReported};
78 use rustc_trans_utils::trans_crate::TransCrate;
79
80 use serialize::json::ToJson;
81
82 use std::any::Any;
83 use std::cmp::max;
84 use std::cmp::Ordering::Equal;
85 use std::default::Default;
86 use std::env;
87 use std::ffi::OsString;
88 use std::io::{self, Read, Write};
89 use std::iter::repeat;
90 use std::path::PathBuf;
91 use std::process::{self, Command, Stdio};
92 use std::rc::Rc;
93 use std::str;
94 use std::sync::{Arc, Mutex};
95 use std::thread;
96
97 use syntax::ast;
98 use syntax::codemap::{CodeMap, FileLoader, RealFileLoader};
99 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
100 use syntax::parse::{self, PResult};
101 use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
102
103 #[cfg(test)]
104 mod test;
105
106 pub mod profile;
107 pub mod driver;
108 pub mod pretty;
109 mod derive_registrar;
110
111 pub mod target_features {
112     use syntax::ast;
113     use syntax::symbol::Symbol;
114     use rustc::session::Session;
115     use rustc_trans_utils::trans_crate::TransCrate;
116
117     /// Add `target_feature = "..."` cfgs for a variety of platform
118     /// specific features (SSE, NEON etc.).
119     ///
120     /// This is performed by checking whether a whitelisted set of
121     /// features is available on the target machine, by querying LLVM.
122     pub fn add_configuration(cfg: &mut ast::CrateConfig, sess: &Session, trans: &TransCrate) {
123         let tf = Symbol::intern("target_feature");
124
125         for feat in trans.target_features(sess) {
126             cfg.insert((tf, Some(feat)));
127         }
128
129         if sess.crt_static_feature() {
130             cfg.insert((tf, Some(Symbol::intern("crt-static"))));
131         }
132     }
133 }
134
135 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
136                                       md#bug-reports";
137
138 pub fn abort_on_err<T>(result: Result<T, CompileIncomplete>, sess: &Session) -> T {
139     match result {
140         Err(CompileIncomplete::Errored(ErrorReported)) => {
141             sess.abort_if_errors();
142             panic!("error reported but abort_if_errors didn't abort???");
143         }
144         Err(CompileIncomplete::Stopped) => {
145             sess.fatal("compilation terminated");
146         }
147         Ok(x) => x,
148     }
149 }
150
151 pub fn run<F>(run_compiler: F) -> isize
152     where F: FnOnce() -> (CompileResult, Option<Session>) + Send + 'static
153 {
154     monitor(move || {
155         let (result, session) = run_compiler();
156         if let Err(CompileIncomplete::Errored(_)) = result {
157             match session {
158                 Some(sess) => {
159                     sess.abort_if_errors();
160                     panic!("error reported but abort_if_errors didn't abort???");
161                 }
162                 None => {
163                     let emitter =
164                         errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
165                                                                None,
166                                                                true);
167                     let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
168                     handler.emit(&MultiSpan::new(),
169                                  "aborting due to previous error(s)",
170                                  errors::Level::Fatal);
171                     exit_on_err();
172                 }
173             }
174         }
175     });
176     0
177 }
178
179 #[cfg(not(feature="llvm"))]
180 pub use rustc_trans_utils::trans_crate::MetadataOnlyTransCrate as DefaultTransCrate;
181 #[cfg(feature="llvm")]
182 pub use rustc_trans::LlvmTransCrate as DefaultTransCrate;
183
184 #[cfg(not(feature="llvm"))]
185 pub mod rustc_trans {
186     pub use rustc_trans_utils::trans_crate::MetadataOnlyTransCrate as LlvmTransCrate;
187
188     pub fn print_version() {}
189     pub fn print_passes() {}
190 }
191
192 fn load_backend_from_dylib(sess: &Session, backend_name: &str) -> Box<TransCrate> {
193     use std::sync::mpsc;
194     use std::path::Path;
195     use syntax::symbol::Symbol;
196     use rustc::session::config::OutputFilenames;
197     use rustc::ty::TyCtxt;
198     use rustc::ty::maps::Providers;
199     use rustc::middle::cstore::MetadataLoader;
200     use rustc::dep_graph::DepGraph;
201     use rustc_metadata::dynamic_lib::DynamicLibrary;
202     /// This prevents the dylib from being unloaded when there is still a TransCrate open
203     struct ExternTransCrate {
204         _lib: DynamicLibrary,
205         trans: Box<TransCrate>,
206     }
207
208     impl Drop for ExternTransCrate {
209         fn drop(&mut self) {
210             // Make sure trans gets dropped before _lib as bad things happen otherwise
211             self.trans = Box::new(::rustc_trans_utils::trans_crate::DummyTransCrate)
212         }
213     }
214
215     impl TransCrate for ExternTransCrate {
216         fn print(&self, req: PrintRequest, sess: &Session) {
217             self.trans.print(req, sess);
218         }
219         fn target_features(&self, sess: &Session) -> Vec<Symbol> {
220             self.trans.target_features((sess))
221         }
222
223         fn metadata_loader(&self) -> Box<MetadataLoader> {
224             self.trans.metadata_loader()
225         }
226         fn provide(&self, providers: &mut Providers) {
227             self.trans.provide(providers)
228         }
229         fn provide_extern(&self, providers: &mut Providers) {
230             self.trans.provide_extern(providers)
231         }
232         fn trans_crate<'a, 'tcx>(
233             &self,
234             tcx: TyCtxt<'a, 'tcx, 'tcx>,
235             rx: mpsc::Receiver<Box<Any + Send>>
236         ) -> Box<Any> {
237             self.trans.trans_crate(tcx, rx)
238         }
239
240         fn join_trans_and_link(
241             &self,
242             trans: Box<Any>,
243             sess: &Session,
244             dep_graph: &DepGraph,
245             outputs: &OutputFilenames,
246         ) -> Result<(), CompileIncomplete> {
247             self.trans.join_trans_and_link(trans, sess, dep_graph, outputs)
248         }
249     }
250
251     match DynamicLibrary::open(Some(Path::new(backend_name))) {
252         Ok(lib) => {
253             unsafe {
254                 let trans = {
255                     let __rustc_codegen_backend: unsafe fn(&Session) -> Box<TransCrate>;
256                     __rustc_codegen_backend = match lib.symbol("__rustc_codegen_backend") {
257                         Ok(f) => ::std::mem::transmute::<*mut u8, _>(f),
258                         Err(e) => sess.fatal(&format!("Couldnt load codegen backend as it\
259                         doesn't export the __rustc_backend_new symbol: {:?}", e)),
260                     };
261                     __rustc_codegen_backend(sess)
262                 };
263                 Box::new(ExternTransCrate {
264                     _lib: lib,
265                     trans
266                 })
267             }
268         }
269         Err(err) => {
270             sess.fatal(&format!("Couldnt load codegen backend {:?}: {:?}", backend_name, err));
271         }
272     }
273 }
274
275 pub fn get_trans(sess: &Session) -> Box<TransCrate> {
276     let trans_name = sess.opts.debugging_opts.codegen_backend.clone();
277     match trans_name.as_ref().map(|s|&**s) {
278         None => DefaultTransCrate::new(&sess),
279         Some("llvm") => rustc_trans::LlvmTransCrate::new(&sess),
280         Some("metadata_only") => {
281             rustc_trans_utils::trans_crate::MetadataOnlyTransCrate::new(&sess)
282         }
283         Some(filename) if filename.contains(".") => {
284             load_backend_from_dylib(&sess, &filename)
285         }
286         Some(trans_name) => sess.fatal(&format!("Unknown codegen backend {}", trans_name)),
287     }
288 }
289
290 // Parse args and run the compiler. This is the primary entry point for rustc.
291 // See comments on CompilerCalls below for details about the callbacks argument.
292 // The FileLoader provides a way to load files from sources other than the file system.
293 pub fn run_compiler<'a>(args: &[String],
294                         callbacks: &mut CompilerCalls<'a>,
295                         file_loader: Option<Box<FileLoader + 'static>>,
296                         emitter_dest: Option<Box<Write + Send>>)
297                         -> (CompileResult, Option<Session>)
298 {
299     macro_rules! do_or_return {($expr: expr, $sess: expr) => {
300         match $expr {
301             Compilation::Stop => return (Ok(()), $sess),
302             Compilation::Continue => {}
303         }
304     }}
305
306     let matches = match handle_options(args) {
307         Some(matches) => matches,
308         None => return (Ok(()), None),
309     };
310
311     let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
312
313     let descriptions = diagnostics_registry();
314
315     do_or_return!(callbacks.early_callback(&matches,
316                                            &sopts,
317                                            &cfg,
318                                            &descriptions,
319                                            sopts.error_format),
320                                            None);
321
322     let (odir, ofile) = make_output(&matches);
323     let (input, input_file_path) = match make_input(&matches.free) {
324         Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
325         None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) {
326             Some((input, input_file_path)) => (input, input_file_path),
327             None => return (Ok(()), None),
328         },
329     };
330
331     let loader = file_loader.unwrap_or(box RealFileLoader);
332     let codemap = Rc::new(CodeMap::with_file_loader(loader, sopts.file_path_mapping()));
333     let mut sess = session::build_session_with_codemap(
334         sopts, input_file_path.clone(), descriptions, codemap, emitter_dest,
335     );
336
337     let trans = get_trans(&sess);
338
339     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
340
341     let mut cfg = config::build_configuration(&sess, cfg);
342     target_features::add_configuration(&mut cfg, &sess, &*trans);
343     sess.parse_sess.config = cfg;
344
345     let plugins = sess.opts.debugging_opts.extra_plugins.clone();
346
347     let cstore = CStore::new(trans.metadata_loader());
348
349     do_or_return!(callbacks.late_callback(&*trans,
350                                           &matches,
351                                           &sess,
352                                           &cstore,
353                                           &input,
354                                           &odir,
355                                           &ofile), Some(sess));
356
357     let control = callbacks.build_controller(&sess, &matches);
358
359     (driver::compile_input(trans,
360                            &sess,
361                            &cstore,
362                            &input_file_path,
363                            &input,
364                            &odir,
365                            &ofile,
366                            Some(plugins),
367                            &control),
368      Some(sess))
369 }
370
371 // Extract output directory and file from matches.
372 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
373     let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
374     let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
375     (odir, ofile)
376 }
377
378 // Extract input (string or file and optional path) from matches.
379 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
380     if free_matches.len() == 1 {
381         let ifile = &free_matches[0];
382         if ifile == "-" {
383             let mut src = String::new();
384             io::stdin().read_to_string(&mut src).unwrap();
385             Some((Input::Str { name: FileName::Anon, input: src },
386                   None))
387         } else {
388             Some((Input::File(PathBuf::from(ifile)),
389                   Some(PathBuf::from(ifile))))
390         }
391     } else {
392         None
393     }
394 }
395
396 fn parse_pretty(sess: &Session,
397                 matches: &getopts::Matches)
398                 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
399     let pretty = if sess.opts.debugging_opts.unstable_options {
400         matches.opt_default("pretty", "normal").map(|a| {
401             // stable pretty-print variants only
402             pretty::parse_pretty(sess, &a, false)
403         })
404     } else {
405         None
406     };
407     if pretty.is_none() && sess.unstable_options() {
408         matches.opt_str("unpretty").map(|a| {
409             // extended with unstable pretty-print variants
410             pretty::parse_pretty(sess, &a, true)
411         })
412     } else {
413         pretty
414     }
415 }
416
417 // Whether to stop or continue compilation.
418 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
419 pub enum Compilation {
420     Stop,
421     Continue,
422 }
423
424 impl Compilation {
425     pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
426         match self {
427             Compilation::Stop => Compilation::Stop,
428             Compilation::Continue => next(),
429         }
430     }
431 }
432
433 // A trait for customising the compilation process. Offers a number of hooks for
434 // executing custom code or customising input.
435 pub trait CompilerCalls<'a> {
436     // Hook for a callback early in the process of handling arguments. This will
437     // be called straight after options have been parsed but before anything
438     // else (e.g., selecting input and output).
439     fn early_callback(&mut self,
440                       _: &getopts::Matches,
441                       _: &config::Options,
442                       _: &ast::CrateConfig,
443                       _: &errors::registry::Registry,
444                       _: ErrorOutputType)
445                       -> Compilation {
446         Compilation::Continue
447     }
448
449     // Hook for a callback late in the process of handling arguments. This will
450     // be called just before actual compilation starts (and before build_controller
451     // is called), after all arguments etc. have been completely handled.
452     fn late_callback(&mut self,
453                      _: &TransCrate,
454                      _: &getopts::Matches,
455                      _: &Session,
456                      _: &CrateStore,
457                      _: &Input,
458                      _: &Option<PathBuf>,
459                      _: &Option<PathBuf>)
460                      -> Compilation {
461         Compilation::Continue
462     }
463
464     // Called after we extract the input from the arguments. Gives the implementer
465     // an opportunity to change the inputs or to add some custom input handling.
466     // The default behaviour is to simply pass through the inputs.
467     fn some_input(&mut self,
468                   input: Input,
469                   input_path: Option<PathBuf>)
470                   -> (Input, Option<PathBuf>) {
471         (input, input_path)
472     }
473
474     // Called after we extract the input from the arguments if there is no valid
475     // input. Gives the implementer an opportunity to supply alternate input (by
476     // returning a Some value) or to add custom behaviour for this error such as
477     // emitting error messages. Returning None will cause compilation to stop
478     // at this point.
479     fn no_input(&mut self,
480                 _: &getopts::Matches,
481                 _: &config::Options,
482                 _: &ast::CrateConfig,
483                 _: &Option<PathBuf>,
484                 _: &Option<PathBuf>,
485                 _: &errors::registry::Registry)
486                 -> Option<(Input, Option<PathBuf>)> {
487         None
488     }
489
490     // Create a CompilController struct for controlling the behaviour of
491     // compilation.
492     fn build_controller(&mut self, _: &Session, _: &getopts::Matches) -> CompileController<'a>;
493 }
494
495 // CompilerCalls instance for a regular rustc build.
496 #[derive(Copy, Clone)]
497 pub struct RustcDefaultCalls;
498
499 // FIXME remove these and use winapi 0.3 instead
500 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
501 #[cfg(unix)]
502 fn stdout_isatty() -> bool {
503     unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
504 }
505
506 #[cfg(windows)]
507 fn stdout_isatty() -> bool {
508     type DWORD = u32;
509     type BOOL = i32;
510     type HANDLE = *mut u8;
511     type LPDWORD = *mut u32;
512     const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
513     extern "system" {
514         fn GetStdHandle(which: DWORD) -> HANDLE;
515         fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
516     }
517     unsafe {
518         let handle = GetStdHandle(STD_OUTPUT_HANDLE);
519         let mut out = 0;
520         GetConsoleMode(handle, &mut out) != 0
521     }
522 }
523
524 fn handle_explain(code: &str,
525                   descriptions: &errors::registry::Registry,
526                   output: ErrorOutputType) {
527     let normalised = if code.starts_with("E") {
528         code.to_string()
529     } else {
530         format!("E{0:0>4}", code)
531     };
532     match descriptions.find_description(&normalised) {
533         Some(ref description) => {
534             let mut is_in_code_block = false;
535             let mut text = String::new();
536
537             // Slice off the leading newline and print.
538             for line in description[1..].lines() {
539                 let indent_level = line.find(|c: char| !c.is_whitespace())
540                     .unwrap_or_else(|| line.len());
541                 let dedented_line = &line[indent_level..];
542                 if dedented_line.starts_with("```") {
543                     is_in_code_block = !is_in_code_block;
544                     text.push_str(&line[..(indent_level+3)]);
545                 } else if is_in_code_block && dedented_line.starts_with("# ") {
546                     continue;
547                 } else {
548                     text.push_str(line);
549                 }
550                 text.push('\n');
551             }
552
553             if stdout_isatty() {
554                 show_content_with_pager(&text);
555             } else {
556                 print!("{}", text);
557             }
558         }
559         None => {
560             early_error(output, &format!("no extended information for {}", code));
561         }
562     }
563 }
564
565 fn show_content_with_pager(content: &String) {
566     let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
567         OsString::from("more.com")
568     } else {
569         OsString::from("less")
570     });
571
572     let mut fallback_to_println = false;
573
574     match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
575         Ok(mut pager) => {
576             if let Some(pipe) = pager.stdin.as_mut() {
577                 if pipe.write_all(content.as_bytes()).is_err() {
578                     fallback_to_println = true;
579                 }
580             }
581
582             if pager.wait().is_err() {
583                 fallback_to_println = true;
584             }
585         }
586         Err(_) => {
587             fallback_to_println = true;
588         }
589     }
590
591     // If pager fails for whatever reason, we should still print the content
592     // to standard output
593     if fallback_to_println {
594         print!("{}", content);
595     }
596 }
597
598 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
599     fn early_callback(&mut self,
600                       matches: &getopts::Matches,
601                       _: &config::Options,
602                       _: &ast::CrateConfig,
603                       descriptions: &errors::registry::Registry,
604                       output: ErrorOutputType)
605                       -> Compilation {
606         if let Some(ref code) = matches.opt_str("explain") {
607             handle_explain(code, descriptions, output);
608             return Compilation::Stop;
609         }
610
611         Compilation::Continue
612     }
613
614     fn no_input(&mut self,
615                 matches: &getopts::Matches,
616                 sopts: &config::Options,
617                 cfg: &ast::CrateConfig,
618                 odir: &Option<PathBuf>,
619                 ofile: &Option<PathBuf>,
620                 descriptions: &errors::registry::Registry)
621                 -> Option<(Input, Option<PathBuf>)> {
622         match matches.free.len() {
623             0 => {
624                 if sopts.describe_lints {
625                     let mut ls = lint::LintStore::new();
626                     rustc_lint::register_builtins(&mut ls, None);
627                     describe_lints(&ls, false);
628                     return None;
629                 }
630                 let mut sess = build_session(sopts.clone(),
631                     None,
632                     descriptions.clone());
633                 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
634                 let mut cfg = config::build_configuration(&sess, cfg.clone());
635                 let trans = get_trans(&sess);
636                 target_features::add_configuration(&mut cfg, &sess, &*trans);
637                 sess.parse_sess.config = cfg;
638                 let should_stop = RustcDefaultCalls::print_crate_info(
639                     &*trans,
640                     &sess,
641                     None,
642                     odir,
643                     ofile
644                 );
645
646                 if should_stop == Compilation::Stop {
647                     return None;
648                 }
649                 early_error(sopts.error_format, "no input filename given");
650             }
651             1 => panic!("make_input should have provided valid inputs"),
652             _ => early_error(sopts.error_format, "multiple input filenames provided"),
653         }
654     }
655
656     fn late_callback(&mut self,
657                      trans: &TransCrate,
658                      matches: &getopts::Matches,
659                      sess: &Session,
660                      cstore: &CrateStore,
661                      input: &Input,
662                      odir: &Option<PathBuf>,
663                      ofile: &Option<PathBuf>)
664                      -> Compilation {
665         RustcDefaultCalls::print_crate_info(trans, sess, Some(input), odir, ofile)
666             .and_then(|| RustcDefaultCalls::list_metadata(sess, cstore, matches, input))
667     }
668
669     fn build_controller(&mut self,
670                         sess: &Session,
671                         matches: &getopts::Matches)
672                         -> CompileController<'a> {
673         let mut control = CompileController::basic();
674
675         control.keep_ast = sess.opts.debugging_opts.keep_ast;
676         control.continue_parse_after_error = sess.opts.debugging_opts.continue_parse_after_error;
677
678         if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
679             if ppm.needs_ast_map(&opt_uii) {
680                 control.after_hir_lowering.stop = Compilation::Stop;
681
682                 control.after_parse.callback = box move |state| {
683                     state.krate = Some(pretty::fold_crate(state.session,
684                                                           state.krate.take().unwrap(),
685                                                           ppm));
686                 };
687                 control.after_hir_lowering.callback = box move |state| {
688                     pretty::print_after_hir_lowering(state.session,
689                                                      state.cstore.unwrap(),
690                                                      state.hir_map.unwrap(),
691                                                      state.analysis.unwrap(),
692                                                      state.resolutions.unwrap(),
693                                                      state.input,
694                                                      &state.expanded_crate.take().unwrap(),
695                                                      state.crate_name.unwrap(),
696                                                      ppm,
697                                                      state.arenas.unwrap(),
698                                                      state.output_filenames.unwrap(),
699                                                      opt_uii.clone(),
700                                                      state.out_file);
701                 };
702             } else {
703                 control.after_parse.stop = Compilation::Stop;
704
705                 control.after_parse.callback = box move |state| {
706                     let krate = pretty::fold_crate(state.session, state.krate.take().unwrap(), ppm);
707                     pretty::print_after_parsing(state.session,
708                                                 state.input,
709                                                 &krate,
710                                                 ppm,
711                                                 state.out_file);
712                 };
713             }
714
715             return control;
716         }
717
718         if sess.opts.debugging_opts.parse_only ||
719            sess.opts.debugging_opts.show_span.is_some() ||
720            sess.opts.debugging_opts.ast_json_noexpand {
721             control.after_parse.stop = Compilation::Stop;
722         }
723
724         if sess.opts.debugging_opts.no_analysis ||
725            sess.opts.debugging_opts.ast_json {
726             control.after_hir_lowering.stop = Compilation::Stop;
727         }
728
729         if save_analysis(sess) {
730             enable_save_analysis(&mut control);
731         }
732
733         if sess.print_fuel_crate.is_some() {
734             let old_callback = control.compilation_done.callback;
735             control.compilation_done.callback = box move |state| {
736                 old_callback(state);
737                 let sess = state.session;
738                 println!("Fuel used by {}: {}",
739                     sess.print_fuel_crate.as_ref().unwrap(),
740                     sess.print_fuel.get());
741             }
742         }
743         control
744     }
745 }
746
747 pub fn enable_save_analysis(control: &mut CompileController) {
748     control.keep_ast = true;
749     control.after_analysis.callback = box |state| {
750         time(state.session.time_passes(), "save analysis", || {
751             save::process_crate(state.tcx.unwrap(),
752                                 state.expanded_crate.unwrap(),
753                                 state.analysis.unwrap(),
754                                 state.crate_name.unwrap(),
755                                 None,
756                                 DumpHandler::new(state.out_dir,
757                                                  state.crate_name.unwrap()))
758         });
759     };
760     control.after_analysis.run_callback_on_error = true;
761     control.make_glob_map = resolve::MakeGlobMap::Yes;
762 }
763
764 fn save_analysis(sess: &Session) -> bool {
765     sess.opts.debugging_opts.save_analysis
766 }
767
768 impl RustcDefaultCalls {
769     pub fn list_metadata(sess: &Session,
770                          cstore: &CrateStore,
771                          matches: &getopts::Matches,
772                          input: &Input)
773                          -> Compilation {
774         let r = matches.opt_strs("Z");
775         if r.contains(&("ls".to_string())) {
776             match input {
777                 &Input::File(ref ifile) => {
778                     let path = &(*ifile);
779                     let mut v = Vec::new();
780                     locator::list_file_metadata(&sess.target.target,
781                                                 path,
782                                                 cstore.metadata_loader(),
783                                                 &mut v)
784                             .unwrap();
785                     println!("{}", String::from_utf8(v).unwrap());
786                 }
787                 &Input::Str { .. } => {
788                     early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
789                 }
790             }
791             return Compilation::Stop;
792         }
793
794         return Compilation::Continue;
795     }
796
797
798     fn print_crate_info(trans: &TransCrate,
799                         sess: &Session,
800                         input: Option<&Input>,
801                         odir: &Option<PathBuf>,
802                         ofile: &Option<PathBuf>)
803                         -> Compilation {
804         use rustc::session::config::PrintRequest::*;
805         // PrintRequest::NativeStaticLibs is special - printed during linking
806         // (empty iterator returns true)
807         if sess.opts.prints.iter().all(|&p| p==PrintRequest::NativeStaticLibs) {
808             return Compilation::Continue;
809         }
810
811         let attrs = match input {
812             None => None,
813             Some(input) => {
814                 let result = parse_crate_attrs(sess, input);
815                 match result {
816                     Ok(attrs) => Some(attrs),
817                     Err(mut parse_error) => {
818                         parse_error.emit();
819                         return Compilation::Stop;
820                     }
821                 }
822             }
823         };
824         for req in &sess.opts.prints {
825             match *req {
826                 TargetList => {
827                     let mut targets = rustc_back::target::get_targets().collect::<Vec<String>>();
828                     targets.sort();
829                     println!("{}", targets.join("\n"));
830                 },
831                 Sysroot => println!("{}", sess.sysroot().display()),
832                 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
833                 FileNames | CrateName => {
834                     let input = match input {
835                         Some(input) => input,
836                         None => early_error(ErrorOutputType::default(), "no input file provided"),
837                     };
838                     let attrs = attrs.as_ref().unwrap();
839                     let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
840                     let id = rustc_trans_utils::link::find_crate_name(Some(sess), attrs, input);
841                     if *req == PrintRequest::CrateName {
842                         println!("{}", id);
843                         continue;
844                     }
845                     let crate_types = driver::collect_crate_types(sess, attrs);
846                     for &style in &crate_types {
847                         let fname = rustc_trans_utils::link::filename_for_input(
848                             sess,
849                             style,
850                             &id,
851                             &t_outputs
852                         );
853                         println!("{}",
854                                  fname.file_name()
855                                       .unwrap()
856                                       .to_string_lossy());
857                     }
858                 }
859                 Cfg => {
860                     let allow_unstable_cfg = UnstableFeatures::from_environment()
861                         .is_nightly_build();
862
863                     let mut cfgs = Vec::new();
864                     for &(name, ref value) in sess.parse_sess.config.iter() {
865                         let gated_cfg = GatedCfg::gate(&ast::MetaItem {
866                             name,
867                             node: ast::MetaItemKind::Word,
868                             span: DUMMY_SP,
869                         });
870
871                         // Note that crt-static is a specially recognized cfg
872                         // directive that's printed out here as part of
873                         // rust-lang/rust#37406, but in general the
874                         // `target_feature` cfg is gated under
875                         // rust-lang/rust#29717. For now this is just
876                         // specifically allowing the crt-static cfg and that's
877                         // it, this is intended to get into Cargo and then go
878                         // through to build scripts.
879                         let value = value.as_ref().map(|s| s.as_str());
880                         let value = value.as_ref().map(|s| s.as_ref());
881                         if name != "target_feature" || value != Some("crt-static") {
882                             if !allow_unstable_cfg && gated_cfg.is_some() {
883                                 continue;
884                             }
885                         }
886
887                         cfgs.push(if let Some(value) = value {
888                             format!("{}=\"{}\"", name, value)
889                         } else {
890                             format!("{}", name)
891                         });
892                     }
893
894                     cfgs.sort();
895                     for cfg in cfgs {
896                         println!("{}", cfg);
897                     }
898                 }
899                 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
900                     trans.print(*req, sess);
901                 }
902                 // Any output here interferes with Cargo's parsing of other printed output
903                 PrintRequest::NativeStaticLibs => {}
904             }
905         }
906         return Compilation::Stop;
907     }
908 }
909
910 /// Returns a version string such as "0.12.0-dev".
911 fn release_str() -> Option<&'static str> {
912     option_env!("CFG_RELEASE")
913 }
914
915 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
916 fn commit_hash_str() -> Option<&'static str> {
917     option_env!("CFG_VER_HASH")
918 }
919
920 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
921 fn commit_date_str() -> Option<&'static str> {
922     option_env!("CFG_VER_DATE")
923 }
924
925 /// Prints version information
926 pub fn version(binary: &str, matches: &getopts::Matches) {
927     let verbose = matches.opt_present("verbose");
928
929     println!("{} {}",
930              binary,
931              option_env!("CFG_VERSION").unwrap_or("unknown version"));
932     if verbose {
933         fn unw(x: Option<&str>) -> &str {
934             x.unwrap_or("unknown")
935         }
936         println!("binary: {}", binary);
937         println!("commit-hash: {}", unw(commit_hash_str()));
938         println!("commit-date: {}", unw(commit_date_str()));
939         println!("host: {}", config::host_triple());
940         println!("release: {}", unw(release_str()));
941         rustc_trans::print_version();
942     }
943 }
944
945 fn usage(verbose: bool, include_unstable_options: bool) {
946     let groups = if verbose {
947         config::rustc_optgroups()
948     } else {
949         config::rustc_short_optgroups()
950     };
951     let mut options = getopts::Options::new();
952     for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
953         (option.apply)(&mut options);
954     }
955     let message = format!("Usage: rustc [OPTIONS] INPUT");
956     let nightly_help = if nightly_options::is_nightly_build() {
957         "\n    -Z help             Print internal options for debugging rustc"
958     } else {
959         ""
960     };
961     let verbose_help = if verbose {
962         ""
963     } else {
964         "\n    --help -v           Print the full set of options rustc accepts"
965     };
966     println!("{}\nAdditional help:
967     -C help             Print codegen options
968     -W help             \
969               Print 'lint' options and default settings{}{}\n",
970              options.usage(&message),
971              nightly_help,
972              verbose_help);
973 }
974
975 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
976     println!("
977 Available lint options:
978     -W <foo>           Warn about <foo>
979     -A <foo>           \
980               Allow <foo>
981     -D <foo>           Deny <foo>
982     -F <foo>           Forbid <foo> \
983               (deny <foo> and all attempts to override)
984
985 ");
986
987     fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
988         let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
989         lints.sort_by(|x: &&Lint, y: &&Lint| {
990             match x.default_level.cmp(&y.default_level) {
991                 // The sort doesn't case-fold but it's doubtful we care.
992                 Equal => x.name.cmp(y.name),
993                 r => r,
994             }
995         });
996         lints
997     }
998
999     fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
1000                         -> Vec<(&'static str, Vec<lint::LintId>)> {
1001         let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
1002         lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
1003                        &(y, _): &(&'static str, Vec<lint::LintId>)| {
1004             x.cmp(y)
1005         });
1006         lints
1007     }
1008
1009     let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
1010                                                    .iter()
1011                                                    .cloned()
1012                                                    .partition(|&(_, p)| p);
1013     let plugin = sort_lints(plugin);
1014     let builtin = sort_lints(builtin);
1015
1016     let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
1017                                                                  .iter()
1018                                                                  .cloned()
1019                                                                  .partition(|&(.., p)| p);
1020     let plugin_groups = sort_lint_groups(plugin_groups);
1021     let builtin_groups = sort_lint_groups(builtin_groups);
1022
1023     let max_name_len = plugin.iter()
1024                              .chain(&builtin)
1025                              .map(|&s| s.name.chars().count())
1026                              .max()
1027                              .unwrap_or(0);
1028     let padded = |x: &str| {
1029         let mut s = repeat(" ")
1030                         .take(max_name_len - x.chars().count())
1031                         .collect::<String>();
1032         s.push_str(x);
1033         s
1034     };
1035
1036     println!("Lint checks provided by rustc:\n");
1037     println!("    {}  {:7.7}  {}", padded("name"), "default", "meaning");
1038     println!("    {}  {:7.7}  {}", padded("----"), "-------", "-------");
1039
1040     let print_lints = |lints: Vec<&Lint>| {
1041         for lint in lints {
1042             let name = lint.name_lower().replace("_", "-");
1043             println!("    {}  {:7.7}  {}",
1044                      padded(&name),
1045                      lint.default_level.as_str(),
1046                      lint.desc);
1047         }
1048         println!("\n");
1049     };
1050
1051     print_lints(builtin);
1052
1053
1054
1055     let max_name_len = max("warnings".len(),
1056                            plugin_groups.iter()
1057                                         .chain(&builtin_groups)
1058                                         .map(|&(s, _)| s.chars().count())
1059                                         .max()
1060                                         .unwrap_or(0));
1061
1062     let padded = |x: &str| {
1063         let mut s = repeat(" ")
1064                         .take(max_name_len - x.chars().count())
1065                         .collect::<String>();
1066         s.push_str(x);
1067         s
1068     };
1069
1070     println!("Lint groups provided by rustc:\n");
1071     println!("    {}  {}", padded("name"), "sub-lints");
1072     println!("    {}  {}", padded("----"), "---------");
1073     println!("    {}  {}", padded("warnings"), "all lints that are set to issue warnings");
1074
1075     let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
1076         for (name, to) in lints {
1077             let name = name.to_lowercase().replace("_", "-");
1078             let desc = to.into_iter()
1079                          .map(|x| x.to_string().replace("_", "-"))
1080                          .collect::<Vec<String>>()
1081                          .join(", ");
1082             println!("    {}  {}", padded(&name), desc);
1083         }
1084         println!("\n");
1085     };
1086
1087     print_lint_groups(builtin_groups);
1088
1089     match (loaded_plugins, plugin.len(), plugin_groups.len()) {
1090         (false, 0, _) | (false, _, 0) => {
1091             println!("Compiler plugins can provide additional lints and lint groups. To see a \
1092                       listing of these, re-run `rustc -W help` with a crate filename.");
1093         }
1094         (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
1095         (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
1096         (true, l, g) => {
1097             if l > 0 {
1098                 println!("Lint checks provided by plugins loaded by this crate:\n");
1099                 print_lints(plugin);
1100             }
1101             if g > 0 {
1102                 println!("Lint groups provided by plugins loaded by this crate:\n");
1103                 print_lint_groups(plugin_groups);
1104             }
1105         }
1106     }
1107 }
1108
1109 fn describe_debug_flags() {
1110     println!("\nAvailable debug options:\n");
1111     print_flag_list("-Z", config::DB_OPTIONS);
1112 }
1113
1114 fn describe_codegen_flags() {
1115     println!("\nAvailable codegen options:\n");
1116     print_flag_list("-C", config::CG_OPTIONS);
1117 }
1118
1119 fn print_flag_list<T>(cmdline_opt: &str,
1120                       flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
1121     let max_len = flag_list.iter()
1122                            .map(|&(name, _, opt_type_desc, _)| {
1123                                let extra_len = match opt_type_desc {
1124                                    Some(..) => 4,
1125                                    None => 0,
1126                                };
1127                                name.chars().count() + extra_len
1128                            })
1129                            .max()
1130                            .unwrap_or(0);
1131
1132     for &(name, _, opt_type_desc, desc) in flag_list {
1133         let (width, extra) = match opt_type_desc {
1134             Some(..) => (max_len - 4, "=val"),
1135             None => (max_len, ""),
1136         };
1137         println!("    {} {:>width$}{} -- {}",
1138                  cmdline_opt,
1139                  name.replace("_", "-"),
1140                  extra,
1141                  desc,
1142                  width = width);
1143     }
1144 }
1145
1146 /// Process command line options. Emits messages as appropriate. If compilation
1147 /// should continue, returns a getopts::Matches object parsed from args,
1148 /// otherwise returns None.
1149 ///
1150 /// The compiler's handling of options is a little complicated as it ties into
1151 /// our stability story, and it's even *more* complicated by historical
1152 /// accidents. The current intention of each compiler option is to have one of
1153 /// three modes:
1154 ///
1155 /// 1. An option is stable and can be used everywhere.
1156 /// 2. An option is unstable, but was historically allowed on the stable
1157 ///    channel.
1158 /// 3. An option is unstable, and can only be used on nightly.
1159 ///
1160 /// Like unstable library and language features, however, unstable options have
1161 /// always required a form of "opt in" to indicate that you're using them. This
1162 /// provides the easy ability to scan a code base to check to see if anything
1163 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1164 ///
1165 /// All options behind `-Z` are considered unstable by default. Other top-level
1166 /// options can also be considered unstable, and they were unlocked through the
1167 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1168 /// instability in both cases, though.
1169 ///
1170 /// So with all that in mind, the comments below have some more detail about the
1171 /// contortions done here to get things to work out correctly.
1172 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
1173     // Throw away the first argument, the name of the binary
1174     let args = &args[1..];
1175
1176     if args.is_empty() {
1177         // user did not write `-v` nor `-Z unstable-options`, so do not
1178         // include that extra information.
1179         usage(false, false);
1180         return None;
1181     }
1182
1183     // Parse with *all* options defined in the compiler, we don't worry about
1184     // option stability here we just want to parse as much as possible.
1185     let mut options = getopts::Options::new();
1186     for option in config::rustc_optgroups() {
1187         (option.apply)(&mut options);
1188     }
1189     let matches = match options.parse(args) {
1190         Ok(m) => m,
1191         Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
1192     };
1193
1194     // For all options we just parsed, we check a few aspects:
1195     //
1196     // * If the option is stable, we're all good
1197     // * If the option wasn't passed, we're all good
1198     // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1199     //   ourselves), then we require the `-Z unstable-options` flag to unlock
1200     //   this option that was passed.
1201     // * If we're a nightly compiler, then unstable options are now unlocked, so
1202     //   we're good to go.
1203     // * Otherwise, if we're a truly unstable option then we generate an error
1204     //   (unstable option being used on stable)
1205     // * If we're a historically stable-but-should-be-unstable option then we
1206     //   emit a warning that we're going to turn this into an error soon.
1207     nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1208
1209     if matches.opt_present("h") || matches.opt_present("help") {
1210         // Only show unstable options in --help if we *really* accept unstable
1211         // options, which catches the case where we got `-Z unstable-options` on
1212         // the stable channel of Rust which was accidentally allowed
1213         // historically.
1214         usage(matches.opt_present("verbose"),
1215               nightly_options::is_unstable_enabled(&matches));
1216         return None;
1217     }
1218
1219     // Don't handle -W help here, because we might first load plugins.
1220     let r = matches.opt_strs("Z");
1221     if r.iter().any(|x| *x == "help") {
1222         describe_debug_flags();
1223         return None;
1224     }
1225
1226     let cg_flags = matches.opt_strs("C");
1227     if cg_flags.iter().any(|x| *x == "help") {
1228         describe_codegen_flags();
1229         return None;
1230     }
1231
1232     if cg_flags.iter().any(|x| *x == "no-stack-check") {
1233         early_warn(ErrorOutputType::default(),
1234                    "the --no-stack-check flag is deprecated and does nothing");
1235     }
1236
1237     if cg_flags.contains(&"passes=list".to_string()) {
1238         rustc_trans::print_passes();
1239         return None;
1240     }
1241
1242     if matches.opt_present("version") {
1243         version("rustc", &matches);
1244         return None;
1245     }
1246
1247     Some(matches)
1248 }
1249
1250 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1251     match *input {
1252         Input::File(ref ifile) => {
1253             parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1254         }
1255         Input::Str { ref name, ref input } => {
1256             parse::parse_crate_attrs_from_source_str(name.clone(),
1257                                                      input.clone(),
1258                                                      &sess.parse_sess)
1259         }
1260     }
1261 }
1262
1263 /// Runs `f` in a suitable thread for running `rustc`; returns a
1264 /// `Result` with either the return value of `f` or -- if a panic
1265 /// occurs -- the panic value.
1266 pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<Any + Send>>
1267     where F: FnOnce() -> R + Send + 'static,
1268           R: Send + 'static,
1269 {
1270     // Temporarily have stack size set to 16MB to deal with nom-using crates failing
1271     const STACK_SIZE: usize = 16 * 1024 * 1024; // 16MB
1272
1273     let mut cfg = thread::Builder::new().name("rustc".to_string());
1274
1275     // FIXME: Hacks on hacks. If the env is trying to override the stack size
1276     // then *don't* set it explicitly.
1277     if env::var_os("RUST_MIN_STACK").is_none() {
1278         cfg = cfg.stack_size(STACK_SIZE);
1279     }
1280
1281     let thread = cfg.spawn(f);
1282     thread.unwrap().join()
1283 }
1284
1285 /// Run a procedure which will detect panics in the compiler and print nicer
1286 /// error messages rather than just failing the test.
1287 ///
1288 /// The diagnostic emitter yielded to the procedure should be used for reporting
1289 /// errors of the compiler.
1290 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
1291     struct Sink(Arc<Mutex<Vec<u8>>>);
1292     impl Write for Sink {
1293         fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1294             Write::write(&mut *self.0.lock().unwrap(), data)
1295         }
1296         fn flush(&mut self) -> io::Result<()> {
1297             Ok(())
1298         }
1299     }
1300
1301     let data = Arc::new(Mutex::new(Vec::new()));
1302     let err = Sink(data.clone());
1303
1304     let result = in_rustc_thread(move || {
1305         io::set_panic(Some(box err));
1306         f()
1307     });
1308
1309     if let Err(value) = result {
1310         // Thread panicked without emitting a fatal diagnostic
1311         if !value.is::<errors::FatalError>() {
1312             let emitter =
1313                 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
1314                                                                 None,
1315                                                                 false));
1316             let handler = errors::Handler::with_emitter(true, false, emitter);
1317
1318             // a .span_bug or .bug call has already printed what
1319             // it wants to print.
1320             if !value.is::<errors::ExplicitBug>() {
1321                 handler.emit(&MultiSpan::new(),
1322                              "unexpected panic",
1323                              errors::Level::Bug);
1324             }
1325
1326             let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1327                       format!("we would appreciate a bug report: {}", BUG_REPORT_URL),
1328                       format!("rustc {} running on {}",
1329                               option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1330                               config::host_triple())];
1331             for note in &xs {
1332                 handler.emit(&MultiSpan::new(),
1333                              &note,
1334                              errors::Level::Note);
1335             }
1336             if match env::var_os("RUST_BACKTRACE") {
1337                 Some(val) => &val != "0",
1338                 None => false,
1339             } {
1340                 handler.emit(&MultiSpan::new(),
1341                              "run with `RUST_BACKTRACE=1` for a backtrace",
1342                              errors::Level::Note);
1343             }
1344
1345             eprintln!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
1346         }
1347
1348         exit_on_err();
1349     }
1350 }
1351
1352 fn exit_on_err() -> ! {
1353     // Panic so the process returns a failure code, but don't pollute the
1354     // output with some unnecessary panic messages, we've already
1355     // printed everything that we needed to.
1356     io::set_panic(Some(box io::sink()));
1357     panic!();
1358 }
1359
1360 #[cfg(stage0)]
1361 pub fn diagnostics_registry() -> errors::registry::Registry {
1362     use errors::registry::Registry;
1363
1364     Registry::new(&[])
1365 }
1366
1367 #[cfg(not(stage0))]
1368 pub fn diagnostics_registry() -> errors::registry::Registry {
1369     use errors::registry::Registry;
1370
1371     let mut all_errors = Vec::new();
1372     all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1373     all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1374     all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1375     all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1376     #[cfg(feature="llvm")]
1377     all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
1378     all_errors.extend_from_slice(&rustc_trans_utils::DIAGNOSTICS);
1379     all_errors.extend_from_slice(&rustc_const_eval::DIAGNOSTICS);
1380     all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1381     all_errors.extend_from_slice(&rustc_passes::DIAGNOSTICS);
1382     all_errors.extend_from_slice(&rustc_plugin::DIAGNOSTICS);
1383     all_errors.extend_from_slice(&rustc_mir::DIAGNOSTICS);
1384     all_errors.extend_from_slice(&syntax::DIAGNOSTICS);
1385
1386     Registry::new(&all_errors)
1387 }
1388
1389 pub fn get_args() -> Vec<String> {
1390     env::args_os().enumerate()
1391         .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1392              early_error(ErrorOutputType::default(),
1393                          &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1394          }))
1395         .collect()
1396 }
1397
1398 pub fn main() {
1399     env_logger::init().unwrap();
1400     let result = run(|| run_compiler(&get_args(),
1401                                      &mut RustcDefaultCalls,
1402                                      None,
1403                                      None));
1404     process::exit(result as i32);
1405 }