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