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