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