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