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