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