]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/lib.rs
Replace all uses of SHA-256 with BLAKE2b.
[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 #![unstable(feature = "rustc_private", issue = "27812")]
19 #![crate_type = "dylib"]
20 #![crate_type = "rlib"]
21 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
22       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
23       html_root_url = "https://doc.rust-lang.org/nightly/")]
24 #![cfg_attr(not(stage0), deny(warnings))]
25
26 #![feature(box_syntax)]
27 #![feature(dotdot_in_tuple_patterns)]
28 #![feature(libc)]
29 #![feature(quote)]
30 #![feature(rustc_diagnostic_macros)]
31 #![feature(rustc_private)]
32 #![feature(set_stdio)]
33 #![feature(staged_api)]
34 #![cfg_attr(stage0, feature(question_mark))]
35
36 extern crate arena;
37 extern crate flate;
38 extern crate getopts;
39 extern crate graphviz;
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 extern crate rustc_llvm as llvm;
60 #[macro_use]
61 extern crate log;
62 #[macro_use]
63 extern crate syntax;
64 extern crate syntax_ext;
65 extern crate syntax_pos;
66
67 use driver::CompileController;
68 use pretty::{PpMode, UserIdentifiedItem};
69
70 use rustc_resolve as resolve;
71 use rustc_save_analysis as save;
72 use rustc_trans::back::link;
73 use rustc_trans::back::write::{create_target_machine, RELOC_MODEL_ARGS, CODE_GEN_MODEL_ARGS};
74 use rustc::dep_graph::DepGraph;
75 use rustc::session::{self, config, Session, build_session, CompileResult};
76 use rustc::session::config::{Input, PrintRequest, OutputType, ErrorOutputType};
77 use rustc::session::config::nightly_options;
78 use rustc::session::early_error;
79 use rustc::lint::Lint;
80 use rustc::lint;
81 use rustc_metadata::locator;
82 use rustc_metadata::cstore::CStore;
83 use rustc::util::common::time;
84
85 use std::cmp::max;
86 use std::cmp::Ordering::Equal;
87 use std::default::Default;
88 use std::env;
89 use std::io::{self, Read, Write};
90 use std::iter::repeat;
91 use std::path::PathBuf;
92 use std::process;
93 use std::rc::Rc;
94 use std::str;
95 use std::sync::{Arc, Mutex};
96 use std::thread;
97
98 use syntax::{ast, json};
99 use syntax::codemap::{CodeMap, FileLoader, RealFileLoader};
100 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
101 use syntax::parse::{self, PResult};
102 use syntax_pos::MultiSpan;
103 use errors::emitter::Emitter;
104
105 #[cfg(test)]
106 pub mod test;
107
108 pub mod driver;
109 pub mod pretty;
110 pub mod target_features;
111 mod derive_registrar;
112
113 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
114                                       md#bug-reports";
115
116 #[inline]
117 fn abort_msg(err_count: usize) -> String {
118     match err_count {
119         0 => "aborting with no errors (maybe a bug?)".to_owned(),
120         1 => "aborting due to previous error".to_owned(),
121         e => format!("aborting due to {} previous errors", e),
122     }
123 }
124
125 pub fn abort_on_err<T>(result: Result<T, usize>, sess: &Session) -> T {
126     match result {
127         Err(err_count) => {
128             sess.fatal(&abort_msg(err_count));
129         }
130         Ok(x) => x,
131     }
132 }
133
134 pub fn run<F>(run_compiler: F) -> isize
135     where F: FnOnce() -> (CompileResult, Option<Session>) + Send + 'static
136 {
137     monitor(move || {
138         let (result, session) = run_compiler();
139         if let Err(err_count) = result {
140             if err_count > 0 {
141                 match session {
142                     Some(sess) => sess.fatal(&abort_msg(err_count)),
143                     None => {
144                         let emitter =
145                             errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None);
146                         let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
147                         handler.emit(&MultiSpan::new(),
148                                      &abort_msg(err_count),
149                                      errors::Level::Fatal);
150                         exit_on_err();
151                     }
152                 }
153             }
154         }
155     });
156     0
157 }
158
159 // Parse args and run the compiler. This is the primary entry point for rustc.
160 // See comments on CompilerCalls below for details about the callbacks argument.
161 // The FileLoader provides a way to load files from sources other than the file system.
162 pub fn run_compiler<'a>(args: &[String],
163                         callbacks: &mut CompilerCalls<'a>,
164                         file_loader: Option<Box<FileLoader + 'static>>,
165                         emitter_dest: Option<Box<Write + Send>>)
166                         -> (CompileResult, Option<Session>)
167 {
168     macro_rules! do_or_return {($expr: expr, $sess: expr) => {
169         match $expr {
170             Compilation::Stop => return (Ok(()), $sess),
171             Compilation::Continue => {}
172         }
173     }}
174
175     let matches = match handle_options(args) {
176         Some(matches) => matches,
177         None => return (Ok(()), None),
178     };
179
180     let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
181
182     if sopts.debugging_opts.debug_llvm {
183         unsafe { llvm::LLVMRustSetDebug(1); }
184     }
185
186     let descriptions = diagnostics_registry();
187
188     do_or_return!(callbacks.early_callback(&matches,
189                                            &sopts,
190                                            &cfg,
191                                            &descriptions,
192                                            sopts.error_format),
193                                            None);
194
195     let (odir, ofile) = make_output(&matches);
196     let (input, input_file_path) = match make_input(&matches.free) {
197         Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
198         None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) {
199             Some((input, input_file_path)) => (input, input_file_path),
200             None => return (Ok(()), None),
201         },
202     };
203
204     let dep_graph = DepGraph::new(sopts.build_dep_graph());
205     let cstore = Rc::new(CStore::new(&dep_graph));
206
207     let loader = file_loader.unwrap_or(box RealFileLoader);
208     let codemap = Rc::new(CodeMap::with_file_loader(loader));
209     let mut sess = session::build_session_with_codemap(
210         sopts, &dep_graph, input_file_path, descriptions, cstore.clone(), codemap, emitter_dest,
211     );
212     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
213
214     let mut cfg = config::build_configuration(&sess, cfg);
215     target_features::add_configuration(&mut cfg, &sess);
216     sess.parse_sess.config = cfg;
217
218     do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile), Some(sess));
219
220     let plugins = sess.opts.debugging_opts.extra_plugins.clone();
221     let control = callbacks.build_controller(&sess, &matches);
222     (driver::compile_input(&sess, &cstore, &input, &odir, &ofile, Some(plugins), &control),
223      Some(sess))
224 }
225
226 // Extract output directory and file from matches.
227 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
228     let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
229     let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
230     (odir, ofile)
231 }
232
233 // Extract input (string or file and optional path) from matches.
234 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
235     if free_matches.len() == 1 {
236         let ifile = &free_matches[0][..];
237         if ifile == "-" {
238             let mut src = String::new();
239             io::stdin().read_to_string(&mut src).unwrap();
240             Some((Input::Str { name: driver::anon_src(), input: src },
241                   None))
242         } else {
243             Some((Input::File(PathBuf::from(ifile)),
244                   Some(PathBuf::from(ifile))))
245         }
246     } else {
247         None
248     }
249 }
250
251 fn parse_pretty(sess: &Session,
252                 matches: &getopts::Matches)
253                 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
254     let pretty = if sess.opts.debugging_opts.unstable_options {
255         matches.opt_default("pretty", "normal").map(|a| {
256             // stable pretty-print variants only
257             pretty::parse_pretty(sess, &a, false)
258         })
259     } else {
260         None
261     };
262     if pretty.is_none() && sess.unstable_options() {
263         matches.opt_str("unpretty").map(|a| {
264             // extended with unstable pretty-print variants
265             pretty::parse_pretty(sess, &a, true)
266         })
267     } else {
268         pretty
269     }
270 }
271
272 // Whether to stop or continue compilation.
273 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
274 pub enum Compilation {
275     Stop,
276     Continue,
277 }
278
279 impl Compilation {
280     pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
281         match self {
282             Compilation::Stop => Compilation::Stop,
283             Compilation::Continue => next(),
284         }
285     }
286 }
287
288 // A trait for customising the compilation process. Offers a number of hooks for
289 // executing custom code or customising input.
290 pub trait CompilerCalls<'a> {
291     // Hook for a callback early in the process of handling arguments. This will
292     // be called straight after options have been parsed but before anything
293     // else (e.g., selecting input and output).
294     fn early_callback(&mut self,
295                       _: &getopts::Matches,
296                       _: &config::Options,
297                       _: &ast::CrateConfig,
298                       _: &errors::registry::Registry,
299                       _: ErrorOutputType)
300                       -> Compilation {
301         Compilation::Continue
302     }
303
304     // Hook for a callback late in the process of handling arguments. This will
305     // be called just before actual compilation starts (and before build_controller
306     // is called), after all arguments etc. have been completely handled.
307     fn late_callback(&mut self,
308                      _: &getopts::Matches,
309                      _: &Session,
310                      _: &Input,
311                      _: &Option<PathBuf>,
312                      _: &Option<PathBuf>)
313                      -> Compilation {
314         Compilation::Continue
315     }
316
317     // Called after we extract the input from the arguments. Gives the implementer
318     // an opportunity to change the inputs or to add some custom input handling.
319     // The default behaviour is to simply pass through the inputs.
320     fn some_input(&mut self,
321                   input: Input,
322                   input_path: Option<PathBuf>)
323                   -> (Input, Option<PathBuf>) {
324         (input, input_path)
325     }
326
327     // Called after we extract the input from the arguments if there is no valid
328     // input. Gives the implementer an opportunity to supply alternate input (by
329     // returning a Some value) or to add custom behaviour for this error such as
330     // emitting error messages. Returning None will cause compilation to stop
331     // at this point.
332     fn no_input(&mut self,
333                 _: &getopts::Matches,
334                 _: &config::Options,
335                 _: &ast::CrateConfig,
336                 _: &Option<PathBuf>,
337                 _: &Option<PathBuf>,
338                 _: &errors::registry::Registry)
339                 -> Option<(Input, Option<PathBuf>)> {
340         None
341     }
342
343     // Create a CompilController struct for controlling the behaviour of
344     // compilation.
345     fn build_controller(&mut self, &Session, &getopts::Matches) -> CompileController<'a>;
346 }
347
348 // CompilerCalls instance for a regular rustc build.
349 #[derive(Copy, Clone)]
350 pub struct RustcDefaultCalls;
351
352 fn handle_explain(code: &str,
353                   descriptions: &errors::registry::Registry,
354                   output: ErrorOutputType) {
355     let normalised = if code.starts_with("E") {
356         code.to_string()
357     } else {
358         format!("E{0:0>4}", code)
359     };
360     match descriptions.find_description(&normalised) {
361         Some(ref description) => {
362             // Slice off the leading newline and print.
363             print!("{}", &(&description[1..]).split("\n").map(|x| {
364                 format!("{}\n", if x.starts_with("```") {
365                     "```"
366                 } else {
367                     x
368                 })
369             }).collect::<String>());
370         }
371         None => {
372             early_error(output, &format!("no extended information for {}", code));
373         }
374     }
375 }
376
377 fn check_cfg(cfg: &ast::CrateConfig,
378              output: ErrorOutputType) {
379     let emitter: Box<Emitter> = match output {
380         config::ErrorOutputType::HumanReadable(color_config) => {
381             Box::new(errors::emitter::EmitterWriter::stderr(color_config, None))
382         }
383         config::ErrorOutputType::Json => Box::new(json::JsonEmitter::basic()),
384     };
385     let handler = errors::Handler::with_emitter(true, false, emitter);
386
387     let mut saw_invalid_predicate = false;
388     for item in cfg.iter() {
389         if item.is_meta_item_list() {
390             saw_invalid_predicate = true;
391             handler.emit(&MultiSpan::new(),
392                          &format!("invalid predicate in --cfg command line argument: `{}`",
393                                   item.name()),
394                             errors::Level::Fatal);
395         }
396     }
397
398     if saw_invalid_predicate {
399         panic!(errors::FatalError);
400     }
401 }
402
403 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
404     fn early_callback(&mut self,
405                       matches: &getopts::Matches,
406                       _: &config::Options,
407                       cfg: &ast::CrateConfig,
408                       descriptions: &errors::registry::Registry,
409                       output: ErrorOutputType)
410                       -> Compilation {
411         if let Some(ref code) = matches.opt_str("explain") {
412             handle_explain(code, descriptions, output);
413             return Compilation::Stop;
414         }
415
416         check_cfg(cfg, output);
417         Compilation::Continue
418     }
419
420     fn no_input(&mut self,
421                 matches: &getopts::Matches,
422                 sopts: &config::Options,
423                 cfg: &ast::CrateConfig,
424                 odir: &Option<PathBuf>,
425                 ofile: &Option<PathBuf>,
426                 descriptions: &errors::registry::Registry)
427                 -> Option<(Input, Option<PathBuf>)> {
428         match matches.free.len() {
429             0 => {
430                 if sopts.describe_lints {
431                     let mut ls = lint::LintStore::new();
432                     rustc_lint::register_builtins(&mut ls, None);
433                     describe_lints(&ls, false);
434                     return None;
435                 }
436                 let dep_graph = DepGraph::new(sopts.build_dep_graph());
437                 let cstore = Rc::new(CStore::new(&dep_graph));
438                 let mut sess = build_session(sopts.clone(),
439                     &dep_graph,
440                     None,
441                     descriptions.clone(),
442                     cstore.clone());
443                 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
444                 let mut cfg = config::build_configuration(&sess, cfg.clone());
445                 target_features::add_configuration(&mut cfg, &sess);
446                 sess.parse_sess.config = cfg;
447                 let should_stop =
448                     RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
449
450                 if should_stop == Compilation::Stop {
451                     return None;
452                 }
453                 early_error(sopts.error_format, "no input filename given");
454             }
455             1 => panic!("make_input should have provided valid inputs"),
456             _ => early_error(sopts.error_format, "multiple input filenames provided"),
457         }
458
459         None
460     }
461
462     fn late_callback(&mut self,
463                      matches: &getopts::Matches,
464                      sess: &Session,
465                      input: &Input,
466                      odir: &Option<PathBuf>,
467                      ofile: &Option<PathBuf>)
468                      -> Compilation {
469         RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
470             .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input))
471     }
472
473     fn build_controller(&mut self,
474                         sess: &Session,
475                         matches: &getopts::Matches)
476                         -> CompileController<'a> {
477         let mut control = CompileController::basic();
478
479         if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
480             if ppm.needs_ast_map(&opt_uii) {
481                 control.after_hir_lowering.stop = Compilation::Stop;
482
483                 control.after_parse.callback = box move |state| {
484                     state.krate = Some(pretty::fold_crate(state.krate.take().unwrap(), ppm));
485                 };
486                 control.after_hir_lowering.callback = box move |state| {
487                     pretty::print_after_hir_lowering(state.session,
488                                                      state.ast_map.unwrap(),
489                                                      state.analysis.unwrap(),
490                                                      state.resolutions.unwrap(),
491                                                      state.input,
492                                                      &state.expanded_crate.take().unwrap(),
493                                                      state.crate_name.unwrap(),
494                                                      ppm,
495                                                      state.arenas.unwrap(),
496                                                      opt_uii.clone(),
497                                                      state.out_file);
498                 };
499             } else {
500                 control.after_parse.stop = Compilation::Stop;
501
502                 control.after_parse.callback = box move |state| {
503                     let krate = pretty::fold_crate(state.krate.take().unwrap(), ppm);
504                     pretty::print_after_parsing(state.session,
505                                                 state.input,
506                                                 &krate,
507                                                 ppm,
508                                                 state.out_file);
509                 };
510             }
511
512             return control;
513         }
514
515         if sess.opts.debugging_opts.parse_only ||
516            sess.opts.debugging_opts.show_span.is_some() ||
517            sess.opts.debugging_opts.ast_json_noexpand {
518             control.after_parse.stop = Compilation::Stop;
519         }
520
521         if sess.opts.debugging_opts.no_analysis ||
522            sess.opts.debugging_opts.ast_json {
523             control.after_hir_lowering.stop = Compilation::Stop;
524         }
525
526         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe) {
527             control.after_llvm.stop = Compilation::Stop;
528         }
529
530         if save_analysis(sess) {
531             control.after_analysis.callback = box |state| {
532                 time(state.session.time_passes(), "save analysis", || {
533                     save::process_crate(state.tcx.unwrap(),
534                                         state.expanded_crate.unwrap(),
535                                         state.analysis.unwrap(),
536                                         state.crate_name.unwrap(),
537                                         state.out_dir,
538                                         save_analysis_format(state.session))
539                 });
540             };
541             control.after_analysis.run_callback_on_error = true;
542             control.make_glob_map = resolve::MakeGlobMap::Yes;
543         }
544
545         control
546     }
547 }
548
549 fn save_analysis(sess: &Session) -> bool {
550     sess.opts.debugging_opts.save_analysis ||
551     sess.opts.debugging_opts.save_analysis_csv ||
552     sess.opts.debugging_opts.save_analysis_api
553 }
554
555 fn save_analysis_format(sess: &Session) -> save::Format {
556     if sess.opts.debugging_opts.save_analysis {
557         save::Format::Json
558     } else if sess.opts.debugging_opts.save_analysis_csv {
559         save::Format::Csv
560     } else if sess.opts.debugging_opts.save_analysis_api {
561         save::Format::JsonApi
562     } else {
563         unreachable!();
564     }
565 }
566
567 impl RustcDefaultCalls {
568     pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation {
569         let r = matches.opt_strs("Z");
570         if r.contains(&("ls".to_string())) {
571             match input {
572                 &Input::File(ref ifile) => {
573                     let path = &(*ifile);
574                     let mut v = Vec::new();
575                     locator::list_file_metadata(&sess.target.target, path, &mut v).unwrap();
576                     println!("{}", String::from_utf8(v).unwrap());
577                 }
578                 &Input::Str { .. } => {
579                     early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
580                 }
581             }
582             return Compilation::Stop;
583         }
584
585         return Compilation::Continue;
586     }
587
588
589     fn print_crate_info(sess: &Session,
590                         input: Option<&Input>,
591                         odir: &Option<PathBuf>,
592                         ofile: &Option<PathBuf>)
593                         -> Compilation {
594         if sess.opts.prints.is_empty() {
595             return Compilation::Continue;
596         }
597
598         let attrs = match input {
599             None => None,
600             Some(input) => {
601                 let result = parse_crate_attrs(sess, input);
602                 match result {
603                     Ok(attrs) => Some(attrs),
604                     Err(mut parse_error) => {
605                         parse_error.emit();
606                         return Compilation::Stop;
607                     }
608                 }
609             }
610         };
611         for req in &sess.opts.prints {
612             match *req {
613                 PrintRequest::TargetList => {
614                     let mut targets = rustc_back::target::get_targets().collect::<Vec<String>>();
615                     targets.sort();
616                     println!("{}", targets.join("\n"));
617                 },
618                 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
619                 PrintRequest::FileNames |
620                 PrintRequest::CrateName => {
621                     let input = match input {
622                         Some(input) => input,
623                         None => early_error(ErrorOutputType::default(), "no input file provided"),
624                     };
625                     let attrs = attrs.as_ref().unwrap();
626                     let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
627                     let id = link::find_crate_name(Some(sess), attrs, input);
628                     if *req == PrintRequest::CrateName {
629                         println!("{}", id);
630                         continue;
631                     }
632                     let crate_types = driver::collect_crate_types(sess, attrs);
633                     for &style in &crate_types {
634                         let fname = link::filename_for_input(sess, style, &id, &t_outputs);
635                         println!("{}",
636                                  fname.file_name()
637                                       .unwrap()
638                                       .to_string_lossy());
639                     }
640                 }
641                 PrintRequest::Cfg => {
642                     let allow_unstable_cfg = UnstableFeatures::from_environment()
643                         .is_nightly_build();
644
645                     for cfg in &sess.parse_sess.config {
646                         if !allow_unstable_cfg && GatedCfg::gate(cfg).is_some() {
647                             continue;
648                         }
649
650                         if cfg.is_word() {
651                             println!("{}", cfg.name());
652                         } else if let Some(s) = cfg.value_str() {
653                             println!("{}=\"{}\"", cfg.name(), s);
654                         } else if cfg.is_meta_item_list() {
655                             // Right now there are not and should not be any
656                             // MetaItemKind::List items in the configuration returned by
657                             // `build_configuration`.
658                             panic!("Found an unexpected list in cfg attribute '{}'!", cfg.name())
659                         } else {
660                             // There also shouldn't be literals.
661                             panic!("Found an unexpected literal in cfg attribute '{}'!", cfg.name())
662                         }
663                     }
664                 }
665                 PrintRequest::TargetCPUs => {
666                     let tm = create_target_machine(sess);
667                     unsafe { llvm::LLVMRustPrintTargetCPUs(tm); }
668                 }
669                 PrintRequest::TargetFeatures => {
670                     let tm = create_target_machine(sess);
671                     unsafe { llvm::LLVMRustPrintTargetFeatures(tm); }
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             }
688         }
689         return Compilation::Stop;
690     }
691 }
692
693 /// Returns a version string such as "0.12.0-dev".
694 pub fn release_str() -> Option<&'static str> {
695     option_env!("CFG_RELEASE")
696 }
697
698 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
699 pub fn commit_hash_str() -> Option<&'static str> {
700     option_env!("CFG_VER_HASH")
701 }
702
703 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
704 pub fn commit_date_str() -> Option<&'static str> {
705     option_env!("CFG_VER_DATE")
706 }
707
708 /// Prints version information
709 pub fn version(binary: &str, matches: &getopts::Matches) {
710     let verbose = matches.opt_present("verbose");
711
712     println!("{} {}",
713              binary,
714              option_env!("CFG_VERSION").unwrap_or("unknown version"));
715     if verbose {
716         fn unw(x: Option<&str>) -> &str {
717             x.unwrap_or("unknown")
718         }
719         println!("binary: {}", binary);
720         println!("commit-hash: {}", unw(commit_hash_str()));
721         println!("commit-date: {}", unw(commit_date_str()));
722         println!("host: {}", config::host_triple());
723         println!("release: {}", unw(release_str()));
724         unsafe {
725             println!("LLVM version: {}.{}",
726                      llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor());
727         }
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, and deny all overrides)
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 complication 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.contains(&"passes=list".to_string()) {
1015         unsafe {
1016             ::llvm::LLVMRustPrintPasses();
1017         }
1018         return None;
1019     }
1020
1021     if matches.opt_present("version") {
1022         version("rustc", &matches);
1023         return None;
1024     }
1025
1026     Some(matches)
1027 }
1028
1029 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1030     match *input {
1031         Input::File(ref ifile) => {
1032             parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1033         }
1034         Input::Str { ref name, ref input } => {
1035             parse::parse_crate_attrs_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
1036         }
1037     }
1038 }
1039
1040 /// Run a procedure which will detect panics in the compiler and print nicer
1041 /// error messages rather than just failing the test.
1042 ///
1043 /// The diagnostic emitter yielded to the procedure should be used for reporting
1044 /// errors of the compiler.
1045 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
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     struct Sink(Arc<Mutex<Vec<u8>>>);
1050     impl Write for Sink {
1051         fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1052             Write::write(&mut *self.0.lock().unwrap(), data)
1053         }
1054         fn flush(&mut self) -> io::Result<()> {
1055             Ok(())
1056         }
1057     }
1058
1059     let data = Arc::new(Mutex::new(Vec::new()));
1060     let err = Sink(data.clone());
1061
1062     let mut cfg = thread::Builder::new().name("rustc".to_string());
1063
1064     // FIXME: Hacks on hacks. If the env is trying to override the stack size
1065     // then *don't* set it explicitly.
1066     if env::var_os("RUST_MIN_STACK").is_none() {
1067         cfg = cfg.stack_size(STACK_SIZE);
1068     }
1069
1070     let thread = cfg.spawn(move || {
1071          io::set_panic(Some(box err));
1072          f()
1073      });
1074
1075      if let Err(value) = thread.unwrap().join() {
1076         // Thread panicked without emitting a fatal diagnostic
1077         if !value.is::<errors::FatalError>() {
1078             let emitter =
1079                 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None));
1080             let handler = errors::Handler::with_emitter(true, false, emitter);
1081
1082             // a .span_bug or .bug call has already printed what
1083             // it wants to print.
1084             if !value.is::<errors::ExplicitBug>() {
1085                 handler.emit(&MultiSpan::new(),
1086                              "unexpected panic",
1087                              errors::Level::Bug);
1088             }
1089
1090             let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1091                       format!("we would appreciate a bug report: {}", BUG_REPORT_URL)];
1092             for note in &xs {
1093                 handler.emit(&MultiSpan::new(),
1094                              &note[..],
1095                              errors::Level::Note);
1096             }
1097             if match env::var_os("RUST_BACKTRACE") {
1098                 Some(val) => &val != "0",
1099                 None => false,
1100             } {
1101                 handler.emit(&MultiSpan::new(),
1102                              "run with `RUST_BACKTRACE=1` for a backtrace",
1103                              errors::Level::Note);
1104             }
1105
1106             writeln!(io::stderr(), "{}", str::from_utf8(&data.lock().unwrap()).unwrap()).unwrap();
1107         }
1108
1109         exit_on_err();
1110     }
1111 }
1112
1113 fn exit_on_err() -> ! {
1114     // Panic so the process returns a failure code, but don't pollute the
1115     // output with some unnecessary panic messages, we've already
1116     // printed everything that we needed to.
1117     io::set_panic(Some(box io::sink()));
1118     panic!();
1119 }
1120
1121 pub fn diagnostics_registry() -> errors::registry::Registry {
1122     use errors::registry::Registry;
1123
1124     let mut all_errors = Vec::new();
1125     all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1126     all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1127     all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
1128     all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1129     all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1130     all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
1131     all_errors.extend_from_slice(&rustc_const_eval::DIAGNOSTICS);
1132     all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1133
1134     Registry::new(&all_errors)
1135 }
1136
1137 pub fn main() {
1138     let result = run(|| run_compiler(&env::args().collect::<Vec<_>>(),
1139                                      &mut RustcDefaultCalls,
1140                                      None,
1141                                      None));
1142     process::exit(result as i32);
1143 }