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