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