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