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