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