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