]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/lib.rs
Rollup merge of #41249 - GuillaumeGomez:rustdoc-render, r=steveklabnik,frewsxcv
[rust.git] / src / librustc_driver / lib.rs
1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! The Rust compiler.
12 //!
13 //! # Note
14 //!
15 //! This API is completely unstable and subject to change.
16
17 #![crate_name = "rustc_driver"]
18 #![unstable(feature = "rustc_private", issue = "27812")]
19 #![crate_type = "dylib"]
20 #![crate_type = "rlib"]
21 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
22       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
23       html_root_url = "https://doc.rust-lang.org/nightly/")]
24 #![deny(warnings)]
25
26 #![feature(box_syntax)]
27 #![feature(loop_break_value)]
28 #![feature(libc)]
29 #![feature(quote)]
30 #![feature(rustc_diagnostic_macros)]
31 #![feature(rustc_private)]
32 #![feature(set_stdio)]
33 #![feature(staged_api)]
34
35 extern crate arena;
36 extern crate getopts;
37 extern crate graphviz;
38 extern crate env_logger;
39 extern crate libc;
40 extern crate rustc;
41 extern crate rustc_back;
42 extern crate rustc_borrowck;
43 extern crate rustc_const_eval;
44 extern crate rustc_data_structures;
45 extern crate rustc_errors as errors;
46 extern crate rustc_passes;
47 extern crate rustc_lint;
48 extern crate rustc_plugin;
49 extern crate rustc_privacy;
50 extern crate rustc_incremental;
51 extern crate rustc_metadata;
52 extern crate rustc_mir;
53 extern crate rustc_resolve;
54 extern crate rustc_save_analysis;
55 extern crate rustc_trans;
56 extern crate rustc_typeck;
57 extern crate serialize;
58 extern crate rustc_llvm as llvm;
59 #[macro_use]
60 extern crate log;
61 extern crate syntax;
62 extern crate syntax_ext;
63 extern crate syntax_pos;
64
65 use driver::CompileController;
66 use pretty::{PpMode, UserIdentifiedItem};
67
68 use rustc_resolve as resolve;
69 use rustc_save_analysis as save;
70 use rustc_save_analysis::DumpHandler;
71 use rustc_trans::back::link;
72 use rustc_trans::back::write::{create_target_machine, RELOC_MODEL_ARGS, CODE_GEN_MODEL_ARGS};
73 use rustc::dep_graph::DepGraph;
74 use rustc::session::{self, config, Session, build_session, CompileResult};
75 use rustc::session::config::{Input, PrintRequest, OutputType, ErrorOutputType};
76 use rustc::session::config::nightly_options;
77 use rustc::session::{early_error, early_warn};
78 use rustc::lint::Lint;
79 use rustc::lint;
80 use rustc_metadata::locator;
81 use rustc_metadata::cstore::CStore;
82 use rustc::util::common::time;
83
84 use serialize::json::ToJson;
85
86 use std::any::Any;
87 use std::cmp::max;
88 use std::cmp::Ordering::Equal;
89 use std::default::Default;
90 use std::env;
91 use std::io::{self, Read, Write};
92 use std::iter::repeat;
93 use std::path::PathBuf;
94 use std::process;
95 use std::rc::Rc;
96 use std::str;
97 use std::sync::{Arc, Mutex};
98 use std::thread;
99
100 use syntax::ast;
101 use syntax::codemap::{CodeMap, FileLoader, RealFileLoader};
102 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
103 use syntax::parse::{self, PResult};
104 use syntax_pos::{DUMMY_SP, MultiSpan};
105
106 #[cfg(test)]
107 pub mod test;
108
109 pub mod driver;
110 pub mod pretty;
111 pub mod target_features;
112 mod derive_registrar;
113
114 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
115                                       md#bug-reports";
116
117 #[inline]
118 fn abort_msg(err_count: usize) -> String {
119     match err_count {
120         0 => "aborting with no errors (maybe a bug?)".to_owned(),
121         1 => "aborting due to previous error".to_owned(),
122         e => format!("aborting due to {} previous errors", e),
123     }
124 }
125
126 pub fn abort_on_err<T>(result: Result<T, usize>, sess: &Session) -> T {
127     match result {
128         Err(err_count) => {
129             sess.fatal(&abort_msg(err_count));
130         }
131         Ok(x) => x,
132     }
133 }
134
135 pub fn run<F>(run_compiler: F) -> isize
136     where F: FnOnce() -> (CompileResult, Option<Session>) + Send + 'static
137 {
138     monitor(move || {
139         let (result, session) = run_compiler();
140         if let Err(err_count) = result {
141             if err_count > 0 {
142                 match session {
143                     Some(sess) => sess.fatal(&abort_msg(err_count)),
144                     None => {
145                         let emitter =
146                             errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None);
147                         let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
148                         handler.emit(&MultiSpan::new(),
149                                      &abort_msg(err_count),
150                                      errors::Level::Fatal);
151                         exit_on_err();
152                     }
153                 }
154             }
155         }
156     });
157     0
158 }
159
160 // Parse args and run the compiler. This is the primary entry point for rustc.
161 // See comments on CompilerCalls below for details about the callbacks argument.
162 // The FileLoader provides a way to load files from sources other than the file system.
163 pub fn run_compiler<'a>(args: &[String],
164                         callbacks: &mut CompilerCalls<'a>,
165                         file_loader: Option<Box<FileLoader + 'static>>,
166                         emitter_dest: Option<Box<Write + Send>>)
167                         -> (CompileResult, Option<Session>)
168 {
169     macro_rules! do_or_return {($expr: expr, $sess: expr) => {
170         match $expr {
171             Compilation::Stop => return (Ok(()), $sess),
172             Compilation::Continue => {}
173         }
174     }}
175
176     let matches = match handle_options(args) {
177         Some(matches) => matches,
178         None => return (Ok(()), None),
179     };
180
181     let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
182
183     if sopts.debugging_opts.debug_llvm {
184         unsafe { llvm::LLVMRustSetDebug(1); }
185     }
186
187     let descriptions = diagnostics_registry();
188
189     do_or_return!(callbacks.early_callback(&matches,
190                                            &sopts,
191                                            &cfg,
192                                            &descriptions,
193                                            sopts.error_format),
194                                            None);
195
196     let (odir, ofile) = make_output(&matches);
197     let (input, input_file_path) = match make_input(&matches.free) {
198         Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
199         None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) {
200             Some((input, input_file_path)) => (input, input_file_path),
201             None => return (Ok(()), None),
202         },
203     };
204
205     let dep_graph = DepGraph::new(sopts.build_dep_graph());
206     let cstore = Rc::new(CStore::new(&dep_graph));
207
208     let loader = file_loader.unwrap_or(box RealFileLoader);
209     let codemap = Rc::new(CodeMap::with_file_loader(loader));
210     let mut sess = session::build_session_with_codemap(
211         sopts, &dep_graph, input_file_path, descriptions, cstore.clone(), codemap, emitter_dest,
212     );
213     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
214
215     let mut cfg = config::build_configuration(&sess, cfg);
216     target_features::add_configuration(&mut cfg, &sess);
217     sess.parse_sess.config = cfg;
218
219     do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile), Some(sess));
220
221     let plugins = sess.opts.debugging_opts.extra_plugins.clone();
222     let control = callbacks.build_controller(&sess, &matches);
223     (driver::compile_input(&sess, &cstore, &input, &odir, &ofile, Some(plugins), &control),
224      Some(sess))
225 }
226
227 // Extract output directory and file from matches.
228 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
229     let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
230     let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
231     (odir, ofile)
232 }
233
234 // Extract input (string or file and optional path) from matches.
235 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
236     if free_matches.len() == 1 {
237         let ifile = &free_matches[0];
238         if ifile == "-" {
239             let mut src = String::new();
240             io::stdin().read_to_string(&mut src).unwrap();
241             Some((Input::Str { name: driver::anon_src(), input: src },
242                   None))
243         } else {
244             Some((Input::File(PathBuf::from(ifile)),
245                   Some(PathBuf::from(ifile))))
246         }
247     } else {
248         None
249     }
250 }
251
252 fn parse_pretty(sess: &Session,
253                 matches: &getopts::Matches)
254                 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
255     let pretty = if sess.opts.debugging_opts.unstable_options {
256         matches.opt_default("pretty", "normal").map(|a| {
257             // stable pretty-print variants only
258             pretty::parse_pretty(sess, &a, false)
259         })
260     } else {
261         None
262     };
263     if pretty.is_none() && sess.unstable_options() {
264         matches.opt_str("unpretty").map(|a| {
265             // extended with unstable pretty-print variants
266             pretty::parse_pretty(sess, &a, true)
267         })
268     } else {
269         pretty
270     }
271 }
272
273 // Whether to stop or continue compilation.
274 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
275 pub enum Compilation {
276     Stop,
277     Continue,
278 }
279
280 impl Compilation {
281     pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
282         match self {
283             Compilation::Stop => Compilation::Stop,
284             Compilation::Continue => next(),
285         }
286     }
287 }
288
289 // A trait for customising the compilation process. Offers a number of hooks for
290 // executing custom code or customising input.
291 pub trait CompilerCalls<'a> {
292     // Hook for a callback early in the process of handling arguments. This will
293     // be called straight after options have been parsed but before anything
294     // else (e.g., selecting input and output).
295     fn early_callback(&mut self,
296                       _: &getopts::Matches,
297                       _: &config::Options,
298                       _: &ast::CrateConfig,
299                       _: &errors::registry::Registry,
300                       _: ErrorOutputType)
301                       -> Compilation {
302         Compilation::Continue
303     }
304
305     // Hook for a callback late in the process of handling arguments. This will
306     // be called just before actual compilation starts (and before build_controller
307     // is called), after all arguments etc. have been completely handled.
308     fn late_callback(&mut self,
309                      _: &getopts::Matches,
310                      _: &Session,
311                      _: &Input,
312                      _: &Option<PathBuf>,
313                      _: &Option<PathBuf>)
314                      -> Compilation {
315         Compilation::Continue
316     }
317
318     // Called after we extract the input from the arguments. Gives the implementer
319     // an opportunity to change the inputs or to add some custom input handling.
320     // The default behaviour is to simply pass through the inputs.
321     fn some_input(&mut self,
322                   input: Input,
323                   input_path: Option<PathBuf>)
324                   -> (Input, Option<PathBuf>) {
325         (input, input_path)
326     }
327
328     // Called after we extract the input from the arguments if there is no valid
329     // input. Gives the implementer an opportunity to supply alternate input (by
330     // returning a Some value) or to add custom behaviour for this error such as
331     // emitting error messages. Returning None will cause compilation to stop
332     // at this point.
333     fn no_input(&mut self,
334                 _: &getopts::Matches,
335                 _: &config::Options,
336                 _: &ast::CrateConfig,
337                 _: &Option<PathBuf>,
338                 _: &Option<PathBuf>,
339                 _: &errors::registry::Registry)
340                 -> Option<(Input, Option<PathBuf>)> {
341         None
342     }
343
344     // Create a CompilController struct for controlling the behaviour of
345     // compilation.
346     fn build_controller(&mut self, &Session, &getopts::Matches) -> CompileController<'a>;
347 }
348
349 // CompilerCalls instance for a regular rustc build.
350 #[derive(Copy, Clone)]
351 pub struct RustcDefaultCalls;
352
353 fn handle_explain(code: &str,
354                   descriptions: &errors::registry::Registry,
355                   output: ErrorOutputType) {
356     let normalised = if code.starts_with("E") {
357         code.to_string()
358     } else {
359         format!("E{0:0>4}", code)
360     };
361     match descriptions.find_description(&normalised) {
362         Some(ref description) => {
363             // Slice off the leading newline and print.
364             print!("{}", &(&description[1..]).split("\n").map(|x| {
365                 format!("{}\n", if x.starts_with("```") {
366                     "```"
367                 } else {
368                     x
369                 })
370             }).collect::<String>());
371         }
372         None => {
373             early_error(output, &format!("no extended information for {}", code));
374         }
375     }
376 }
377
378 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
379     fn early_callback(&mut self,
380                       matches: &getopts::Matches,
381                       _: &config::Options,
382                       _: &ast::CrateConfig,
383                       descriptions: &errors::registry::Registry,
384                       output: ErrorOutputType)
385                       -> Compilation {
386         if let Some(ref code) = matches.opt_str("explain") {
387             handle_explain(code, descriptions, output);
388             return Compilation::Stop;
389         }
390
391         Compilation::Continue
392     }
393
394     fn no_input(&mut self,
395                 matches: &getopts::Matches,
396                 sopts: &config::Options,
397                 cfg: &ast::CrateConfig,
398                 odir: &Option<PathBuf>,
399                 ofile: &Option<PathBuf>,
400                 descriptions: &errors::registry::Registry)
401                 -> Option<(Input, Option<PathBuf>)> {
402         match matches.free.len() {
403             0 => {
404                 if sopts.describe_lints {
405                     let mut ls = lint::LintStore::new();
406                     rustc_lint::register_builtins(&mut ls, None);
407                     describe_lints(&ls, false);
408                     return None;
409                 }
410                 let dep_graph = DepGraph::new(sopts.build_dep_graph());
411                 let cstore = Rc::new(CStore::new(&dep_graph));
412                 let mut sess = build_session(sopts.clone(),
413                     &dep_graph,
414                     None,
415                     descriptions.clone(),
416                     cstore.clone());
417                 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
418                 let mut cfg = config::build_configuration(&sess, cfg.clone());
419                 target_features::add_configuration(&mut cfg, &sess);
420                 sess.parse_sess.config = cfg;
421                 let should_stop =
422                     RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
423
424                 if should_stop == Compilation::Stop {
425                     return None;
426                 }
427                 early_error(sopts.error_format, "no input filename given");
428             }
429             1 => panic!("make_input should have provided valid inputs"),
430             _ => early_error(sopts.error_format, "multiple input filenames provided"),
431         }
432     }
433
434     fn late_callback(&mut self,
435                      matches: &getopts::Matches,
436                      sess: &Session,
437                      input: &Input,
438                      odir: &Option<PathBuf>,
439                      ofile: &Option<PathBuf>)
440                      -> Compilation {
441         RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
442             .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input))
443     }
444
445     fn build_controller(&mut self,
446                         sess: &Session,
447                         matches: &getopts::Matches)
448                         -> CompileController<'a> {
449         let mut control = CompileController::basic();
450
451         if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
452             if ppm.needs_ast_map(&opt_uii) {
453                 control.after_hir_lowering.stop = Compilation::Stop;
454
455                 control.after_parse.callback = box move |state| {
456                     state.krate = Some(pretty::fold_crate(state.krate.take().unwrap(), ppm));
457                 };
458                 control.after_hir_lowering.callback = box move |state| {
459                     pretty::print_after_hir_lowering(state.session,
460                                                      state.hir_map.unwrap(),
461                                                      state.analysis.unwrap(),
462                                                      state.resolutions.unwrap(),
463                                                      state.input,
464                                                      &state.expanded_crate.take().unwrap(),
465                                                      state.crate_name.unwrap(),
466                                                      ppm,
467                                                      state.arena.unwrap(),
468                                                      state.arenas.unwrap(),
469                                                      opt_uii.clone(),
470                                                      state.out_file);
471                 };
472             } else {
473                 control.after_parse.stop = Compilation::Stop;
474
475                 control.after_parse.callback = box move |state| {
476                     let krate = pretty::fold_crate(state.krate.take().unwrap(), ppm);
477                     pretty::print_after_parsing(state.session,
478                                                 state.input,
479                                                 &krate,
480                                                 ppm,
481                                                 state.out_file);
482                 };
483             }
484
485             return control;
486         }
487
488         if sess.opts.debugging_opts.parse_only ||
489            sess.opts.debugging_opts.show_span.is_some() ||
490            sess.opts.debugging_opts.ast_json_noexpand {
491             control.after_parse.stop = Compilation::Stop;
492         }
493
494         if sess.opts.debugging_opts.no_analysis ||
495            sess.opts.debugging_opts.ast_json {
496             control.after_hir_lowering.stop = Compilation::Stop;
497         }
498
499         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
500                                                    i == OutputType::Metadata) {
501             control.after_llvm.stop = Compilation::Stop;
502         }
503
504         if save_analysis(sess) {
505             control.after_analysis.callback = box |state| {
506                 time(state.session.time_passes(), "save analysis", || {
507                     save::process_crate(state.tcx.unwrap(),
508                                         state.expanded_crate.unwrap(),
509                                         state.analysis.unwrap(),
510                                         state.crate_name.unwrap(),
511                                         DumpHandler::new(save_analysis_format(state.session),
512                                                          state.out_dir,
513                                                          state.crate_name.unwrap()))
514                 });
515             };
516             control.after_analysis.run_callback_on_error = true;
517             control.make_glob_map = resolve::MakeGlobMap::Yes;
518         }
519
520         if sess.print_fuel_crate.is_some() {
521             let old_callback = control.compilation_done.callback;
522             control.compilation_done.callback = box move |state| {
523                 old_callback(state);
524                 let sess = state.session;
525                 println!("Fuel used by {}: {}",
526                     sess.print_fuel_crate.as_ref().unwrap(),
527                     sess.print_fuel.get());
528             }
529         }
530         control
531     }
532 }
533
534 fn save_analysis(sess: &Session) -> bool {
535     sess.opts.debugging_opts.save_analysis ||
536     sess.opts.debugging_opts.save_analysis_csv ||
537     sess.opts.debugging_opts.save_analysis_api
538 }
539
540 fn save_analysis_format(sess: &Session) -> save::Format {
541     if sess.opts.debugging_opts.save_analysis {
542         save::Format::Json
543     } else if sess.opts.debugging_opts.save_analysis_csv {
544         save::Format::Csv
545     } else if sess.opts.debugging_opts.save_analysis_api {
546         save::Format::JsonApi
547     } else {
548         unreachable!();
549     }
550 }
551
552 impl RustcDefaultCalls {
553     pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation {
554         let r = matches.opt_strs("Z");
555         if r.contains(&("ls".to_string())) {
556             match input {
557                 &Input::File(ref ifile) => {
558                     let path = &(*ifile);
559                     let mut v = Vec::new();
560                     locator::list_file_metadata(&sess.target.target, path, &mut v).unwrap();
561                     println!("{}", String::from_utf8(v).unwrap());
562                 }
563                 &Input::Str { .. } => {
564                     early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
565                 }
566             }
567             return Compilation::Stop;
568         }
569
570         return Compilation::Continue;
571     }
572
573
574     fn print_crate_info(sess: &Session,
575                         input: Option<&Input>,
576                         odir: &Option<PathBuf>,
577                         ofile: &Option<PathBuf>)
578                         -> Compilation {
579         if sess.opts.prints.is_empty() {
580             return Compilation::Continue;
581         }
582
583         let attrs = match input {
584             None => None,
585             Some(input) => {
586                 let result = parse_crate_attrs(sess, input);
587                 match result {
588                     Ok(attrs) => Some(attrs),
589                     Err(mut parse_error) => {
590                         parse_error.emit();
591                         return Compilation::Stop;
592                     }
593                 }
594             }
595         };
596         for req in &sess.opts.prints {
597             match *req {
598                 PrintRequest::TargetList => {
599                     let mut targets = rustc_back::target::get_targets().collect::<Vec<String>>();
600                     targets.sort();
601                     println!("{}", targets.join("\n"));
602                 },
603                 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
604                 PrintRequest::TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
605                 PrintRequest::FileNames |
606                 PrintRequest::CrateName => {
607                     let input = match input {
608                         Some(input) => input,
609                         None => early_error(ErrorOutputType::default(), "no input file provided"),
610                     };
611                     let attrs = attrs.as_ref().unwrap();
612                     let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
613                     let id = link::find_crate_name(Some(sess), attrs, input);
614                     if *req == PrintRequest::CrateName {
615                         println!("{}", id);
616                         continue;
617                     }
618                     let crate_types = driver::collect_crate_types(sess, attrs);
619                     for &style in &crate_types {
620                         let fname = link::filename_for_input(sess, style, &id, &t_outputs);
621                         println!("{}",
622                                  fname.file_name()
623                                       .unwrap()
624                                       .to_string_lossy());
625                     }
626                 }
627                 PrintRequest::Cfg => {
628                     let allow_unstable_cfg = UnstableFeatures::from_environment()
629                         .is_nightly_build();
630
631                     let mut cfgs = Vec::new();
632                     for &(name, ref value) in sess.parse_sess.config.iter() {
633                         let gated_cfg = GatedCfg::gate(&ast::MetaItem {
634                             name: name,
635                             node: ast::MetaItemKind::Word,
636                             span: DUMMY_SP,
637                         });
638                         if !allow_unstable_cfg && gated_cfg.is_some() {
639                             continue;
640                         }
641
642                         cfgs.push(if let &Some(ref value) = value {
643                             format!("{}=\"{}\"", name, value)
644                         } else {
645                             format!("{}", name)
646                         });
647                     }
648
649                     cfgs.sort();
650                     for cfg in cfgs {
651                         println!("{}", cfg);
652                     }
653                 }
654                 PrintRequest::TargetCPUs => {
655                     let tm = create_target_machine(sess);
656                     unsafe { llvm::LLVMRustPrintTargetCPUs(tm); }
657                 }
658                 PrintRequest::TargetFeatures => {
659                     let tm = create_target_machine(sess);
660                     unsafe { llvm::LLVMRustPrintTargetFeatures(tm); }
661                 }
662                 PrintRequest::RelocationModels => {
663                     println!("Available relocation models:");
664                     for &(name, _) in RELOC_MODEL_ARGS.iter() {
665                         println!("    {}", name);
666                     }
667                     println!("");
668                 }
669                 PrintRequest::CodeModels => {
670                     println!("Available code models:");
671                     for &(name, _) in CODE_GEN_MODEL_ARGS.iter(){
672                         println!("    {}", name);
673                     }
674                     println!("");
675                 }
676             }
677         }
678         return Compilation::Stop;
679     }
680 }
681
682 /// Returns a version string such as "0.12.0-dev".
683 pub fn release_str() -> Option<&'static str> {
684     option_env!("CFG_RELEASE")
685 }
686
687 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
688 pub fn commit_hash_str() -> Option<&'static str> {
689     option_env!("CFG_VER_HASH")
690 }
691
692 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
693 pub fn commit_date_str() -> Option<&'static str> {
694     option_env!("CFG_VER_DATE")
695 }
696
697 /// Prints version information
698 pub fn version(binary: &str, matches: &getopts::Matches) {
699     let verbose = matches.opt_present("verbose");
700
701     println!("{} {}",
702              binary,
703              option_env!("CFG_VERSION").unwrap_or("unknown version"));
704     if verbose {
705         fn unw(x: Option<&str>) -> &str {
706             x.unwrap_or("unknown")
707         }
708         println!("binary: {}", binary);
709         println!("commit-hash: {}", unw(commit_hash_str()));
710         println!("commit-date: {}", unw(commit_date_str()));
711         println!("host: {}", config::host_triple());
712         println!("release: {}", unw(release_str()));
713         unsafe {
714             println!("LLVM version: {}.{}",
715                      llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor());
716         }
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 <foo> and all attempts to override)
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.to_string().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 complicated 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.iter().any(|x| *x == "no-stack-check") {
1004         early_warn(ErrorOutputType::default(),
1005                    "the --no-stack-check flag is deprecated and does nothing");
1006     }
1007
1008     if cg_flags.contains(&"passes=list".to_string()) {
1009         unsafe {
1010             ::llvm::LLVMRustPrintPasses();
1011         }
1012         return None;
1013     }
1014
1015     if matches.opt_present("version") {
1016         version("rustc", &matches);
1017         return None;
1018     }
1019
1020     Some(matches)
1021 }
1022
1023 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1024     match *input {
1025         Input::File(ref ifile) => {
1026             parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1027         }
1028         Input::Str { ref name, ref input } => {
1029             parse::parse_crate_attrs_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
1030         }
1031     }
1032 }
1033
1034 /// Runs `f` in a suitable thread for running `rustc`; returns a
1035 /// `Result` with either the return value of `f` or -- if a panic
1036 /// occurs -- the panic value.
1037 pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<Any + Send>>
1038     where F: FnOnce() -> R + Send + 'static,
1039           R: Send + 'static,
1040 {
1041     // Temporarily have stack size set to 16MB to deal with nom-using crates failing
1042     const STACK_SIZE: usize = 16 * 1024 * 1024; // 16MB
1043
1044     let mut cfg = thread::Builder::new().name("rustc".to_string());
1045
1046     // FIXME: Hacks on hacks. If the env is trying to override the stack size
1047     // then *don't* set it explicitly.
1048     if env::var_os("RUST_MIN_STACK").is_none() {
1049         cfg = cfg.stack_size(STACK_SIZE);
1050     }
1051
1052     let thread = cfg.spawn(f);
1053     thread.unwrap().join()
1054 }
1055
1056 /// Run a procedure which will detect panics in the compiler and print nicer
1057 /// error messages rather than just failing the test.
1058 ///
1059 /// The diagnostic emitter yielded to the procedure should be used for reporting
1060 /// errors of the compiler.
1061 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
1062     struct Sink(Arc<Mutex<Vec<u8>>>);
1063     impl Write for Sink {
1064         fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1065             Write::write(&mut *self.0.lock().unwrap(), data)
1066         }
1067         fn flush(&mut self) -> io::Result<()> {
1068             Ok(())
1069         }
1070     }
1071
1072     let data = Arc::new(Mutex::new(Vec::new()));
1073     let err = Sink(data.clone());
1074
1075     let result = in_rustc_thread(move || {
1076         io::set_panic(Some(box err));
1077         f()
1078     });
1079
1080     if let Err(value) = result {
1081         // Thread panicked without emitting a fatal diagnostic
1082         if !value.is::<errors::FatalError>() {
1083             let emitter =
1084                 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None));
1085             let handler = errors::Handler::with_emitter(true, false, emitter);
1086
1087             // a .span_bug or .bug call has already printed what
1088             // it wants to print.
1089             if !value.is::<errors::ExplicitBug>() {
1090                 handler.emit(&MultiSpan::new(),
1091                              "unexpected panic",
1092                              errors::Level::Bug);
1093             }
1094
1095             let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1096                       format!("we would appreciate a bug report: {}", BUG_REPORT_URL)];
1097             for note in &xs {
1098                 handler.emit(&MultiSpan::new(),
1099                              &note,
1100                              errors::Level::Note);
1101             }
1102             if match env::var_os("RUST_BACKTRACE") {
1103                 Some(val) => &val != "0",
1104                 None => false,
1105             } {
1106                 handler.emit(&MultiSpan::new(),
1107                              "run with `RUST_BACKTRACE=1` for a backtrace",
1108                              errors::Level::Note);
1109             }
1110
1111             writeln!(io::stderr(), "{}", str::from_utf8(&data.lock().unwrap()).unwrap()).unwrap();
1112         }
1113
1114         exit_on_err();
1115     }
1116 }
1117
1118 fn exit_on_err() -> ! {
1119     // Panic so the process returns a failure code, but don't pollute the
1120     // output with some unnecessary panic messages, we've already
1121     // printed everything that we needed to.
1122     io::set_panic(Some(box io::sink()));
1123     panic!();
1124 }
1125
1126 pub fn diagnostics_registry() -> errors::registry::Registry {
1127     use errors::registry::Registry;
1128
1129     let mut all_errors = Vec::new();
1130     all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1131     all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1132     all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
1133     all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1134     all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1135     all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
1136     all_errors.extend_from_slice(&rustc_const_eval::DIAGNOSTICS);
1137     all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1138
1139     Registry::new(&all_errors)
1140 }
1141
1142 pub fn main() {
1143     env_logger::init().unwrap();
1144     let result = run(|| run_compiler(&env::args().collect::<Vec<_>>(),
1145                                      &mut RustcDefaultCalls,
1146                                      None,
1147                                      None));
1148     process::exit(result as i32);
1149 }