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