]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/lib.rs
Auto merge of #43724 - lukaramu:std-ops-docs, r=QuietMisdreavus
[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 #![crate_name = "rustc_driver"]
18 #![crate_type = "dylib"]
19 #![crate_type = "rlib"]
20 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
21       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
22       html_root_url = "https://doc.rust-lang.org/nightly/")]
23 #![deny(warnings)]
24
25 #![feature(box_syntax)]
26 #![feature(libc)]
27 #![feature(quote)]
28 #![feature(rustc_diagnostic_macros)]
29 #![feature(set_stdio)]
30
31 #[cfg(not(feature="llvm"))]
32 extern crate ar;
33
34 extern crate arena;
35 extern crate getopts;
36 extern crate graphviz;
37 extern crate env_logger;
38 #[cfg(not(feature="llvm"))]
39 extern crate owning_ref;
40 extern crate libc;
41 extern crate rustc;
42 extern crate rustc_allocator;
43 extern crate rustc_back;
44 extern crate rustc_borrowck;
45 extern crate rustc_const_eval;
46 extern crate rustc_data_structures;
47 extern crate rustc_errors as errors;
48 extern crate rustc_passes;
49 extern crate rustc_lint;
50 extern crate rustc_plugin;
51 extern crate rustc_privacy;
52 extern crate rustc_incremental;
53 extern crate rustc_metadata;
54 extern crate rustc_mir;
55 extern crate rustc_resolve;
56 extern crate rustc_save_analysis;
57 #[cfg(feature="llvm")]
58 extern crate rustc_trans;
59 extern crate rustc_trans_utils;
60 extern crate rustc_typeck;
61 extern crate serialize;
62 #[macro_use]
63 extern crate log;
64 extern crate syntax;
65 extern crate syntax_ext;
66 extern crate syntax_pos;
67
68 use driver::CompileController;
69 use pretty::{PpMode, UserIdentifiedItem};
70
71 use rustc_resolve as resolve;
72 use rustc_save_analysis as save;
73 use rustc_save_analysis::DumpHandler;
74 #[cfg(feature="llvm")]
75 use rustc_trans::back::write::{RELOC_MODEL_ARGS, CODE_GEN_MODEL_ARGS};
76 use rustc::dep_graph::DepGraph;
77 use rustc::session::{self, config, Session, build_session, CompileResult};
78 use rustc::session::CompileIncomplete;
79 use rustc::session::config::{Input, PrintRequest, OutputType, ErrorOutputType};
80 use rustc::session::config::nightly_options;
81 use rustc::session::{early_error, early_warn};
82 use rustc::lint::Lint;
83 use rustc::lint;
84 #[cfg(not(feature="llvm"))]
85 use rustc::middle::cstore::MetadataLoader as MetadataLoaderTrait;
86 use rustc_metadata::locator;
87 use rustc_metadata::cstore::CStore;
88 use rustc::util::common::{time, ErrorReported};
89 #[cfg(not(feature="llvm"))]
90 use rustc_back::target::Target;
91
92 use serialize::json::ToJson;
93
94 use std::any::Any;
95 use std::cmp::max;
96 use std::cmp::Ordering::Equal;
97 use std::default::Default;
98 use std::env;
99 use std::ffi::OsString;
100 use std::io::{self, Read, Write};
101 use std::iter::repeat;
102 use std::path::PathBuf;
103 #[cfg(not(feature="llvm"))]
104 use std::path::Path;
105 use std::process::{self, Command, Stdio};
106 use std::rc::Rc;
107 use std::str;
108 use std::sync::{Arc, Mutex};
109 use std::thread;
110
111 use syntax::ast;
112 use syntax::codemap::{CodeMap, FileLoader, RealFileLoader};
113 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
114 use syntax::parse::{self, PResult};
115 use syntax_pos::{DUMMY_SP, MultiSpan};
116
117 #[cfg(not(feature="llvm"))]
118 use owning_ref::{OwningRef, ErasedBoxRef};
119
120 #[cfg(test)]
121 pub mod test;
122
123 pub mod driver;
124 pub mod pretty;
125 #[cfg(feature="llvm")]
126 pub mod target_features;
127 mod derive_registrar;
128
129 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
130                                       md#bug-reports";
131
132 pub fn abort_on_err<T>(result: Result<T, CompileIncomplete>, sess: &Session) -> T {
133     match result {
134         Err(CompileIncomplete::Errored(ErrorReported)) => {
135             sess.abort_if_errors();
136             panic!("error reported but abort_if_errors didn't abort???");
137         }
138         Err(CompileIncomplete::Stopped) => {
139             sess.fatal("compilation terminated");
140         }
141         Ok(x) => x,
142     }
143 }
144
145 pub fn run<F>(run_compiler: F) -> isize
146     where F: FnOnce() -> (CompileResult, Option<Session>) + Send + 'static
147 {
148     monitor(move || {
149         let (result, session) = run_compiler();
150         if let Err(CompileIncomplete::Errored(_)) = result {
151             match session {
152                 Some(sess) => {
153                     sess.abort_if_errors();
154                     panic!("error reported but abort_if_errors didn't abort???");
155                 }
156                 None => {
157                     let emitter =
158                         errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None);
159                     let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
160                     handler.emit(&MultiSpan::new(),
161                                  "aborting due to previous error(s)",
162                                  errors::Level::Fatal);
163                     exit_on_err();
164                 }
165             }
166         }
167     });
168     0
169 }
170
171 #[cfg(not(feature="llvm"))]
172 pub struct NoLLvmMetadataLoader;
173
174 #[cfg(not(feature="llvm"))]
175 pub use NoLLvmMetadataLoader as MetadataLoader;
176 #[cfg(feature="llvm")]
177 pub use rustc_trans::LlvmMetadataLoader as MetadataLoader;
178
179 #[cfg(not(feature="llvm"))]
180 impl MetadataLoaderTrait for NoLLvmMetadataLoader {
181     fn get_rlib_metadata(&self, _: &Target, filename: &Path) -> Result<ErasedBoxRef<[u8]>, String> {
182         use std::fs::File;
183         use std::io;
184         use self::ar::Archive;
185
186         let file = File::open(filename).map_err(|e|format!("metadata file open err: {:?}", e))?;
187         let mut archive = Archive::new(file);
188
189         while let Some(entry_result) = archive.next_entry() {
190             let mut entry = entry_result.map_err(|e|format!("metadata section read err: {:?}", e))?;
191             if entry.header().identifier() == "rust.metadata.bin" {
192                 let mut buf = Vec::new();
193                 io::copy(&mut entry, &mut buf).unwrap();
194                 let buf: OwningRef<Vec<u8>, [u8]> = OwningRef::new(buf).into();
195                 return Ok(buf.map_owner_box().erase_owner());
196             }
197         }
198
199         Err("Couldnt find metadata section".to_string())
200     }
201
202     fn get_dylib_metadata(&self,
203                           _target: &Target,
204                           _filename: &Path)
205                           -> Result<ErasedBoxRef<[u8]>, String> {
206         panic!("Dylib metadata loading not supported without LLVM")
207     }
208 }
209
210 // Parse args and run the compiler. This is the primary entry point for rustc.
211 // See comments on CompilerCalls below for details about the callbacks argument.
212 // The FileLoader provides a way to load files from sources other than the file system.
213 #[cfg_attr(not(feature="llvm"), allow(unused_mut))]
214 pub fn run_compiler<'a>(args: &[String],
215                         callbacks: &mut CompilerCalls<'a>,
216                         file_loader: Option<Box<FileLoader + 'static>>,
217                         emitter_dest: Option<Box<Write + Send>>)
218                         -> (CompileResult, Option<Session>)
219 {
220     macro_rules! do_or_return {($expr: expr, $sess: expr) => {
221         match $expr {
222             Compilation::Stop => return (Ok(()), $sess),
223             Compilation::Continue => {}
224         }
225     }}
226
227     let matches = match handle_options(args) {
228         Some(matches) => matches,
229         None => return (Ok(()), None),
230     };
231
232     let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
233
234     if sopts.debugging_opts.debug_llvm {
235         #[cfg(feature="llvm")]
236         rustc_trans::enable_llvm_debug();
237     }
238
239     let descriptions = diagnostics_registry();
240
241     do_or_return!(callbacks.early_callback(&matches,
242                                            &sopts,
243                                            &cfg,
244                                            &descriptions,
245                                            sopts.error_format),
246                                            None);
247
248     let (odir, ofile) = make_output(&matches);
249     let (input, input_file_path) = match make_input(&matches.free) {
250         Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
251         None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) {
252             Some((input, input_file_path)) => (input, input_file_path),
253             None => return (Ok(()), None),
254         },
255     };
256
257     let dep_graph = DepGraph::new(sopts.build_dep_graph());
258     let cstore = Rc::new(CStore::new(&dep_graph, box ::MetadataLoader));
259
260     let loader = file_loader.unwrap_or(box RealFileLoader);
261     let codemap = Rc::new(CodeMap::with_file_loader(loader, sopts.file_path_mapping()));
262     let mut sess = session::build_session_with_codemap(
263         sopts, &dep_graph, input_file_path, descriptions, cstore.clone(), codemap, emitter_dest,
264     );
265     #[cfg(feature="llvm")]
266     rustc_trans::init(&sess);
267     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
268
269     let mut cfg = config::build_configuration(&sess, cfg);
270     #[cfg(feature="llvm")]
271     target_features::add_configuration(&mut cfg, &sess);
272     sess.parse_sess.config = cfg;
273
274     do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile), Some(sess));
275
276     let plugins = sess.opts.debugging_opts.extra_plugins.clone();
277     let control = callbacks.build_controller(&sess, &matches);
278     (driver::compile_input(&sess, &cstore, &input, &odir, &ofile, Some(plugins), &control),
279      Some(sess))
280 }
281
282 // Extract output directory and file from matches.
283 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
284     let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
285     let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
286     (odir, ofile)
287 }
288
289 // Extract input (string or file and optional path) from matches.
290 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
291     if free_matches.len() == 1 {
292         let ifile = &free_matches[0];
293         if ifile == "-" {
294             let mut src = String::new();
295             io::stdin().read_to_string(&mut src).unwrap();
296             Some((Input::Str { name: driver::anon_src(), input: src },
297                   None))
298         } else {
299             Some((Input::File(PathBuf::from(ifile)),
300                   Some(PathBuf::from(ifile))))
301         }
302     } else {
303         None
304     }
305 }
306
307 fn parse_pretty(sess: &Session,
308                 matches: &getopts::Matches)
309                 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
310     let pretty = if sess.opts.debugging_opts.unstable_options {
311         matches.opt_default("pretty", "normal").map(|a| {
312             // stable pretty-print variants only
313             pretty::parse_pretty(sess, &a, false)
314         })
315     } else {
316         None
317     };
318     if pretty.is_none() && sess.unstable_options() {
319         matches.opt_str("unpretty").map(|a| {
320             // extended with unstable pretty-print variants
321             pretty::parse_pretty(sess, &a, true)
322         })
323     } else {
324         pretty
325     }
326 }
327
328 // Whether to stop or continue compilation.
329 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
330 pub enum Compilation {
331     Stop,
332     Continue,
333 }
334
335 impl Compilation {
336     pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
337         match self {
338             Compilation::Stop => Compilation::Stop,
339             Compilation::Continue => next(),
340         }
341     }
342 }
343
344 // A trait for customising the compilation process. Offers a number of hooks for
345 // executing custom code or customising input.
346 pub trait CompilerCalls<'a> {
347     // Hook for a callback early in the process of handling arguments. This will
348     // be called straight after options have been parsed but before anything
349     // else (e.g., selecting input and output).
350     fn early_callback(&mut self,
351                       _: &getopts::Matches,
352                       _: &config::Options,
353                       _: &ast::CrateConfig,
354                       _: &errors::registry::Registry,
355                       _: ErrorOutputType)
356                       -> Compilation {
357         Compilation::Continue
358     }
359
360     // Hook for a callback late in the process of handling arguments. This will
361     // be called just before actual compilation starts (and before build_controller
362     // is called), after all arguments etc. have been completely handled.
363     fn late_callback(&mut self,
364                      _: &getopts::Matches,
365                      _: &Session,
366                      _: &Input,
367                      _: &Option<PathBuf>,
368                      _: &Option<PathBuf>)
369                      -> Compilation {
370         Compilation::Continue
371     }
372
373     // Called after we extract the input from the arguments. Gives the implementer
374     // an opportunity to change the inputs or to add some custom input handling.
375     // The default behaviour is to simply pass through the inputs.
376     fn some_input(&mut self,
377                   input: Input,
378                   input_path: Option<PathBuf>)
379                   -> (Input, Option<PathBuf>) {
380         (input, input_path)
381     }
382
383     // Called after we extract the input from the arguments if there is no valid
384     // input. Gives the implementer an opportunity to supply alternate input (by
385     // returning a Some value) or to add custom behaviour for this error such as
386     // emitting error messages. Returning None will cause compilation to stop
387     // at this point.
388     fn no_input(&mut self,
389                 _: &getopts::Matches,
390                 _: &config::Options,
391                 _: &ast::CrateConfig,
392                 _: &Option<PathBuf>,
393                 _: &Option<PathBuf>,
394                 _: &errors::registry::Registry)
395                 -> Option<(Input, Option<PathBuf>)> {
396         None
397     }
398
399     // Create a CompilController struct for controlling the behaviour of
400     // compilation.
401     fn build_controller(&mut self, _: &Session, _: &getopts::Matches) -> CompileController<'a>;
402 }
403
404 // CompilerCalls instance for a regular rustc build.
405 #[derive(Copy, Clone)]
406 pub struct RustcDefaultCalls;
407
408 // FIXME remove these and use winapi 0.3 instead
409 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
410 #[cfg(unix)]
411 fn stdout_isatty() -> bool {
412     unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
413 }
414
415 #[cfg(windows)]
416 fn stdout_isatty() -> bool {
417     type DWORD = u32;
418     type BOOL = i32;
419     type HANDLE = *mut u8;
420     type LPDWORD = *mut u32;
421     const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
422     extern "system" {
423         fn GetStdHandle(which: DWORD) -> HANDLE;
424         fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
425     }
426     unsafe {
427         let handle = GetStdHandle(STD_OUTPUT_HANDLE);
428         let mut out = 0;
429         GetConsoleMode(handle, &mut out) != 0
430     }
431 }
432
433 fn handle_explain(code: &str,
434                   descriptions: &errors::registry::Registry,
435                   output: ErrorOutputType) {
436     let normalised = if code.starts_with("E") {
437         code.to_string()
438     } else {
439         format!("E{0:0>4}", code)
440     };
441     match descriptions.find_description(&normalised) {
442         Some(ref description) => {
443             let mut is_in_code_block = false;
444             let mut text = String::new();
445
446             // Slice off the leading newline and print.
447             for line in description[1..].lines() {
448                 let indent_level = line.find(|c: char| !c.is_whitespace())
449                     .unwrap_or_else(|| line.len());
450                 let dedented_line = &line[indent_level..];
451                 if dedented_line.starts_with("```") {
452                     is_in_code_block = !is_in_code_block;
453                     text.push_str(&line[..(indent_level+3)]);
454                 } else if is_in_code_block && dedented_line.starts_with("# ") {
455                     continue;
456                 } else {
457                     text.push_str(line);
458                 }
459                 text.push('\n');
460             }
461
462             if stdout_isatty() {
463                 show_content_with_pager(&text);
464             } else {
465                 print!("{}", text);
466             }
467         }
468         None => {
469             early_error(output, &format!("no extended information for {}", code));
470         }
471     }
472 }
473
474 fn show_content_with_pager(content: &String) {
475     let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
476         OsString::from("more.com")
477     } else {
478         OsString::from("less")
479     });
480
481     let mut fallback_to_println = false;
482
483     match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
484         Ok(mut pager) => {
485             if let Some(pipe) = pager.stdin.as_mut() {
486                 if pipe.write_all(content.as_bytes()).is_err() {
487                     fallback_to_println = true;
488                 }
489             }
490
491             if pager.wait().is_err() {
492                 fallback_to_println = true;
493             }
494         }
495         Err(_) => {
496             fallback_to_println = true;
497         }
498     }
499
500     // If pager fails for whatever reason, we should still print the content
501     // to standard output
502     if fallback_to_println {
503         print!("{}", content);
504     }
505 }
506
507 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
508     fn early_callback(&mut self,
509                       matches: &getopts::Matches,
510                       _: &config::Options,
511                       _: &ast::CrateConfig,
512                       descriptions: &errors::registry::Registry,
513                       output: ErrorOutputType)
514                       -> Compilation {
515         if let Some(ref code) = matches.opt_str("explain") {
516             handle_explain(code, descriptions, output);
517             return Compilation::Stop;
518         }
519
520         Compilation::Continue
521     }
522
523     #[cfg_attr(not(feature="llvm"), allow(unused_mut))]
524     fn no_input(&mut self,
525                 matches: &getopts::Matches,
526                 sopts: &config::Options,
527                 cfg: &ast::CrateConfig,
528                 odir: &Option<PathBuf>,
529                 ofile: &Option<PathBuf>,
530                 descriptions: &errors::registry::Registry)
531                 -> Option<(Input, Option<PathBuf>)> {
532         match matches.free.len() {
533             0 => {
534                 if sopts.describe_lints {
535                     let mut ls = lint::LintStore::new();
536                     rustc_lint::register_builtins(&mut ls, None);
537                     describe_lints(&ls, false);
538                     return None;
539                 }
540                 let dep_graph = DepGraph::new(sopts.build_dep_graph());
541                 let cstore = Rc::new(CStore::new(&dep_graph, box ::MetadataLoader));
542                 let mut sess = build_session(sopts.clone(),
543                     &dep_graph,
544                     None,
545                     descriptions.clone(),
546                     cstore.clone());
547                 #[cfg(feature="llvm")]
548                 rustc_trans::init(&sess);
549                 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
550                 let mut cfg = config::build_configuration(&sess, cfg.clone());
551                 #[cfg(feature="llvm")]
552                 target_features::add_configuration(&mut cfg, &sess);
553                 sess.parse_sess.config = cfg;
554                 let should_stop =
555                     RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
556
557                 if should_stop == Compilation::Stop {
558                     return None;
559                 }
560                 early_error(sopts.error_format, "no input filename given");
561             }
562             1 => panic!("make_input should have provided valid inputs"),
563             _ => early_error(sopts.error_format, "multiple input filenames provided"),
564         }
565     }
566
567     fn late_callback(&mut self,
568                      matches: &getopts::Matches,
569                      sess: &Session,
570                      input: &Input,
571                      odir: &Option<PathBuf>,
572                      ofile: &Option<PathBuf>)
573                      -> Compilation {
574         RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
575             .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input))
576     }
577
578     fn build_controller(&mut self,
579                         sess: &Session,
580                         matches: &getopts::Matches)
581                         -> CompileController<'a> {
582         let mut control = CompileController::basic();
583
584         control.keep_ast = sess.opts.debugging_opts.keep_ast;
585         control.continue_parse_after_error = sess.opts.debugging_opts.continue_parse_after_error;
586
587         if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
588             if ppm.needs_ast_map(&opt_uii) {
589                 control.after_hir_lowering.stop = Compilation::Stop;
590
591                 control.after_parse.callback = box move |state| {
592                     state.krate = Some(pretty::fold_crate(state.krate.take().unwrap(), ppm));
593                 };
594                 control.after_hir_lowering.callback = box move |state| {
595                     pretty::print_after_hir_lowering(state.session,
596                                                      state.hir_map.unwrap(),
597                                                      state.analysis.unwrap(),
598                                                      state.resolutions.unwrap(),
599                                                      state.input,
600                                                      &state.expanded_crate.take().unwrap(),
601                                                      state.crate_name.unwrap(),
602                                                      ppm,
603                                                      state.arena.unwrap(),
604                                                      state.arenas.unwrap(),
605                                                      opt_uii.clone(),
606                                                      state.out_file);
607                 };
608             } else {
609                 control.after_parse.stop = Compilation::Stop;
610
611                 control.after_parse.callback = box move |state| {
612                     let krate = pretty::fold_crate(state.krate.take().unwrap(), ppm);
613                     pretty::print_after_parsing(state.session,
614                                                 state.input,
615                                                 &krate,
616                                                 ppm,
617                                                 state.out_file);
618                 };
619             }
620
621             return control;
622         }
623
624         if sess.opts.debugging_opts.parse_only ||
625            sess.opts.debugging_opts.show_span.is_some() ||
626            sess.opts.debugging_opts.ast_json_noexpand {
627             control.after_parse.stop = Compilation::Stop;
628         }
629
630         if sess.opts.debugging_opts.no_analysis ||
631            sess.opts.debugging_opts.ast_json {
632             control.after_hir_lowering.stop = Compilation::Stop;
633         }
634
635         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
636                                                    i == OutputType::Metadata) {
637             control.after_llvm.stop = Compilation::Stop;
638         }
639
640         if save_analysis(sess) {
641             enable_save_analysis(&mut control);
642         }
643
644         if sess.print_fuel_crate.is_some() {
645             let old_callback = control.compilation_done.callback;
646             control.compilation_done.callback = box move |state| {
647                 old_callback(state);
648                 let sess = state.session;
649                 println!("Fuel used by {}: {}",
650                     sess.print_fuel_crate.as_ref().unwrap(),
651                     sess.print_fuel.get());
652             }
653         }
654         control
655     }
656 }
657
658 pub fn enable_save_analysis(control: &mut CompileController) {
659     control.keep_ast = true;
660     control.after_analysis.callback = box |state| {
661         time(state.session.time_passes(), "save analysis", || {
662             save::process_crate(state.tcx.unwrap(),
663                                 state.expanded_crate.unwrap(),
664                                 state.analysis.unwrap(),
665                                 state.crate_name.unwrap(),
666                                 None,
667                                 DumpHandler::new(state.out_dir,
668                                                  state.crate_name.unwrap()))
669         });
670     };
671     control.after_analysis.run_callback_on_error = true;
672     control.make_glob_map = resolve::MakeGlobMap::Yes;
673 }
674
675 fn save_analysis(sess: &Session) -> bool {
676     sess.opts.debugging_opts.save_analysis
677 }
678
679 impl RustcDefaultCalls {
680     pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation {
681         let r = matches.opt_strs("Z");
682         if r.contains(&("ls".to_string())) {
683             match input {
684                 &Input::File(ref ifile) => {
685                     let path = &(*ifile);
686                     let mut v = Vec::new();
687                     locator::list_file_metadata(&sess.target.target,
688                                                 path,
689                                                 sess.cstore.metadata_loader(),
690                                                 &mut v)
691                             .unwrap();
692                     println!("{}", String::from_utf8(v).unwrap());
693                 }
694                 &Input::Str { .. } => {
695                     early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
696                 }
697             }
698             return Compilation::Stop;
699         }
700
701         return Compilation::Continue;
702     }
703
704
705     fn print_crate_info(sess: &Session,
706                         input: Option<&Input>,
707                         odir: &Option<PathBuf>,
708                         ofile: &Option<PathBuf>)
709                         -> Compilation {
710         if sess.opts.prints.is_empty() {
711             return Compilation::Continue;
712         }
713
714         let attrs = match input {
715             None => None,
716             Some(input) => {
717                 let result = parse_crate_attrs(sess, input);
718                 match result {
719                     Ok(attrs) => Some(attrs),
720                     Err(mut parse_error) => {
721                         parse_error.emit();
722                         return Compilation::Stop;
723                     }
724                 }
725             }
726         };
727         for req in &sess.opts.prints {
728             match *req {
729                 PrintRequest::TargetList => {
730                     let mut targets = rustc_back::target::get_targets().collect::<Vec<String>>();
731                     targets.sort();
732                     println!("{}", targets.join("\n"));
733                 },
734                 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
735                 PrintRequest::TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
736                 PrintRequest::FileNames |
737                 PrintRequest::CrateName => {
738                     let input = match input {
739                         Some(input) => input,
740                         None => early_error(ErrorOutputType::default(), "no input file provided"),
741                     };
742                     let attrs = attrs.as_ref().unwrap();
743                     let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
744                     let id = rustc_trans_utils::link::find_crate_name(Some(sess), attrs, input);
745                     if *req == PrintRequest::CrateName {
746                         println!("{}", id);
747                         continue;
748                     }
749                     let crate_types = driver::collect_crate_types(sess, attrs);
750                     for &style in &crate_types {
751                         let fname = rustc_trans_utils::link::filename_for_input(
752                             sess,
753                             style,
754                             &id,
755                             &t_outputs
756                         );
757                         println!("{}",
758                                  fname.file_name()
759                                       .unwrap()
760                                       .to_string_lossy());
761                     }
762                 }
763                 PrintRequest::Cfg => {
764                     let allow_unstable_cfg = UnstableFeatures::from_environment()
765                         .is_nightly_build();
766
767                     let mut cfgs = Vec::new();
768                     for &(name, ref value) in sess.parse_sess.config.iter() {
769                         let gated_cfg = GatedCfg::gate(&ast::MetaItem {
770                             name: name,
771                             node: ast::MetaItemKind::Word,
772                             span: DUMMY_SP,
773                         });
774
775                         // Note that crt-static is a specially recognized cfg
776                         // directive that's printed out here as part of
777                         // rust-lang/rust#37406, but in general the
778                         // `target_feature` cfg is gated under
779                         // rust-lang/rust#29717. For now this is just
780                         // specifically allowing the crt-static cfg and that's
781                         // it, this is intended to get into Cargo and then go
782                         // through to build scripts.
783                         let value = value.as_ref().map(|s| s.as_str());
784                         let value = value.as_ref().map(|s| s.as_ref());
785                         if name != "target_feature" || value != Some("crt-static") {
786                             if !allow_unstable_cfg && gated_cfg.is_some() {
787                                 continue;
788                             }
789                         }
790
791                         cfgs.push(if let Some(value) = value {
792                             format!("{}=\"{}\"", name, value)
793                         } else {
794                             format!("{}", name)
795                         });
796                     }
797
798                     cfgs.sort();
799                     for cfg in cfgs {
800                         println!("{}", cfg);
801                     }
802                 }
803                 PrintRequest::RelocationModels => {
804                     println!("Available relocation models:");
805                     #[cfg(feature="llvm")]
806                     for &(name, _) in RELOC_MODEL_ARGS.iter() {
807                         println!("    {}", name);
808                     }
809                     println!("");
810                 }
811                 PrintRequest::CodeModels => {
812                     println!("Available code models:");
813                     #[cfg(feature="llvm")]
814                     for &(name, _) in CODE_GEN_MODEL_ARGS.iter(){
815                         println!("    {}", name);
816                     }
817                     println!("");
818                 }
819                 PrintRequest::TargetCPUs | PrintRequest::TargetFeatures => {
820                     #[cfg(feature="llvm")]
821                     rustc_trans::print(*req, sess);
822                     #[cfg(not(feature="llvm"))]
823                     panic!("LLVM not supported by this rustc")
824                 }
825             }
826         }
827         return Compilation::Stop;
828     }
829 }
830
831 /// Returns a version string such as "0.12.0-dev".
832 pub fn release_str() -> Option<&'static str> {
833     option_env!("CFG_RELEASE")
834 }
835
836 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
837 pub fn commit_hash_str() -> Option<&'static str> {
838     option_env!("CFG_VER_HASH")
839 }
840
841 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
842 pub fn commit_date_str() -> Option<&'static str> {
843     option_env!("CFG_VER_DATE")
844 }
845
846 /// Prints version information
847 pub fn version(binary: &str, matches: &getopts::Matches) {
848     let verbose = matches.opt_present("verbose");
849
850     println!("{} {}",
851              binary,
852              option_env!("CFG_VERSION").unwrap_or("unknown version"));
853     if verbose {
854         fn unw(x: Option<&str>) -> &str {
855             x.unwrap_or("unknown")
856         }
857         println!("binary: {}", binary);
858         println!("commit-hash: {}", unw(commit_hash_str()));
859         println!("commit-date: {}", unw(commit_date_str()));
860         println!("host: {}", config::host_triple());
861         println!("release: {}", unw(release_str()));
862         #[cfg(feature="llvm")]
863         rustc_trans::print_version();
864     }
865 }
866
867 fn usage(verbose: bool, include_unstable_options: bool) {
868     let groups = if verbose {
869         config::rustc_optgroups()
870     } else {
871         config::rustc_short_optgroups()
872     };
873     let mut options = getopts::Options::new();
874     for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
875         (option.apply)(&mut options);
876     }
877     let message = format!("Usage: rustc [OPTIONS] INPUT");
878     let nightly_help = if nightly_options::is_nightly_build() {
879         "\n    -Z help             Print internal options for debugging rustc"
880     } else {
881         ""
882     };
883     let verbose_help = if verbose {
884         ""
885     } else {
886         "\n    --help -v           Print the full set of options rustc accepts"
887     };
888     println!("{}\nAdditional help:
889     -C help             Print codegen options
890     -W help             \
891               Print 'lint' options and default settings{}{}\n",
892              options.usage(&message),
893              nightly_help,
894              verbose_help);
895 }
896
897 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
898     println!("
899 Available lint options:
900     -W <foo>           Warn about <foo>
901     -A <foo>           \
902               Allow <foo>
903     -D <foo>           Deny <foo>
904     -F <foo>           Forbid <foo> \
905               (deny <foo> and all attempts to override)
906
907 ");
908
909     fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
910         let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
911         lints.sort_by(|x: &&Lint, y: &&Lint| {
912             match x.default_level.cmp(&y.default_level) {
913                 // The sort doesn't case-fold but it's doubtful we care.
914                 Equal => x.name.cmp(y.name),
915                 r => r,
916             }
917         });
918         lints
919     }
920
921     fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
922                         -> Vec<(&'static str, Vec<lint::LintId>)> {
923         let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
924         lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
925                        &(y, _): &(&'static str, Vec<lint::LintId>)| {
926             x.cmp(y)
927         });
928         lints
929     }
930
931     let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
932                                                    .iter()
933                                                    .cloned()
934                                                    .partition(|&(_, p)| p);
935     let plugin = sort_lints(plugin);
936     let builtin = sort_lints(builtin);
937
938     let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
939                                                                  .iter()
940                                                                  .cloned()
941                                                                  .partition(|&(.., p)| p);
942     let plugin_groups = sort_lint_groups(plugin_groups);
943     let builtin_groups = sort_lint_groups(builtin_groups);
944
945     let max_name_len = plugin.iter()
946                              .chain(&builtin)
947                              .map(|&s| s.name.chars().count())
948                              .max()
949                              .unwrap_or(0);
950     let padded = |x: &str| {
951         let mut s = repeat(" ")
952                         .take(max_name_len - x.chars().count())
953                         .collect::<String>();
954         s.push_str(x);
955         s
956     };
957
958     println!("Lint checks provided by rustc:\n");
959     println!("    {}  {:7.7}  {}", padded("name"), "default", "meaning");
960     println!("    {}  {:7.7}  {}", padded("----"), "-------", "-------");
961
962     let print_lints = |lints: Vec<&Lint>| {
963         for lint in lints {
964             let name = lint.name_lower().replace("_", "-");
965             println!("    {}  {:7.7}  {}",
966                      padded(&name),
967                      lint.default_level.as_str(),
968                      lint.desc);
969         }
970         println!("\n");
971     };
972
973     print_lints(builtin);
974
975
976
977     let max_name_len = max("warnings".len(),
978                            plugin_groups.iter()
979                                         .chain(&builtin_groups)
980                                         .map(|&(s, _)| s.chars().count())
981                                         .max()
982                                         .unwrap_or(0));
983
984     let padded = |x: &str| {
985         let mut s = repeat(" ")
986                         .take(max_name_len - x.chars().count())
987                         .collect::<String>();
988         s.push_str(x);
989         s
990     };
991
992     println!("Lint groups provided by rustc:\n");
993     println!("    {}  {}", padded("name"), "sub-lints");
994     println!("    {}  {}", padded("----"), "---------");
995     println!("    {}  {}", padded("warnings"), "all built-in lints");
996
997     let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
998         for (name, to) in lints {
999             let name = name.to_lowercase().replace("_", "-");
1000             let desc = to.into_iter()
1001                          .map(|x| x.to_string().replace("_", "-"))
1002                          .collect::<Vec<String>>()
1003                          .join(", ");
1004             println!("    {}  {}", padded(&name), desc);
1005         }
1006         println!("\n");
1007     };
1008
1009     print_lint_groups(builtin_groups);
1010
1011     match (loaded_plugins, plugin.len(), plugin_groups.len()) {
1012         (false, 0, _) | (false, _, 0) => {
1013             println!("Compiler plugins can provide additional lints and lint groups. To see a \
1014                       listing of these, re-run `rustc -W help` with a crate filename.");
1015         }
1016         (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
1017         (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
1018         (true, l, g) => {
1019             if l > 0 {
1020                 println!("Lint checks provided by plugins loaded by this crate:\n");
1021                 print_lints(plugin);
1022             }
1023             if g > 0 {
1024                 println!("Lint groups provided by plugins loaded by this crate:\n");
1025                 print_lint_groups(plugin_groups);
1026             }
1027         }
1028     }
1029 }
1030
1031 fn describe_debug_flags() {
1032     println!("\nAvailable debug options:\n");
1033     print_flag_list("-Z", config::DB_OPTIONS);
1034 }
1035
1036 fn describe_codegen_flags() {
1037     println!("\nAvailable codegen options:\n");
1038     print_flag_list("-C", config::CG_OPTIONS);
1039 }
1040
1041 fn print_flag_list<T>(cmdline_opt: &str,
1042                       flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
1043     let max_len = flag_list.iter()
1044                            .map(|&(name, _, opt_type_desc, _)| {
1045                                let extra_len = match opt_type_desc {
1046                                    Some(..) => 4,
1047                                    None => 0,
1048                                };
1049                                name.chars().count() + extra_len
1050                            })
1051                            .max()
1052                            .unwrap_or(0);
1053
1054     for &(name, _, opt_type_desc, desc) in flag_list {
1055         let (width, extra) = match opt_type_desc {
1056             Some(..) => (max_len - 4, "=val"),
1057             None => (max_len, ""),
1058         };
1059         println!("    {} {:>width$}{} -- {}",
1060                  cmdline_opt,
1061                  name.replace("_", "-"),
1062                  extra,
1063                  desc,
1064                  width = width);
1065     }
1066 }
1067
1068 /// Process command line options. Emits messages as appropriate. If compilation
1069 /// should continue, returns a getopts::Matches object parsed from args,
1070 /// otherwise returns None.
1071 ///
1072 /// The compiler's handling of options is a little complicated as it ties into
1073 /// our stability story, and it's even *more* complicated by historical
1074 /// accidents. The current intention of each compiler option is to have one of
1075 /// three modes:
1076 ///
1077 /// 1. An option is stable and can be used everywhere.
1078 /// 2. An option is unstable, but was historically allowed on the stable
1079 ///    channel.
1080 /// 3. An option is unstable, and can only be used on nightly.
1081 ///
1082 /// Like unstable library and language features, however, unstable options have
1083 /// always required a form of "opt in" to indicate that you're using them. This
1084 /// provides the easy ability to scan a code base to check to see if anything
1085 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1086 ///
1087 /// All options behind `-Z` are considered unstable by default. Other top-level
1088 /// options can also be considered unstable, and they were unlocked through the
1089 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1090 /// instability in both cases, though.
1091 ///
1092 /// So with all that in mind, the comments below have some more detail about the
1093 /// contortions done here to get things to work out correctly.
1094 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
1095     // Throw away the first argument, the name of the binary
1096     let args = &args[1..];
1097
1098     if args.is_empty() {
1099         // user did not write `-v` nor `-Z unstable-options`, so do not
1100         // include that extra information.
1101         usage(false, false);
1102         return None;
1103     }
1104
1105     // Parse with *all* options defined in the compiler, we don't worry about
1106     // option stability here we just want to parse as much as possible.
1107     let mut options = getopts::Options::new();
1108     for option in config::rustc_optgroups() {
1109         (option.apply)(&mut options);
1110     }
1111     let matches = match options.parse(args) {
1112         Ok(m) => m,
1113         Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
1114     };
1115
1116     // For all options we just parsed, we check a few aspects:
1117     //
1118     // * If the option is stable, we're all good
1119     // * If the option wasn't passed, we're all good
1120     // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1121     //   ourselves), then we require the `-Z unstable-options` flag to unlock
1122     //   this option that was passed.
1123     // * If we're a nightly compiler, then unstable options are now unlocked, so
1124     //   we're good to go.
1125     // * Otherwise, if we're a truly unstable option then we generate an error
1126     //   (unstable option being used on stable)
1127     // * If we're a historically stable-but-should-be-unstable option then we
1128     //   emit a warning that we're going to turn this into an error soon.
1129     nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1130
1131     if matches.opt_present("h") || matches.opt_present("help") {
1132         // Only show unstable options in --help if we *really* accept unstable
1133         // options, which catches the case where we got `-Z unstable-options` on
1134         // the stable channel of Rust which was accidentally allowed
1135         // historically.
1136         usage(matches.opt_present("verbose"),
1137               nightly_options::is_unstable_enabled(&matches));
1138         return None;
1139     }
1140
1141     // Don't handle -W help here, because we might first load plugins.
1142     let r = matches.opt_strs("Z");
1143     if r.iter().any(|x| *x == "help") {
1144         describe_debug_flags();
1145         return None;
1146     }
1147
1148     let cg_flags = matches.opt_strs("C");
1149     if cg_flags.iter().any(|x| *x == "help") {
1150         describe_codegen_flags();
1151         return None;
1152     }
1153
1154     if cg_flags.iter().any(|x| *x == "no-stack-check") {
1155         early_warn(ErrorOutputType::default(),
1156                    "the --no-stack-check flag is deprecated and does nothing");
1157     }
1158
1159     if cg_flags.contains(&"passes=list".to_string()) {
1160         #[cfg(feature="llvm")]
1161         rustc_trans::print_passes();
1162         return None;
1163     }
1164
1165     if matches.opt_present("version") {
1166         version("rustc", &matches);
1167         return None;
1168     }
1169
1170     Some(matches)
1171 }
1172
1173 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1174     match *input {
1175         Input::File(ref ifile) => {
1176             parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1177         }
1178         Input::Str { ref name, ref input } => {
1179             parse::parse_crate_attrs_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
1180         }
1181     }
1182 }
1183
1184 /// Runs `f` in a suitable thread for running `rustc`; returns a
1185 /// `Result` with either the return value of `f` or -- if a panic
1186 /// occurs -- the panic value.
1187 pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<Any + Send>>
1188     where F: FnOnce() -> R + Send + 'static,
1189           R: Send + 'static,
1190 {
1191     // Temporarily have stack size set to 16MB to deal with nom-using crates failing
1192     const STACK_SIZE: usize = 16 * 1024 * 1024; // 16MB
1193
1194     let mut cfg = thread::Builder::new().name("rustc".to_string());
1195
1196     // FIXME: Hacks on hacks. If the env is trying to override the stack size
1197     // then *don't* set it explicitly.
1198     if env::var_os("RUST_MIN_STACK").is_none() {
1199         cfg = cfg.stack_size(STACK_SIZE);
1200     }
1201
1202     let thread = cfg.spawn(f);
1203     thread.unwrap().join()
1204 }
1205
1206 /// Run a procedure which will detect panics in the compiler and print nicer
1207 /// error messages rather than just failing the test.
1208 ///
1209 /// The diagnostic emitter yielded to the procedure should be used for reporting
1210 /// errors of the compiler.
1211 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
1212     struct Sink(Arc<Mutex<Vec<u8>>>);
1213     impl Write for Sink {
1214         fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1215             Write::write(&mut *self.0.lock().unwrap(), data)
1216         }
1217         fn flush(&mut self) -> io::Result<()> {
1218             Ok(())
1219         }
1220     }
1221
1222     let data = Arc::new(Mutex::new(Vec::new()));
1223     let err = Sink(data.clone());
1224
1225     let result = in_rustc_thread(move || {
1226         io::set_panic(Some(box err));
1227         f()
1228     });
1229
1230     if let Err(value) = result {
1231         // Thread panicked without emitting a fatal diagnostic
1232         if !value.is::<errors::FatalError>() {
1233             let emitter =
1234                 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None));
1235             let handler = errors::Handler::with_emitter(true, false, emitter);
1236
1237             // a .span_bug or .bug call has already printed what
1238             // it wants to print.
1239             if !value.is::<errors::ExplicitBug>() {
1240                 handler.emit(&MultiSpan::new(),
1241                              "unexpected panic",
1242                              errors::Level::Bug);
1243             }
1244
1245             let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1246                       format!("we would appreciate a bug report: {}", BUG_REPORT_URL),
1247                       format!("rustc {} running on {}",
1248                               option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1249                               config::host_triple())];
1250             for note in &xs {
1251                 handler.emit(&MultiSpan::new(),
1252                              &note,
1253                              errors::Level::Note);
1254             }
1255             if match env::var_os("RUST_BACKTRACE") {
1256                 Some(val) => &val != "0",
1257                 None => false,
1258             } {
1259                 handler.emit(&MultiSpan::new(),
1260                              "run with `RUST_BACKTRACE=1` for a backtrace",
1261                              errors::Level::Note);
1262             }
1263
1264             writeln!(io::stderr(), "{}", str::from_utf8(&data.lock().unwrap()).unwrap()).unwrap();
1265         }
1266
1267         exit_on_err();
1268     }
1269 }
1270
1271 fn exit_on_err() -> ! {
1272     // Panic so the process returns a failure code, but don't pollute the
1273     // output with some unnecessary panic messages, we've already
1274     // printed everything that we needed to.
1275     io::set_panic(Some(box io::sink()));
1276     panic!();
1277 }
1278
1279 pub fn diagnostics_registry() -> errors::registry::Registry {
1280     use errors::registry::Registry;
1281
1282     let mut all_errors = Vec::new();
1283     all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1284     all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1285     all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
1286     all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1287     all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1288     #[cfg(feature="llvm")]
1289     all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
1290     all_errors.extend_from_slice(&rustc_const_eval::DIAGNOSTICS);
1291     all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1292     all_errors.extend_from_slice(&rustc_passes::DIAGNOSTICS);
1293     all_errors.extend_from_slice(&rustc_plugin::DIAGNOSTICS);
1294     all_errors.extend_from_slice(&rustc_mir::DIAGNOSTICS);
1295     all_errors.extend_from_slice(&syntax::DIAGNOSTICS);
1296
1297     Registry::new(&all_errors)
1298 }
1299
1300 pub fn get_args() -> Vec<String> {
1301     env::args_os().enumerate()
1302         .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1303              early_error(ErrorOutputType::default(),
1304                          &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1305          }))
1306         .collect()
1307 }
1308
1309 pub fn main() {
1310     env_logger::init().unwrap();
1311     let result = run(|| run_compiler(&get_args(),
1312                                      &mut RustcDefaultCalls,
1313                                      None,
1314                                      None));
1315     process::exit(result as i32);
1316 }