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