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