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