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