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