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