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