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