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