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