]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/lib.rs
rustc: Remove `Session::dep_graph`
[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                                                      opt_uii.clone(),
649                                                      state.out_file);
650                 };
651             } else {
652                 control.after_parse.stop = Compilation::Stop;
653
654                 control.after_parse.callback = box move |state| {
655                     let krate = pretty::fold_crate(state.krate.take().unwrap(), ppm);
656                     pretty::print_after_parsing(state.session,
657                                                 state.input,
658                                                 &krate,
659                                                 ppm,
660                                                 state.out_file);
661                 };
662             }
663
664             return control;
665         }
666
667         if sess.opts.debugging_opts.parse_only ||
668            sess.opts.debugging_opts.show_span.is_some() ||
669            sess.opts.debugging_opts.ast_json_noexpand {
670             control.after_parse.stop = Compilation::Stop;
671         }
672
673         if sess.opts.debugging_opts.no_analysis ||
674            sess.opts.debugging_opts.ast_json {
675             control.after_hir_lowering.stop = Compilation::Stop;
676         }
677
678         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
679                                                    i == OutputType::Metadata) {
680             control.after_llvm.stop = Compilation::Stop;
681         }
682
683         if save_analysis(sess) {
684             enable_save_analysis(&mut control);
685         }
686
687         if sess.print_fuel_crate.is_some() {
688             let old_callback = control.compilation_done.callback;
689             control.compilation_done.callback = box move |state| {
690                 old_callback(state);
691                 let sess = state.session;
692                 println!("Fuel used by {}: {}",
693                     sess.print_fuel_crate.as_ref().unwrap(),
694                     sess.print_fuel.get());
695             }
696         }
697         control
698     }
699 }
700
701 pub fn enable_save_analysis(control: &mut CompileController) {
702     control.keep_ast = true;
703     control.after_analysis.callback = box |state| {
704         time(state.session.time_passes(), "save analysis", || {
705             save::process_crate(state.tcx.unwrap(),
706                                 state.expanded_crate.unwrap(),
707                                 state.analysis.unwrap(),
708                                 state.crate_name.unwrap(),
709                                 None,
710                                 DumpHandler::new(state.out_dir,
711                                                  state.crate_name.unwrap()))
712         });
713     };
714     control.after_analysis.run_callback_on_error = true;
715     control.make_glob_map = resolve::MakeGlobMap::Yes;
716 }
717
718 fn save_analysis(sess: &Session) -> bool {
719     sess.opts.debugging_opts.save_analysis
720 }
721
722 impl RustcDefaultCalls {
723     pub fn list_metadata(sess: &Session,
724                          cstore: &CrateStore,
725                          matches: &getopts::Matches,
726                          input: &Input)
727                          -> Compilation {
728         let r = matches.opt_strs("Z");
729         if r.contains(&("ls".to_string())) {
730             match input {
731                 &Input::File(ref ifile) => {
732                     let path = &(*ifile);
733                     let mut v = Vec::new();
734                     locator::list_file_metadata(&sess.target.target,
735                                                 path,
736                                                 cstore.metadata_loader(),
737                                                 &mut v)
738                             .unwrap();
739                     println!("{}", String::from_utf8(v).unwrap());
740                 }
741                 &Input::Str { .. } => {
742                     early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
743                 }
744             }
745             return Compilation::Stop;
746         }
747
748         return Compilation::Continue;
749     }
750
751
752     fn print_crate_info(sess: &Session,
753                         input: Option<&Input>,
754                         odir: &Option<PathBuf>,
755                         ofile: &Option<PathBuf>)
756                         -> Compilation {
757         // PrintRequest::NativeStaticLibs is special - printed during linking
758         // (empty iterator returns true)
759         if sess.opts.prints.iter().all(|&p| p==PrintRequest::NativeStaticLibs) {
760             return Compilation::Continue;
761         }
762
763         let attrs = match input {
764             None => None,
765             Some(input) => {
766                 let result = parse_crate_attrs(sess, input);
767                 match result {
768                     Ok(attrs) => Some(attrs),
769                     Err(mut parse_error) => {
770                         parse_error.emit();
771                         return Compilation::Stop;
772                     }
773                 }
774             }
775         };
776         for req in &sess.opts.prints {
777             match *req {
778                 PrintRequest::TargetList => {
779                     let mut targets = rustc_back::target::get_targets().collect::<Vec<String>>();
780                     targets.sort();
781                     println!("{}", targets.join("\n"));
782                 },
783                 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
784                 PrintRequest::TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
785                 PrintRequest::FileNames |
786                 PrintRequest::CrateName => {
787                     let input = match input {
788                         Some(input) => input,
789                         None => early_error(ErrorOutputType::default(), "no input file provided"),
790                     };
791                     let attrs = attrs.as_ref().unwrap();
792                     let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
793                     let id = rustc_trans_utils::link::find_crate_name(Some(sess), attrs, input);
794                     if *req == PrintRequest::CrateName {
795                         println!("{}", id);
796                         continue;
797                     }
798                     let crate_types = driver::collect_crate_types(sess, attrs);
799                     for &style in &crate_types {
800                         let fname = rustc_trans_utils::link::filename_for_input(
801                             sess,
802                             style,
803                             &id,
804                             &t_outputs
805                         );
806                         println!("{}",
807                                  fname.file_name()
808                                       .unwrap()
809                                       .to_string_lossy());
810                     }
811                 }
812                 PrintRequest::Cfg => {
813                     let allow_unstable_cfg = UnstableFeatures::from_environment()
814                         .is_nightly_build();
815
816                     let mut cfgs = Vec::new();
817                     for &(name, ref value) in sess.parse_sess.config.iter() {
818                         let gated_cfg = GatedCfg::gate(&ast::MetaItem {
819                             name,
820                             node: ast::MetaItemKind::Word,
821                             span: DUMMY_SP,
822                         });
823
824                         // Note that crt-static is a specially recognized cfg
825                         // directive that's printed out here as part of
826                         // rust-lang/rust#37406, but in general the
827                         // `target_feature` cfg is gated under
828                         // rust-lang/rust#29717. For now this is just
829                         // specifically allowing the crt-static cfg and that's
830                         // it, this is intended to get into Cargo and then go
831                         // through to build scripts.
832                         let value = value.as_ref().map(|s| s.as_str());
833                         let value = value.as_ref().map(|s| s.as_ref());
834                         if name != "target_feature" || value != Some("crt-static") {
835                             if !allow_unstable_cfg && gated_cfg.is_some() {
836                                 continue;
837                             }
838                         }
839
840                         cfgs.push(if let Some(value) = value {
841                             format!("{}=\"{}\"", name, value)
842                         } else {
843                             format!("{}", name)
844                         });
845                     }
846
847                     cfgs.sort();
848                     for cfg in cfgs {
849                         println!("{}", cfg);
850                     }
851                 }
852                 PrintRequest::RelocationModels => {
853                     println!("Available relocation models:");
854                     for &(name, _) in rustc_trans::back::write::RELOC_MODEL_ARGS.iter() {
855                         println!("    {}", name);
856                     }
857                     println!("");
858                 }
859                 PrintRequest::CodeModels => {
860                     println!("Available code models:");
861                     for &(name, _) in rustc_trans::back::write::CODE_GEN_MODEL_ARGS.iter(){
862                         println!("    {}", name);
863                     }
864                     println!("");
865                 }
866                 PrintRequest::TargetCPUs | PrintRequest::TargetFeatures => {
867                     rustc_trans::print(*req, sess);
868                 }
869                 PrintRequest::NativeStaticLibs => {
870                     println!("Native static libs can be printed only during linking");
871                 }
872             }
873         }
874         return Compilation::Stop;
875     }
876 }
877
878 /// Returns a version string such as "0.12.0-dev".
879 fn release_str() -> Option<&'static str> {
880     option_env!("CFG_RELEASE")
881 }
882
883 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
884 fn commit_hash_str() -> Option<&'static str> {
885     option_env!("CFG_VER_HASH")
886 }
887
888 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
889 fn commit_date_str() -> Option<&'static str> {
890     option_env!("CFG_VER_DATE")
891 }
892
893 /// Prints version information
894 pub fn version(binary: &str, matches: &getopts::Matches) {
895     let verbose = matches.opt_present("verbose");
896
897     println!("{} {}",
898              binary,
899              option_env!("CFG_VERSION").unwrap_or("unknown version"));
900     if verbose {
901         fn unw(x: Option<&str>) -> &str {
902             x.unwrap_or("unknown")
903         }
904         println!("binary: {}", binary);
905         println!("commit-hash: {}", unw(commit_hash_str()));
906         println!("commit-date: {}", unw(commit_date_str()));
907         println!("host: {}", config::host_triple());
908         println!("release: {}", unw(release_str()));
909         rustc_trans::print_version();
910     }
911 }
912
913 fn usage(verbose: bool, include_unstable_options: bool) {
914     let groups = if verbose {
915         config::rustc_optgroups()
916     } else {
917         config::rustc_short_optgroups()
918     };
919     let mut options = getopts::Options::new();
920     for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
921         (option.apply)(&mut options);
922     }
923     let message = format!("Usage: rustc [OPTIONS] INPUT");
924     let nightly_help = if nightly_options::is_nightly_build() {
925         "\n    -Z help             Print internal options for debugging rustc"
926     } else {
927         ""
928     };
929     let verbose_help = if verbose {
930         ""
931     } else {
932         "\n    --help -v           Print the full set of options rustc accepts"
933     };
934     println!("{}\nAdditional help:
935     -C help             Print codegen options
936     -W help             \
937               Print 'lint' options and default settings{}{}\n",
938              options.usage(&message),
939              nightly_help,
940              verbose_help);
941 }
942
943 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
944     println!("
945 Available lint options:
946     -W <foo>           Warn about <foo>
947     -A <foo>           \
948               Allow <foo>
949     -D <foo>           Deny <foo>
950     -F <foo>           Forbid <foo> \
951               (deny <foo> and all attempts to override)
952
953 ");
954
955     fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
956         let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
957         lints.sort_by(|x: &&Lint, y: &&Lint| {
958             match x.default_level.cmp(&y.default_level) {
959                 // The sort doesn't case-fold but it's doubtful we care.
960                 Equal => x.name.cmp(y.name),
961                 r => r,
962             }
963         });
964         lints
965     }
966
967     fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
968                         -> Vec<(&'static str, Vec<lint::LintId>)> {
969         let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
970         lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
971                        &(y, _): &(&'static str, Vec<lint::LintId>)| {
972             x.cmp(y)
973         });
974         lints
975     }
976
977     let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
978                                                    .iter()
979                                                    .cloned()
980                                                    .partition(|&(_, p)| p);
981     let plugin = sort_lints(plugin);
982     let builtin = sort_lints(builtin);
983
984     let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
985                                                                  .iter()
986                                                                  .cloned()
987                                                                  .partition(|&(.., p)| p);
988     let plugin_groups = sort_lint_groups(plugin_groups);
989     let builtin_groups = sort_lint_groups(builtin_groups);
990
991     let max_name_len = plugin.iter()
992                              .chain(&builtin)
993                              .map(|&s| s.name.chars().count())
994                              .max()
995                              .unwrap_or(0);
996     let padded = |x: &str| {
997         let mut s = repeat(" ")
998                         .take(max_name_len - x.chars().count())
999                         .collect::<String>();
1000         s.push_str(x);
1001         s
1002     };
1003
1004     println!("Lint checks provided by rustc:\n");
1005     println!("    {}  {:7.7}  {}", padded("name"), "default", "meaning");
1006     println!("    {}  {:7.7}  {}", padded("----"), "-------", "-------");
1007
1008     let print_lints = |lints: Vec<&Lint>| {
1009         for lint in lints {
1010             let name = lint.name_lower().replace("_", "-");
1011             println!("    {}  {:7.7}  {}",
1012                      padded(&name),
1013                      lint.default_level.as_str(),
1014                      lint.desc);
1015         }
1016         println!("\n");
1017     };
1018
1019     print_lints(builtin);
1020
1021
1022
1023     let max_name_len = max("warnings".len(),
1024                            plugin_groups.iter()
1025                                         .chain(&builtin_groups)
1026                                         .map(|&(s, _)| s.chars().count())
1027                                         .max()
1028                                         .unwrap_or(0));
1029
1030     let padded = |x: &str| {
1031         let mut s = repeat(" ")
1032                         .take(max_name_len - x.chars().count())
1033                         .collect::<String>();
1034         s.push_str(x);
1035         s
1036     };
1037
1038     println!("Lint groups provided by rustc:\n");
1039     println!("    {}  {}", padded("name"), "sub-lints");
1040     println!("    {}  {}", padded("----"), "---------");
1041     println!("    {}  {}", padded("warnings"), "all built-in lints");
1042
1043     let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
1044         for (name, to) in lints {
1045             let name = name.to_lowercase().replace("_", "-");
1046             let desc = to.into_iter()
1047                          .map(|x| x.to_string().replace("_", "-"))
1048                          .collect::<Vec<String>>()
1049                          .join(", ");
1050             println!("    {}  {}", padded(&name), desc);
1051         }
1052         println!("\n");
1053     };
1054
1055     print_lint_groups(builtin_groups);
1056
1057     match (loaded_plugins, plugin.len(), plugin_groups.len()) {
1058         (false, 0, _) | (false, _, 0) => {
1059             println!("Compiler plugins can provide additional lints and lint groups. To see a \
1060                       listing of these, re-run `rustc -W help` with a crate filename.");
1061         }
1062         (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
1063         (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
1064         (true, l, g) => {
1065             if l > 0 {
1066                 println!("Lint checks provided by plugins loaded by this crate:\n");
1067                 print_lints(plugin);
1068             }
1069             if g > 0 {
1070                 println!("Lint groups provided by plugins loaded by this crate:\n");
1071                 print_lint_groups(plugin_groups);
1072             }
1073         }
1074     }
1075 }
1076
1077 fn describe_debug_flags() {
1078     println!("\nAvailable debug options:\n");
1079     print_flag_list("-Z", config::DB_OPTIONS);
1080 }
1081
1082 fn describe_codegen_flags() {
1083     println!("\nAvailable codegen options:\n");
1084     print_flag_list("-C", config::CG_OPTIONS);
1085 }
1086
1087 fn print_flag_list<T>(cmdline_opt: &str,
1088                       flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
1089     let max_len = flag_list.iter()
1090                            .map(|&(name, _, opt_type_desc, _)| {
1091                                let extra_len = match opt_type_desc {
1092                                    Some(..) => 4,
1093                                    None => 0,
1094                                };
1095                                name.chars().count() + extra_len
1096                            })
1097                            .max()
1098                            .unwrap_or(0);
1099
1100     for &(name, _, opt_type_desc, desc) in flag_list {
1101         let (width, extra) = match opt_type_desc {
1102             Some(..) => (max_len - 4, "=val"),
1103             None => (max_len, ""),
1104         };
1105         println!("    {} {:>width$}{} -- {}",
1106                  cmdline_opt,
1107                  name.replace("_", "-"),
1108                  extra,
1109                  desc,
1110                  width = width);
1111     }
1112 }
1113
1114 /// Process command line options. Emits messages as appropriate. If compilation
1115 /// should continue, returns a getopts::Matches object parsed from args,
1116 /// otherwise returns None.
1117 ///
1118 /// The compiler's handling of options is a little complicated as it ties into
1119 /// our stability story, and it's even *more* complicated by historical
1120 /// accidents. The current intention of each compiler option is to have one of
1121 /// three modes:
1122 ///
1123 /// 1. An option is stable and can be used everywhere.
1124 /// 2. An option is unstable, but was historically allowed on the stable
1125 ///    channel.
1126 /// 3. An option is unstable, and can only be used on nightly.
1127 ///
1128 /// Like unstable library and language features, however, unstable options have
1129 /// always required a form of "opt in" to indicate that you're using them. This
1130 /// provides the easy ability to scan a code base to check to see if anything
1131 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1132 ///
1133 /// All options behind `-Z` are considered unstable by default. Other top-level
1134 /// options can also be considered unstable, and they were unlocked through the
1135 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1136 /// instability in both cases, though.
1137 ///
1138 /// So with all that in mind, the comments below have some more detail about the
1139 /// contortions done here to get things to work out correctly.
1140 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
1141     // Throw away the first argument, the name of the binary
1142     let args = &args[1..];
1143
1144     if args.is_empty() {
1145         // user did not write `-v` nor `-Z unstable-options`, so do not
1146         // include that extra information.
1147         usage(false, false);
1148         return None;
1149     }
1150
1151     // Parse with *all* options defined in the compiler, we don't worry about
1152     // option stability here we just want to parse as much as possible.
1153     let mut options = getopts::Options::new();
1154     for option in config::rustc_optgroups() {
1155         (option.apply)(&mut options);
1156     }
1157     let matches = match options.parse(args) {
1158         Ok(m) => m,
1159         Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
1160     };
1161
1162     // For all options we just parsed, we check a few aspects:
1163     //
1164     // * If the option is stable, we're all good
1165     // * If the option wasn't passed, we're all good
1166     // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1167     //   ourselves), then we require the `-Z unstable-options` flag to unlock
1168     //   this option that was passed.
1169     // * If we're a nightly compiler, then unstable options are now unlocked, so
1170     //   we're good to go.
1171     // * Otherwise, if we're a truly unstable option then we generate an error
1172     //   (unstable option being used on stable)
1173     // * If we're a historically stable-but-should-be-unstable option then we
1174     //   emit a warning that we're going to turn this into an error soon.
1175     nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1176
1177     if matches.opt_present("h") || matches.opt_present("help") {
1178         // Only show unstable options in --help if we *really* accept unstable
1179         // options, which catches the case where we got `-Z unstable-options` on
1180         // the stable channel of Rust which was accidentally allowed
1181         // historically.
1182         usage(matches.opt_present("verbose"),
1183               nightly_options::is_unstable_enabled(&matches));
1184         return None;
1185     }
1186
1187     // Don't handle -W help here, because we might first load plugins.
1188     let r = matches.opt_strs("Z");
1189     if r.iter().any(|x| *x == "help") {
1190         describe_debug_flags();
1191         return None;
1192     }
1193
1194     let cg_flags = matches.opt_strs("C");
1195     if cg_flags.iter().any(|x| *x == "help") {
1196         describe_codegen_flags();
1197         return None;
1198     }
1199
1200     if cg_flags.iter().any(|x| *x == "no-stack-check") {
1201         early_warn(ErrorOutputType::default(),
1202                    "the --no-stack-check flag is deprecated and does nothing");
1203     }
1204
1205     if cg_flags.contains(&"passes=list".to_string()) {
1206         rustc_trans::print_passes();
1207         return None;
1208     }
1209
1210     if matches.opt_present("version") {
1211         version("rustc", &matches);
1212         return None;
1213     }
1214
1215     Some(matches)
1216 }
1217
1218 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1219     match *input {
1220         Input::File(ref ifile) => {
1221             parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1222         }
1223         Input::Str { ref name, ref input } => {
1224             parse::parse_crate_attrs_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
1225         }
1226     }
1227 }
1228
1229 /// Runs `f` in a suitable thread for running `rustc`; returns a
1230 /// `Result` with either the return value of `f` or -- if a panic
1231 /// occurs -- the panic value.
1232 pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<Any + Send>>
1233     where F: FnOnce() -> R + Send + 'static,
1234           R: Send + 'static,
1235 {
1236     // Temporarily have stack size set to 16MB to deal with nom-using crates failing
1237     const STACK_SIZE: usize = 16 * 1024 * 1024; // 16MB
1238
1239     let mut cfg = thread::Builder::new().name("rustc".to_string());
1240
1241     // FIXME: Hacks on hacks. If the env is trying to override the stack size
1242     // then *don't* set it explicitly.
1243     if env::var_os("RUST_MIN_STACK").is_none() {
1244         cfg = cfg.stack_size(STACK_SIZE);
1245     }
1246
1247     let thread = cfg.spawn(f);
1248     thread.unwrap().join()
1249 }
1250
1251 /// Run a procedure which will detect panics in the compiler and print nicer
1252 /// error messages rather than just failing the test.
1253 ///
1254 /// The diagnostic emitter yielded to the procedure should be used for reporting
1255 /// errors of the compiler.
1256 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
1257     struct Sink(Arc<Mutex<Vec<u8>>>);
1258     impl Write for Sink {
1259         fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1260             Write::write(&mut *self.0.lock().unwrap(), data)
1261         }
1262         fn flush(&mut self) -> io::Result<()> {
1263             Ok(())
1264         }
1265     }
1266
1267     let data = Arc::new(Mutex::new(Vec::new()));
1268     let err = Sink(data.clone());
1269
1270     let result = in_rustc_thread(move || {
1271         io::set_panic(Some(box err));
1272         f()
1273     });
1274
1275     if let Err(value) = result {
1276         // Thread panicked without emitting a fatal diagnostic
1277         if !value.is::<errors::FatalError>() {
1278             let emitter =
1279                 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None));
1280             let handler = errors::Handler::with_emitter(true, false, emitter);
1281
1282             // a .span_bug or .bug call has already printed what
1283             // it wants to print.
1284             if !value.is::<errors::ExplicitBug>() {
1285                 handler.emit(&MultiSpan::new(),
1286                              "unexpected panic",
1287                              errors::Level::Bug);
1288             }
1289
1290             let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1291                       format!("we would appreciate a bug report: {}", BUG_REPORT_URL),
1292                       format!("rustc {} running on {}",
1293                               option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1294                               config::host_triple())];
1295             for note in &xs {
1296                 handler.emit(&MultiSpan::new(),
1297                              &note,
1298                              errors::Level::Note);
1299             }
1300             if match env::var_os("RUST_BACKTRACE") {
1301                 Some(val) => &val != "0",
1302                 None => false,
1303             } {
1304                 handler.emit(&MultiSpan::new(),
1305                              "run with `RUST_BACKTRACE=1` for a backtrace",
1306                              errors::Level::Note);
1307             }
1308
1309             writeln!(io::stderr(), "{}", str::from_utf8(&data.lock().unwrap()).unwrap()).unwrap();
1310         }
1311
1312         exit_on_err();
1313     }
1314 }
1315
1316 fn exit_on_err() -> ! {
1317     // Panic so the process returns a failure code, but don't pollute the
1318     // output with some unnecessary panic messages, we've already
1319     // printed everything that we needed to.
1320     io::set_panic(Some(box io::sink()));
1321     panic!();
1322 }
1323
1324 pub fn diagnostics_registry() -> errors::registry::Registry {
1325     use errors::registry::Registry;
1326
1327     let mut all_errors = Vec::new();
1328     all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1329     all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1330     all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
1331     all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1332     all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1333     all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
1334     all_errors.extend_from_slice(&rustc_const_eval::DIAGNOSTICS);
1335     all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1336     all_errors.extend_from_slice(&rustc_passes::DIAGNOSTICS);
1337     all_errors.extend_from_slice(&rustc_plugin::DIAGNOSTICS);
1338     all_errors.extend_from_slice(&rustc_mir::DIAGNOSTICS);
1339     all_errors.extend_from_slice(&syntax::DIAGNOSTICS);
1340
1341     Registry::new(&all_errors)
1342 }
1343
1344 pub fn get_args() -> Vec<String> {
1345     env::args_os().enumerate()
1346         .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1347              early_error(ErrorOutputType::default(),
1348                          &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1349          }))
1350         .collect()
1351 }
1352
1353 pub fn main() {
1354     env_logger::init().unwrap();
1355     let result = run(|| run_compiler(&get_args(),
1356                                      &mut RustcDefaultCalls,
1357                                      None,
1358                                      None));
1359     process::exit(result as i32);
1360 }