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