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