]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/lib.rs
Rollup merge of #31295 - steveklabnik:gh31266, r=alexcrichton
[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
34 extern crate arena;
35 extern crate flate;
36 extern crate getopts;
37 extern crate graphviz;
38 extern crate libc;
39 extern crate rustc;
40 extern crate rustc_back;
41 extern crate rustc_borrowck;
42 extern crate rustc_passes;
43 extern crate rustc_front;
44 extern crate rustc_lint;
45 extern crate rustc_plugin;
46 extern crate rustc_privacy;
47 extern crate rustc_metadata;
48 extern crate rustc_mir;
49 extern crate rustc_resolve;
50 extern crate rustc_trans;
51 extern crate rustc_typeck;
52 extern crate serialize;
53 extern crate rustc_llvm as llvm;
54 #[macro_use]
55 extern crate log;
56 #[macro_use]
57 extern crate syntax;
58 extern crate syntax_ext;
59
60 use driver::CompileController;
61 use pretty::{PpMode, UserIdentifiedItem};
62
63 use rustc_resolve as resolve;
64 use rustc_trans::back::link;
65 use rustc_trans::save;
66 use rustc::session::{config, Session, build_session};
67 use rustc::session::config::{Input, PrintRequest, OutputType, ErrorOutputType};
68 use rustc::middle::cstore::CrateStore;
69 use rustc::lint::Lint;
70 use rustc::lint;
71 use rustc_metadata::loader;
72 use rustc_metadata::cstore::CStore;
73 use rustc::util::common::time;
74
75 use std::cmp::max;
76 use std::cmp::Ordering::Equal;
77 use std::default::Default;
78 use std::env;
79 use std::io::{self, Read, Write};
80 use std::iter::repeat;
81 use std::path::PathBuf;
82 use std::process;
83 use std::rc::Rc;
84 use std::str;
85 use std::sync::{Arc, Mutex};
86 use std::thread;
87
88 use rustc::session::early_error;
89
90 use syntax::ast;
91 use syntax::parse;
92 use syntax::errors;
93 use syntax::errors::emitter::Emitter;
94 use syntax::diagnostics;
95 use syntax::parse::token;
96
97 #[cfg(test)]
98 pub mod test;
99
100 pub mod driver;
101 pub mod pretty;
102 pub mod target_features;
103
104
105 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
106                                       md#bug-reports";
107
108 // Err(0) means compilation was stopped, but no errors were found.
109 // This would be better as a dedicated enum, but using try! is so convenient.
110 pub type CompileResult = Result<(), usize>;
111
112 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
113     if err_count == 0 {
114         Ok(())
115     } else {
116         Err(err_count)
117     }
118 }
119
120 #[inline]
121 fn abort_msg(err_count: usize) -> String {
122     match err_count {
123         0 => "aborting with no errors (maybe a bug?)".to_owned(),
124         1 => "aborting due to previous error".to_owned(),
125         e => format!("aborting due to {} previous errors", e),
126     }
127 }
128
129 pub fn abort_on_err<T>(result: Result<T, usize>, sess: &Session) -> T {
130     match result {
131         Err(err_count) => {
132             sess.fatal(&abort_msg(err_count));
133         }
134         Ok(x) => x,
135     }
136 }
137
138 pub fn run(args: Vec<String>) -> isize {
139     monitor(move || {
140         let (result, session) = run_compiler(&args, &mut RustcDefaultCalls);
141         if let Err(err_count) = result {
142             if err_count > 0 {
143                 match session {
144                     Some(sess) => sess.fatal(&abort_msg(err_count)),
145                     None => {
146                         let mut emitter =
147                             errors::emitter::BasicEmitter::stderr(errors::ColorConfig::Auto);
148                         emitter.emit(None, &abort_msg(err_count), None, errors::Level::Fatal);
149                         panic!(errors::FatalError);
150                     }
151                 }
152             }
153         }
154     });
155     0
156 }
157
158 // Parse args and run the compiler. This is the primary entry point for rustc.
159 // See comments on CompilerCalls below for details about the callbacks argument.
160 pub fn run_compiler<'a>(args: &[String],
161                         callbacks: &mut CompilerCalls<'a>)
162                         -> (CompileResult, Option<Session>) {
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.to_vec()) {
171         Some(matches) => matches,
172         None => return (Ok(()), None),
173     };
174
175     let sopts = config::build_session_options(&matches);
176
177     let descriptions = diagnostics_registry();
178
179     do_or_return!(callbacks.early_callback(&matches, &descriptions, sopts.error_format), None);
180
181     let (odir, ofile) = make_output(&matches);
182     let (input, input_file_path) = match make_input(&matches.free) {
183         Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
184         None => match callbacks.no_input(&matches, &sopts, &odir, &ofile, &descriptions) {
185             Some((input, input_file_path)) => (input, input_file_path),
186             None => return (Ok(()), None),
187         },
188     };
189
190     let cstore = Rc::new(CStore::new(token::get_ident_interner()));
191     let sess = build_session(sopts, input_file_path, descriptions, cstore.clone());
192     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
193     let mut cfg = config::build_configuration(&sess);
194     target_features::add_configuration(&mut cfg, &sess);
195
196     do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile), Some(sess));
197
198     // It is somewhat unfortunate that this is hardwired in - this is forced by
199     // the fact that pretty_print_input requires the session by value.
200     let pretty = callbacks.parse_pretty(&sess, &matches);
201     match pretty {
202         Some((ppm, opt_uii)) => {
203             pretty::pretty_print_input(sess, &cstore, cfg, &input, ppm, opt_uii, ofile);
204             return (Ok(()), None);
205         }
206         None => {
207             // continue
208         }
209     }
210
211     let plugins = sess.opts.debugging_opts.extra_plugins.clone();
212     let control = callbacks.build_controller(&sess);
213     (driver::compile_input(&sess, &cstore, cfg, &input, &odir, &ofile,
214                            Some(plugins), control),
215      Some(sess))
216 }
217
218 // Extract output directory and file from matches.
219 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
220     let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
221     let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
222     (odir, ofile)
223 }
224
225 // Extract input (string or file and optional path) from matches.
226 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
227     if free_matches.len() == 1 {
228         let ifile = &free_matches[0][..];
229         if ifile == "-" {
230             let mut src = String::new();
231             io::stdin().read_to_string(&mut src).unwrap();
232             Some((Input::Str(src), None))
233         } else {
234             Some((Input::File(PathBuf::from(ifile)),
235                   Some(PathBuf::from(ifile))))
236         }
237     } else {
238         None
239     }
240 }
241
242 // Whether to stop or continue compilation.
243 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
244 pub enum Compilation {
245     Stop,
246     Continue,
247 }
248
249 impl Compilation {
250     pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
251         match self {
252             Compilation::Stop => Compilation::Stop,
253             Compilation::Continue => next(),
254         }
255     }
256 }
257
258 // A trait for customising the compilation process. Offers a number of hooks for
259 // executing custom code or customising input.
260 pub trait CompilerCalls<'a> {
261     // Hook for a callback early in the process of handling arguments. This will
262     // be called straight after options have been parsed but before anything
263     // else (e.g., selecting input and output).
264     fn early_callback(&mut self,
265                       _: &getopts::Matches,
266                       _: &diagnostics::registry::Registry,
267                       _: ErrorOutputType)
268                       -> Compilation {
269         Compilation::Continue
270     }
271
272     // Hook for a callback late in the process of handling arguments. This will
273     // be called just before actual compilation starts (and before build_controller
274     // is called), after all arguments etc. have been completely handled.
275     fn late_callback(&mut self,
276                      _: &getopts::Matches,
277                      _: &Session,
278                      _: &Input,
279                      _: &Option<PathBuf>,
280                      _: &Option<PathBuf>)
281                      -> Compilation {
282         Compilation::Continue
283     }
284
285     // Called after we extract the input from the arguments. Gives the implementer
286     // an opportunity to change the inputs or to add some custom input handling.
287     // The default behaviour is to simply pass through the inputs.
288     fn some_input(&mut self,
289                   input: Input,
290                   input_path: Option<PathBuf>)
291                   -> (Input, Option<PathBuf>) {
292         (input, input_path)
293     }
294
295     // Called after we extract the input from the arguments if there is no valid
296     // input. Gives the implementer an opportunity to supply alternate input (by
297     // returning a Some value) or to add custom behaviour for this error such as
298     // emitting error messages. Returning None will cause compilation to stop
299     // at this point.
300     fn no_input(&mut self,
301                 _: &getopts::Matches,
302                 _: &config::Options,
303                 _: &Option<PathBuf>,
304                 _: &Option<PathBuf>,
305                 _: &diagnostics::registry::Registry)
306                 -> Option<(Input, Option<PathBuf>)> {
307         None
308     }
309
310     // Parse pretty printing information from the arguments. The implementer can
311     // choose to ignore this (the default will return None) which will skip pretty
312     // printing. If you do want to pretty print, it is recommended to use the
313     // implementation of this method from RustcDefaultCalls.
314     // FIXME, this is a terrible bit of API. Parsing of pretty printing stuff
315     // should be done as part of the framework and the implementor should customise
316     // handling of it. However, that is not possible atm because pretty printing
317     // essentially goes off and takes another path through the compiler which
318     // means the session is either moved or not depending on what parse_pretty
319     // returns (we could fix this by cloning, but it's another hack). The proper
320     // solution is to handle pretty printing as if it were a compiler extension,
321     // extending CompileController to make this work (see for example the treatment
322     // of save-analysis in RustcDefaultCalls::build_controller).
323     fn parse_pretty(&mut self,
324                     _sess: &Session,
325                     _matches: &getopts::Matches)
326                     -> Option<(PpMode, Option<UserIdentifiedItem>)> {
327         None
328     }
329
330     // Create a CompilController struct for controlling the behaviour of
331     // compilation.
332     fn build_controller(&mut self, &Session) -> CompileController<'a>;
333 }
334
335 // CompilerCalls instance for a regular rustc build.
336 #[derive(Copy, Clone)]
337 pub struct RustcDefaultCalls;
338
339 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
340     fn early_callback(&mut self,
341                       matches: &getopts::Matches,
342                       descriptions: &diagnostics::registry::Registry,
343                       output: ErrorOutputType)
344                       -> Compilation {
345         match matches.opt_str("explain") {
346             Some(ref code) => {
347                 let normalised = if !code.starts_with("E") {
348                     format!("E{0:0>4}", code)
349                 } else {
350                     code.to_string()
351                 };
352                 match descriptions.find_description(&normalised) {
353                     Some(ref description) => {
354                         // Slice off the leading newline and print.
355                         print!("{}", &description[1..]);
356                     }
357                     None => {
358                         early_error(output, &format!("no extended information for {}", code));
359                     }
360                 }
361                 return Compilation::Stop;
362             }
363             None => (),
364         }
365
366         return Compilation::Continue;
367     }
368
369     fn no_input(&mut self,
370                 matches: &getopts::Matches,
371                 sopts: &config::Options,
372                 odir: &Option<PathBuf>,
373                 ofile: &Option<PathBuf>,
374                 descriptions: &diagnostics::registry::Registry)
375                 -> Option<(Input, Option<PathBuf>)> {
376         match matches.free.len() {
377             0 => {
378                 if sopts.describe_lints {
379                     let mut ls = lint::LintStore::new();
380                     rustc_lint::register_builtins(&mut ls, None);
381                     describe_lints(&ls, false);
382                     return None;
383                 }
384                 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
385                 let sess = build_session(sopts.clone(), None, descriptions.clone(),
386                                          cstore.clone());
387                 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
388                 let should_stop = RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
389                 if should_stop == Compilation::Stop {
390                     return None;
391                 }
392                 early_error(sopts.error_format, "no input filename given");
393             }
394             1 => panic!("make_input should have provided valid inputs"),
395             _ => early_error(sopts.error_format, "multiple input filenames provided"),
396         }
397
398         None
399     }
400
401     fn parse_pretty(&mut self,
402                     sess: &Session,
403                     matches: &getopts::Matches)
404                     -> Option<(PpMode, Option<UserIdentifiedItem>)> {
405         let pretty = if sess.opts.debugging_opts.unstable_options {
406             matches.opt_default("pretty", "normal").map(|a| {
407                 // stable pretty-print variants only
408                 pretty::parse_pretty(sess, &a, false)
409             })
410         } else {
411             None
412         };
413         if pretty.is_none() && sess.unstable_options() {
414             matches.opt_str("unpretty").map(|a| {
415                 // extended with unstable pretty-print variants
416                 pretty::parse_pretty(sess, &a, true)
417             })
418         } else {
419             pretty
420         }
421     }
422
423     fn late_callback(&mut self,
424                      matches: &getopts::Matches,
425                      sess: &Session,
426                      input: &Input,
427                      odir: &Option<PathBuf>,
428                      ofile: &Option<PathBuf>)
429                      -> Compilation {
430         RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
431             .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input))
432     }
433
434     fn build_controller(&mut self, sess: &Session) -> CompileController<'a> {
435         let mut control = CompileController::basic();
436
437         if sess.opts.parse_only || sess.opts.debugging_opts.show_span.is_some() ||
438            sess.opts.debugging_opts.ast_json_noexpand {
439             control.after_parse.stop = Compilation::Stop;
440         }
441
442         if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
443             control.after_write_deps.stop = Compilation::Stop;
444         }
445
446         if sess.opts.no_trans {
447             control.after_analysis.stop = Compilation::Stop;
448         }
449
450         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe) {
451             control.after_llvm.stop = Compilation::Stop;
452         }
453
454         if sess.opts.debugging_opts.save_analysis {
455             control.after_analysis.callback = box |state| {
456                 time(state.session.time_passes(), "save analysis", || {
457                     save::process_crate(state.tcx.unwrap(),
458                                         state.lcx.unwrap(),
459                                         state.krate.unwrap(),
460                                         state.analysis.unwrap(),
461                                         state.crate_name.unwrap(),
462                                         state.out_dir)
463                 });
464             };
465             control.make_glob_map = resolve::MakeGlobMap::Yes;
466         }
467
468         control
469     }
470 }
471
472 impl RustcDefaultCalls {
473     pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation {
474         let r = matches.opt_strs("Z");
475         if r.contains(&("ls".to_string())) {
476             match input {
477                 &Input::File(ref ifile) => {
478                     let path = &(*ifile);
479                     let mut v = Vec::new();
480                     loader::list_file_metadata(&sess.target.target, path, &mut v)
481                         .unwrap();
482                     println!("{}", String::from_utf8(v).unwrap());
483                 }
484                 &Input::Str(_) => {
485                     early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
486                 }
487             }
488             return Compilation::Stop;
489         }
490
491         return Compilation::Continue;
492     }
493
494
495     fn print_crate_info(sess: &Session,
496                         input: Option<&Input>,
497                         odir: &Option<PathBuf>,
498                         ofile: &Option<PathBuf>)
499                         -> Compilation {
500         if sess.opts.prints.is_empty() {
501             return Compilation::Continue;
502         }
503
504         let attrs = input.map(|input| parse_crate_attrs(sess, input));
505         for req in &sess.opts.prints {
506             match *req {
507                 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
508                 PrintRequest::FileNames |
509                 PrintRequest::CrateName => {
510                     let input = match input {
511                         Some(input) => input,
512                         None => early_error(ErrorOutputType::default(), "no input file provided"),
513                     };
514                     let attrs = attrs.as_ref().unwrap();
515                     let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
516                     let id = link::find_crate_name(Some(sess), attrs, input);
517                     if *req == PrintRequest::CrateName {
518                         println!("{}", id);
519                         continue;
520                     }
521                     let crate_types = driver::collect_crate_types(sess, attrs);
522                     let metadata = driver::collect_crate_metadata(sess, attrs);
523                     *sess.crate_metadata.borrow_mut() = metadata;
524                     for &style in &crate_types {
525                         let fname = link::filename_for_input(sess, style, &id, &t_outputs);
526                         println!("{}",
527                                  fname.file_name()
528                                       .unwrap()
529                                       .to_string_lossy());
530                     }
531                 }
532             }
533         }
534         return Compilation::Stop;
535     }
536 }
537
538 /// Returns a version string such as "0.12.0-dev".
539 pub fn release_str() -> Option<&'static str> {
540     option_env!("CFG_RELEASE")
541 }
542
543 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
544 pub fn commit_hash_str() -> Option<&'static str> {
545     option_env!("CFG_VER_HASH")
546 }
547
548 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
549 pub fn commit_date_str() -> Option<&'static str> {
550     option_env!("CFG_VER_DATE")
551 }
552
553 /// Prints version information
554 pub fn version(binary: &str, matches: &getopts::Matches) {
555     let verbose = matches.opt_present("verbose");
556
557     println!("{} {}",
558              binary,
559              option_env!("CFG_VERSION").unwrap_or("unknown version"));
560     if verbose {
561         fn unw(x: Option<&str>) -> &str {
562             x.unwrap_or("unknown")
563         }
564         println!("binary: {}", binary);
565         println!("commit-hash: {}", unw(commit_hash_str()));
566         println!("commit-date: {}", unw(commit_date_str()));
567         println!("host: {}", config::host_triple());
568         println!("release: {}", unw(release_str()));
569     }
570 }
571
572 fn usage(verbose: bool, include_unstable_options: bool) {
573     let groups = if verbose {
574         config::rustc_optgroups()
575     } else {
576         config::rustc_short_optgroups()
577     };
578     let groups: Vec<_> = groups.into_iter()
579                                .filter(|x| include_unstable_options || x.is_stable())
580                                .map(|x| x.opt_group)
581                                .collect();
582     let message = format!("Usage: rustc [OPTIONS] INPUT");
583     let extra_help = if verbose {
584         ""
585     } else {
586         "\n    --help -v           Print the full set of options rustc accepts"
587     };
588     println!("{}\nAdditional help:
589     -C help             Print codegen options
590     -W help             \
591               Print 'lint' options and default settings
592     -Z help             Print internal \
593               options for debugging rustc{}\n",
594              getopts::usage(&message, &groups),
595              extra_help);
596 }
597
598 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
599     println!("
600 Available lint options:
601     -W <foo>           Warn about <foo>
602     -A <foo>           \
603               Allow <foo>
604     -D <foo>           Deny <foo>
605     -F <foo>           Forbid <foo> \
606               (deny, and deny all overrides)
607
608 ");
609
610     fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
611         let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
612         lints.sort_by(|x: &&Lint, y: &&Lint| {
613             match x.default_level.cmp(&y.default_level) {
614                 // The sort doesn't case-fold but it's doubtful we care.
615                 Equal => x.name.cmp(y.name),
616                 r => r,
617             }
618         });
619         lints
620     }
621
622     fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
623                         -> Vec<(&'static str, Vec<lint::LintId>)> {
624         let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
625         lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
626                        &(y, _): &(&'static str, Vec<lint::LintId>)| {
627             x.cmp(y)
628         });
629         lints
630     }
631
632     let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
633                                                    .iter()
634                                                    .cloned()
635                                                    .partition(|&(_, p)| p);
636     let plugin = sort_lints(plugin);
637     let builtin = sort_lints(builtin);
638
639     let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
640                                                                  .iter()
641                                                                  .cloned()
642                                                                  .partition(|&(_, _, p)| p);
643     let plugin_groups = sort_lint_groups(plugin_groups);
644     let builtin_groups = sort_lint_groups(builtin_groups);
645
646     let max_name_len = plugin.iter()
647                              .chain(&builtin)
648                              .map(|&s| s.name.chars().count())
649                              .max()
650                              .unwrap_or(0);
651     let padded = |x: &str| {
652         let mut s = repeat(" ")
653                         .take(max_name_len - x.chars().count())
654                         .collect::<String>();
655         s.push_str(x);
656         s
657     };
658
659     println!("Lint checks provided by rustc:\n");
660     println!("    {}  {:7.7}  {}", padded("name"), "default", "meaning");
661     println!("    {}  {:7.7}  {}", padded("----"), "-------", "-------");
662
663     let print_lints = |lints: Vec<&Lint>| {
664         for lint in lints {
665             let name = lint.name_lower().replace("_", "-");
666             println!("    {}  {:7.7}  {}",
667                      padded(&name[..]),
668                      lint.default_level.as_str(),
669                      lint.desc);
670         }
671         println!("\n");
672     };
673
674     print_lints(builtin);
675
676
677
678     let max_name_len = max("warnings".len(),
679                            plugin_groups.iter()
680                                         .chain(&builtin_groups)
681                                         .map(|&(s, _)| s.chars().count())
682                                         .max()
683                                         .unwrap_or(0));
684
685     let padded = |x: &str| {
686         let mut s = repeat(" ")
687                         .take(max_name_len - x.chars().count())
688                         .collect::<String>();
689         s.push_str(x);
690         s
691     };
692
693     println!("Lint groups provided by rustc:\n");
694     println!("    {}  {}", padded("name"), "sub-lints");
695     println!("    {}  {}", padded("----"), "---------");
696     println!("    {}  {}", padded("warnings"), "all built-in lints");
697
698     let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
699         for (name, to) in lints {
700             let name = name.to_lowercase().replace("_", "-");
701             let desc = to.into_iter()
702                          .map(|x| x.as_str().replace("_", "-"))
703                          .collect::<Vec<String>>()
704                          .join(", ");
705             println!("    {}  {}", padded(&name[..]), desc);
706         }
707         println!("\n");
708     };
709
710     print_lint_groups(builtin_groups);
711
712     match (loaded_plugins, plugin.len(), plugin_groups.len()) {
713         (false, 0, _) | (false, _, 0) => {
714             println!("Compiler plugins can provide additional lints and lint groups. To see a \
715                       listing of these, re-run `rustc -W help` with a crate filename.");
716         }
717         (false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
718         (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
719         (true, l, g) => {
720             if l > 0 {
721                 println!("Lint checks provided by plugins loaded by this crate:\n");
722                 print_lints(plugin);
723             }
724             if g > 0 {
725                 println!("Lint groups provided by plugins loaded by this crate:\n");
726                 print_lint_groups(plugin_groups);
727             }
728         }
729     }
730 }
731
732 fn describe_debug_flags() {
733     println!("\nAvailable debug options:\n");
734     print_flag_list("-Z", config::DB_OPTIONS);
735 }
736
737 fn describe_codegen_flags() {
738     println!("\nAvailable codegen options:\n");
739     print_flag_list("-C", config::CG_OPTIONS);
740 }
741
742 fn print_flag_list<T>(cmdline_opt: &str,
743                       flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
744     let max_len = flag_list.iter()
745                            .map(|&(name, _, opt_type_desc, _)| {
746                                let extra_len = match opt_type_desc {
747                                    Some(..) => 4,
748                                    None => 0,
749                                };
750                                name.chars().count() + extra_len
751                            })
752                            .max()
753                            .unwrap_or(0);
754
755     for &(name, _, opt_type_desc, desc) in flag_list {
756         let (width, extra) = match opt_type_desc {
757             Some(..) => (max_len - 4, "=val"),
758             None => (max_len, ""),
759         };
760         println!("    {} {:>width$}{} -- {}",
761                  cmdline_opt,
762                  name.replace("_", "-"),
763                  extra,
764                  desc,
765                  width = width);
766     }
767 }
768
769 /// Process command line options. Emits messages as appropriate. If compilation
770 /// should continue, returns a getopts::Matches object parsed from args, otherwise
771 /// returns None.
772 pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
773     // Throw away the first argument, the name of the binary
774     let _binary = args.remove(0);
775
776     if args.is_empty() {
777         // user did not write `-v` nor `-Z unstable-options`, so do not
778         // include that extra information.
779         usage(false, false);
780         return None;
781     }
782
783     fn allows_unstable_options(matches: &getopts::Matches) -> bool {
784         let r = matches.opt_strs("Z");
785         r.iter().any(|x| *x == "unstable-options")
786     }
787
788     fn parse_all_options(args: &Vec<String>) -> getopts::Matches {
789         let all_groups: Vec<getopts::OptGroup> = config::rustc_optgroups()
790                                                      .into_iter()
791                                                      .map(|x| x.opt_group)
792                                                      .collect();
793         match getopts::getopts(&args[..], &all_groups) {
794             Ok(m) => {
795                 if !allows_unstable_options(&m) {
796                     // If -Z unstable-options was not specified, verify that
797                     // no unstable options were present.
798                     for opt in config::rustc_optgroups().into_iter().filter(|x| !x.is_stable()) {
799                         let opt_name = if !opt.opt_group.long_name.is_empty() {
800                             &opt.opt_group.long_name
801                         } else {
802                             &opt.opt_group.short_name
803                         };
804                         if m.opt_present(opt_name) {
805                             early_error(ErrorOutputType::default(),
806                                         &format!("use of unstable option '{}' requires -Z \
807                                                   unstable-options",
808                                                  opt_name));
809                         }
810                     }
811                 }
812                 m
813             }
814             Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
815         }
816     }
817
818     // As a speed optimization, first try to parse the command-line using just
819     // the stable options.
820     let matches = match getopts::getopts(&args[..], &config::optgroups()) {
821         Ok(ref m) if allows_unstable_options(m) => {
822             // If -Z unstable-options was specified, redo parsing with the
823             // unstable options to ensure that unstable options are defined
824             // in the returned getopts::Matches.
825             parse_all_options(&args)
826         }
827         Ok(m) => m,
828         Err(_) => {
829             // redo option parsing, including unstable options this time,
830             // in anticipation that the mishandled option was one of the
831             // unstable ones.
832             parse_all_options(&args)
833         }
834     };
835
836     if matches.opt_present("h") || matches.opt_present("help") {
837         usage(matches.opt_present("verbose"),
838               allows_unstable_options(&matches));
839         return None;
840     }
841
842     // Don't handle -W help here, because we might first load plugins.
843
844     let r = matches.opt_strs("Z");
845     if r.iter().any(|x| *x == "help") {
846         describe_debug_flags();
847         return None;
848     }
849
850     let cg_flags = matches.opt_strs("C");
851     if cg_flags.iter().any(|x| *x == "help") {
852         describe_codegen_flags();
853         return None;
854     }
855
856     if cg_flags.contains(&"passes=list".to_string()) {
857         unsafe {
858             ::llvm::LLVMRustPrintPasses();
859         }
860         return None;
861     }
862
863     if matches.opt_present("version") {
864         version("rustc", &matches);
865         return None;
866     }
867
868     Some(matches)
869 }
870
871 fn parse_crate_attrs(sess: &Session, input: &Input) -> Vec<ast::Attribute> {
872     let result = match *input {
873         Input::File(ref ifile) => {
874             parse::parse_crate_attrs_from_file(ifile, Vec::new(), &sess.parse_sess)
875         }
876         Input::Str(ref src) => {
877             parse::parse_crate_attrs_from_source_str(driver::anon_src().to_string(),
878                                                      src.to_string(),
879                                                      Vec::new(),
880                                                      &sess.parse_sess)
881         }
882     };
883     result.into_iter().collect()
884 }
885
886 /// Run a procedure which will detect panics in the compiler and print nicer
887 /// error messages rather than just failing the test.
888 ///
889 /// The diagnostic emitter yielded to the procedure should be used for reporting
890 /// errors of the compiler.
891 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
892     const STACK_SIZE: usize = 8 * 1024 * 1024; // 8MB
893
894     struct Sink(Arc<Mutex<Vec<u8>>>);
895     impl Write for Sink {
896         fn write(&mut self, data: &[u8]) -> io::Result<usize> {
897             Write::write(&mut *self.0.lock().unwrap(), data)
898         }
899         fn flush(&mut self) -> io::Result<()> {
900             Ok(())
901         }
902     }
903
904     let data = Arc::new(Mutex::new(Vec::new()));
905     let err = Sink(data.clone());
906
907     let mut cfg = thread::Builder::new().name("rustc".to_string());
908
909     // FIXME: Hacks on hacks. If the env is trying to override the stack size
910     // then *don't* set it explicitly.
911     if env::var_os("RUST_MIN_STACK").is_none() {
912         cfg = cfg.stack_size(STACK_SIZE);
913     }
914
915     match cfg.spawn(move || {
916                  io::set_panic(box err);
917                  f()
918              })
919              .unwrap()
920              .join() {
921         Ok(()) => {
922             // fallthrough
923         }
924         Err(value) => {
925             // Thread panicked without emitting a fatal diagnostic
926             if !value.is::<errors::FatalError>() {
927                 let mut emitter = errors::emitter::BasicEmitter::stderr(errors::ColorConfig::Auto);
928
929                 // a .span_bug or .bug call has already printed what
930                 // it wants to print.
931                 if !value.is::<errors::ExplicitBug>() {
932                     emitter.emit(None, "unexpected panic", None, errors::Level::Bug);
933                 }
934
935                 let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
936                           format!("we would appreciate a bug report: {}", BUG_REPORT_URL)];
937                 for note in &xs {
938                     emitter.emit(None, &note[..], None, errors::Level::Note)
939                 }
940                 if let None = env::var_os("RUST_BACKTRACE") {
941                     emitter.emit(None,
942                                  "run with `RUST_BACKTRACE=1` for a backtrace",
943                                  None,
944                                  errors::Level::Note);
945                 }
946
947                 println!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
948             }
949
950             // Panic so the process returns a failure code, but don't pollute the
951             // output with some unnecessary panic messages, we've already
952             // printed everything that we needed to.
953             io::set_panic(box io::sink());
954             panic!();
955         }
956     }
957 }
958
959 pub fn diagnostics_registry() -> diagnostics::registry::Registry {
960     use syntax::diagnostics::registry::Registry;
961
962     let mut all_errors = Vec::new();
963     all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
964     all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
965     all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
966     all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
967     all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
968     all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
969
970     Registry::new(&*all_errors)
971 }
972
973 pub fn main() {
974     let result = run(env::args().collect());
975     process::exit(result as i32);
976 }