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