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