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