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