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