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