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