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