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