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