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