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