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