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