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