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