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