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