]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/lib.rs
Auto merge of #41990 - qnighy:disallow-underscore-suffix-for-string-like-literals...
[rust.git] / src / librustc_driver / lib.rs
1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! The Rust compiler.
12 //!
13 //! # Note
14 //!
15 //! This API is completely unstable and subject to change.
16
17 #![crate_name = "rustc_driver"]
18 #![crate_type = "dylib"]
19 #![crate_type = "rlib"]
20 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
21       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
22       html_root_url = "https://doc.rust-lang.org/nightly/")]
23 #![deny(warnings)]
24
25 #![feature(box_syntax)]
26 #![feature(libc)]
27 #![feature(quote)]
28 #![feature(rustc_diagnostic_macros)]
29 #![feature(set_stdio)]
30
31 #![cfg_attr(stage0, unstable(feature = "rustc_private", issue = "27812"))]
32 #![cfg_attr(stage0, feature(rustc_private))]
33 #![cfg_attr(stage0, feature(staged_api))]
34 #![cfg_attr(stage0, feature(loop_break_value))]
35
36 extern crate arena;
37 extern crate getopts;
38 extern crate graphviz;
39 extern crate env_logger;
40 extern crate libc;
41 extern crate rustc;
42 extern crate rustc_back;
43 extern crate rustc_borrowck;
44 extern crate rustc_const_eval;
45 extern crate rustc_data_structures;
46 extern crate rustc_errors as errors;
47 extern crate rustc_passes;
48 extern crate rustc_lint;
49 extern crate rustc_plugin;
50 extern crate rustc_privacy;
51 extern crate rustc_incremental;
52 extern crate rustc_metadata;
53 extern crate rustc_mir;
54 extern crate rustc_resolve;
55 extern crate rustc_save_analysis;
56 extern crate rustc_trans;
57 extern crate rustc_typeck;
58 extern crate serialize;
59 #[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::{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         _ => "aborting due to previous error(s)".to_owned(),
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<F>(run_compiler: F) -> isize
135     where F: FnOnce() -> (CompileResult, Option<Session>) + Send + 'static
136 {
137     monitor(move || {
138         let (result, session) = run_compiler();
139         if let Err(err_count) = result {
140             if err_count > 0 {
141                 match session {
142                     Some(sess) => sess.fatal(&abort_msg(err_count)),
143                     None => {
144                         let emitter =
145                             errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None);
146                         let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
147                         handler.emit(&MultiSpan::new(),
148                                      &abort_msg(err_count),
149                                      errors::Level::Fatal);
150                         exit_on_err();
151                     }
152                 }
153             }
154         }
155     });
156     0
157 }
158
159 // Parse args and run the compiler. This is the primary entry point for rustc.
160 // See comments on CompilerCalls below for details about the callbacks argument.
161 // The FileLoader provides a way to load files from sources other than the file system.
162 pub fn run_compiler<'a>(args: &[String],
163                         callbacks: &mut CompilerCalls<'a>,
164                         file_loader: Option<Box<FileLoader + 'static>>,
165                         emitter_dest: Option<Box<Write + Send>>)
166                         -> (CompileResult, Option<Session>)
167 {
168     macro_rules! do_or_return {($expr: expr, $sess: expr) => {
169         match $expr {
170             Compilation::Stop => return (Ok(()), $sess),
171             Compilation::Continue => {}
172         }
173     }}
174
175     let matches = match handle_options(args) {
176         Some(matches) => matches,
177         None => return (Ok(()), None),
178     };
179
180     let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
181
182     if sopts.debugging_opts.debug_llvm {
183         rustc_trans::enable_llvm_debug();
184     }
185
186     let descriptions = diagnostics_registry();
187
188     do_or_return!(callbacks.early_callback(&matches,
189                                            &sopts,
190                                            &cfg,
191                                            &descriptions,
192                                            sopts.error_format),
193                                            None);
194
195     let (odir, ofile) = make_output(&matches);
196     let (input, input_file_path) = match make_input(&matches.free) {
197         Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
198         None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) {
199             Some((input, input_file_path)) => (input, input_file_path),
200             None => return (Ok(()), None),
201         },
202     };
203
204     let dep_graph = DepGraph::new(sopts.build_dep_graph());
205     let cstore = Rc::new(CStore::new(&dep_graph, box rustc_trans::LlvmMetadataLoader));
206
207     let loader = file_loader.unwrap_or(box RealFileLoader);
208     let codemap = Rc::new(CodeMap::with_file_loader(loader, sopts.file_path_mapping()));
209     let mut sess = session::build_session_with_codemap(
210         sopts, &dep_graph, input_file_path, descriptions, cstore.clone(), codemap, emitter_dest,
211     );
212     rustc_trans::init(&sess);
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, box rustc_trans::LlvmMetadataLoader));
412                 let mut sess = build_session(sopts.clone(),
413                     &dep_graph,
414                     None,
415                     descriptions.clone(),
416                     cstore.clone());
417                 rustc_trans::init(&sess);
418                 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
419                 let mut cfg = config::build_configuration(&sess, cfg.clone());
420                 target_features::add_configuration(&mut cfg, &sess);
421                 sess.parse_sess.config = cfg;
422                 let should_stop =
423                     RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
424
425                 if should_stop == Compilation::Stop {
426                     return None;
427                 }
428                 early_error(sopts.error_format, "no input filename given");
429             }
430             1 => panic!("make_input should have provided valid inputs"),
431             _ => early_error(sopts.error_format, "multiple input filenames provided"),
432         }
433     }
434
435     fn late_callback(&mut self,
436                      matches: &getopts::Matches,
437                      sess: &Session,
438                      input: &Input,
439                      odir: &Option<PathBuf>,
440                      ofile: &Option<PathBuf>)
441                      -> Compilation {
442         RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
443             .and_then(|| RustcDefaultCalls::list_metadata(sess, matches, input))
444     }
445
446     fn build_controller(&mut self,
447                         sess: &Session,
448                         matches: &getopts::Matches)
449                         -> CompileController<'a> {
450         let mut control = CompileController::basic();
451
452         if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
453             if ppm.needs_ast_map(&opt_uii) {
454                 control.after_hir_lowering.stop = Compilation::Stop;
455
456                 control.after_parse.callback = box move |state| {
457                     state.krate = Some(pretty::fold_crate(state.krate.take().unwrap(), ppm));
458                 };
459                 control.after_hir_lowering.callback = box move |state| {
460                     pretty::print_after_hir_lowering(state.session,
461                                                      state.hir_map.unwrap(),
462                                                      state.analysis.unwrap(),
463                                                      state.resolutions.unwrap(),
464                                                      state.input,
465                                                      &state.expanded_crate.take().unwrap(),
466                                                      state.crate_name.unwrap(),
467                                                      ppm,
468                                                      state.arena.unwrap(),
469                                                      state.arenas.unwrap(),
470                                                      opt_uii.clone(),
471                                                      state.out_file);
472                 };
473             } else {
474                 control.after_parse.stop = Compilation::Stop;
475
476                 control.after_parse.callback = box move |state| {
477                     let krate = pretty::fold_crate(state.krate.take().unwrap(), ppm);
478                     pretty::print_after_parsing(state.session,
479                                                 state.input,
480                                                 &krate,
481                                                 ppm,
482                                                 state.out_file);
483                 };
484             }
485
486             return control;
487         }
488
489         if sess.opts.debugging_opts.parse_only ||
490            sess.opts.debugging_opts.show_span.is_some() ||
491            sess.opts.debugging_opts.ast_json_noexpand {
492             control.after_parse.stop = Compilation::Stop;
493         }
494
495         if sess.opts.debugging_opts.no_analysis ||
496            sess.opts.debugging_opts.ast_json {
497             control.after_hir_lowering.stop = Compilation::Stop;
498         }
499
500         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
501                                                    i == OutputType::Metadata) {
502             control.after_llvm.stop = Compilation::Stop;
503         }
504
505         if save_analysis(sess) {
506             control.after_analysis.callback = box |state| {
507                 time(state.session.time_passes(), "save analysis", || {
508                     save::process_crate(state.tcx.unwrap(),
509                                         state.expanded_crate.unwrap(),
510                                         state.analysis.unwrap(),
511                                         state.crate_name.unwrap(),
512                                         DumpHandler::new(save_analysis_format(state.session),
513                                                          state.out_dir,
514                                                          state.crate_name.unwrap()))
515                 });
516             };
517             control.after_analysis.run_callback_on_error = true;
518             control.make_glob_map = resolve::MakeGlobMap::Yes;
519         }
520
521         if sess.print_fuel_crate.is_some() {
522             let old_callback = control.compilation_done.callback;
523             control.compilation_done.callback = box move |state| {
524                 old_callback(state);
525                 let sess = state.session;
526                 println!("Fuel used by {}: {}",
527                     sess.print_fuel_crate.as_ref().unwrap(),
528                     sess.print_fuel.get());
529             }
530         }
531         control
532     }
533 }
534
535 fn save_analysis(sess: &Session) -> bool {
536     sess.opts.debugging_opts.save_analysis ||
537     sess.opts.debugging_opts.save_analysis_csv ||
538     sess.opts.debugging_opts.save_analysis_api
539 }
540
541 fn save_analysis_format(sess: &Session) -> save::Format {
542     if sess.opts.debugging_opts.save_analysis {
543         save::Format::Json
544     } else if sess.opts.debugging_opts.save_analysis_csv {
545         save::Format::Csv
546     } else if sess.opts.debugging_opts.save_analysis_api {
547         save::Format::JsonApi
548     } else {
549         unreachable!();
550     }
551 }
552
553 impl RustcDefaultCalls {
554     pub fn list_metadata(sess: &Session, matches: &getopts::Matches, input: &Input) -> Compilation {
555         let r = matches.opt_strs("Z");
556         if r.contains(&("ls".to_string())) {
557             match input {
558                 &Input::File(ref ifile) => {
559                     let path = &(*ifile);
560                     let mut v = Vec::new();
561                     locator::list_file_metadata(&sess.target.target,
562                                                 path,
563                                                 sess.cstore.metadata_loader(),
564                                                 &mut v)
565                             .unwrap();
566                     println!("{}", String::from_utf8(v).unwrap());
567                 }
568                 &Input::Str { .. } => {
569                     early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
570                 }
571             }
572             return Compilation::Stop;
573         }
574
575         return Compilation::Continue;
576     }
577
578
579     fn print_crate_info(sess: &Session,
580                         input: Option<&Input>,
581                         odir: &Option<PathBuf>,
582                         ofile: &Option<PathBuf>)
583                         -> Compilation {
584         if sess.opts.prints.is_empty() {
585             return Compilation::Continue;
586         }
587
588         let attrs = match input {
589             None => None,
590             Some(input) => {
591                 let result = parse_crate_attrs(sess, input);
592                 match result {
593                     Ok(attrs) => Some(attrs),
594                     Err(mut parse_error) => {
595                         parse_error.emit();
596                         return Compilation::Stop;
597                     }
598                 }
599             }
600         };
601         for req in &sess.opts.prints {
602             match *req {
603                 PrintRequest::TargetList => {
604                     let mut targets = rustc_back::target::get_targets().collect::<Vec<String>>();
605                     targets.sort();
606                     println!("{}", targets.join("\n"));
607                 },
608                 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
609                 PrintRequest::TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
610                 PrintRequest::FileNames |
611                 PrintRequest::CrateName => {
612                     let input = match input {
613                         Some(input) => input,
614                         None => early_error(ErrorOutputType::default(), "no input file provided"),
615                     };
616                     let attrs = attrs.as_ref().unwrap();
617                     let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
618                     let id = link::find_crate_name(Some(sess), attrs, input);
619                     if *req == PrintRequest::CrateName {
620                         println!("{}", id);
621                         continue;
622                     }
623                     let crate_types = driver::collect_crate_types(sess, attrs);
624                     for &style in &crate_types {
625                         let fname = link::filename_for_input(sess, style, &id, &t_outputs);
626                         println!("{}",
627                                  fname.file_name()
628                                       .unwrap()
629                                       .to_string_lossy());
630                     }
631                 }
632                 PrintRequest::Cfg => {
633                     let allow_unstable_cfg = UnstableFeatures::from_environment()
634                         .is_nightly_build();
635
636                     let mut cfgs = Vec::new();
637                     for &(name, ref value) in sess.parse_sess.config.iter() {
638                         let gated_cfg = GatedCfg::gate(&ast::MetaItem {
639                             name: name,
640                             node: ast::MetaItemKind::Word,
641                             span: DUMMY_SP,
642                         });
643
644                         // Note that crt-static is a specially recognized cfg
645                         // directive that's printed out here as part of
646                         // rust-lang/rust#37406, but in general the
647                         // `target_feature` cfg is gated under
648                         // rust-lang/rust#29717. For now this is just
649                         // specifically allowing the crt-static cfg and that's
650                         // it, this is intended to get into Cargo and then go
651                         // through to build scripts.
652                         let value = value.as_ref().map(|s| s.as_str());
653                         let value = value.as_ref().map(|s| s.as_ref());
654                         if name != "target_feature" || value != Some("crt-static") {
655                             if !allow_unstable_cfg && gated_cfg.is_some() {
656                                 continue;
657                             }
658                         }
659
660                         cfgs.push(if let Some(value) = value {
661                             format!("{}=\"{}\"", name, value)
662                         } else {
663                             format!("{}", name)
664                         });
665                     }
666
667                     cfgs.sort();
668                     for cfg in cfgs {
669                         println!("{}", cfg);
670                     }
671                 }
672                 PrintRequest::RelocationModels => {
673                     println!("Available relocation models:");
674                     for &(name, _) in RELOC_MODEL_ARGS.iter() {
675                         println!("    {}", name);
676                     }
677                     println!("");
678                 }
679                 PrintRequest::CodeModels => {
680                     println!("Available code models:");
681                     for &(name, _) in CODE_GEN_MODEL_ARGS.iter(){
682                         println!("    {}", name);
683                     }
684                     println!("");
685                 }
686                 PrintRequest::TargetCPUs | PrintRequest::TargetFeatures => {
687                     rustc_trans::print(*req, sess);
688                 }
689             }
690         }
691         return Compilation::Stop;
692     }
693 }
694
695 /// Returns a version string such as "0.12.0-dev".
696 pub fn release_str() -> Option<&'static str> {
697     option_env!("CFG_RELEASE")
698 }
699
700 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
701 pub fn commit_hash_str() -> Option<&'static str> {
702     option_env!("CFG_VER_HASH")
703 }
704
705 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
706 pub fn commit_date_str() -> Option<&'static str> {
707     option_env!("CFG_VER_DATE")
708 }
709
710 /// Prints version information
711 pub fn version(binary: &str, matches: &getopts::Matches) {
712     let verbose = matches.opt_present("verbose");
713
714     println!("{} {}",
715              binary,
716              option_env!("CFG_VERSION").unwrap_or("unknown version"));
717     if verbose {
718         fn unw(x: Option<&str>) -> &str {
719             x.unwrap_or("unknown")
720         }
721         println!("binary: {}", binary);
722         println!("commit-hash: {}", unw(commit_hash_str()));
723         println!("commit-date: {}", unw(commit_date_str()));
724         println!("host: {}", config::host_triple());
725         println!("release: {}", unw(release_str()));
726         rustc_trans::print_version();
727     }
728 }
729
730 fn usage(verbose: bool, include_unstable_options: bool) {
731     let groups = if verbose {
732         config::rustc_optgroups()
733     } else {
734         config::rustc_short_optgroups()
735     };
736     let groups: Vec<_> = groups.into_iter()
737                                .filter(|x| include_unstable_options || x.is_stable())
738                                .map(|x| x.opt_group)
739                                .collect();
740     let message = format!("Usage: rustc [OPTIONS] INPUT");
741     let extra_help = if verbose {
742         ""
743     } else {
744         "\n    --help -v           Print the full set of options rustc accepts"
745     };
746     println!("{}\nAdditional help:
747     -C help             Print codegen options
748     -W help             \
749               Print 'lint' options and default settings
750     -Z help             Print internal \
751               options for debugging rustc{}\n",
752              getopts::usage(&message, &groups),
753              extra_help);
754 }
755
756 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
757     println!("
758 Available lint options:
759     -W <foo>           Warn about <foo>
760     -A <foo>           \
761               Allow <foo>
762     -D <foo>           Deny <foo>
763     -F <foo>           Forbid <foo> \
764               (deny <foo> and all attempts to override)
765
766 ");
767
768     fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
769         let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
770         lints.sort_by(|x: &&Lint, y: &&Lint| {
771             match x.default_level.cmp(&y.default_level) {
772                 // The sort doesn't case-fold but it's doubtful we care.
773                 Equal => x.name.cmp(y.name),
774                 r => r,
775             }
776         });
777         lints
778     }
779
780     fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
781                         -> Vec<(&'static str, Vec<lint::LintId>)> {
782         let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
783         lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
784                        &(y, _): &(&'static str, Vec<lint::LintId>)| {
785             x.cmp(y)
786         });
787         lints
788     }
789
790     let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
791                                                    .iter()
792                                                    .cloned()
793                                                    .partition(|&(_, p)| p);
794     let plugin = sort_lints(plugin);
795     let builtin = sort_lints(builtin);
796
797     let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
798                                                                  .iter()
799                                                                  .cloned()
800                                                                  .partition(|&(.., p)| p);
801     let plugin_groups = sort_lint_groups(plugin_groups);
802     let builtin_groups = sort_lint_groups(builtin_groups);
803
804     let max_name_len = plugin.iter()
805                              .chain(&builtin)
806                              .map(|&s| s.name.chars().count())
807                              .max()
808                              .unwrap_or(0);
809     let padded = |x: &str| {
810         let mut s = repeat(" ")
811                         .take(max_name_len - x.chars().count())
812                         .collect::<String>();
813         s.push_str(x);
814         s
815     };
816
817     println!("Lint checks provided by rustc:\n");
818     println!("    {}  {:7.7}  {}", padded("name"), "default", "meaning");
819     println!("    {}  {:7.7}  {}", padded("----"), "-------", "-------");
820
821     let print_lints = |lints: Vec<&Lint>| {
822         for lint in lints {
823             let name = lint.name_lower().replace("_", "-");
824             println!("    {}  {:7.7}  {}",
825                      padded(&name),
826                      lint.default_level.as_str(),
827                      lint.desc);
828         }
829         println!("\n");
830     };
831
832     print_lints(builtin);
833
834
835
836     let max_name_len = max("warnings".len(),
837                            plugin_groups.iter()
838                                         .chain(&builtin_groups)
839                                         .map(|&(s, _)| s.chars().count())
840                                         .max()
841                                         .unwrap_or(0));
842
843     let padded = |x: &str| {
844         let mut s = repeat(" ")
845                         .take(max_name_len - x.chars().count())
846                         .collect::<String>();
847         s.push_str(x);
848         s
849     };
850
851     println!("Lint groups provided by rustc:\n");
852     println!("    {}  {}", padded("name"), "sub-lints");
853     println!("    {}  {}", padded("----"), "---------");
854     println!("    {}  {}", padded("warnings"), "all built-in lints");
855
856     let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
857         for (name, to) in lints {
858             let name = name.to_lowercase().replace("_", "-");
859             let desc = to.into_iter()
860                          .map(|x| x.to_string().replace("_", "-"))
861                          .collect::<Vec<String>>()
862                          .join(", ");
863             println!("    {}  {}", padded(&name), desc);
864         }
865         println!("\n");
866     };
867
868     print_lint_groups(builtin_groups);
869
870     match (loaded_plugins, plugin.len(), plugin_groups.len()) {
871         (false, 0, _) | (false, _, 0) => {
872             println!("Compiler plugins can provide additional lints and lint groups. To see a \
873                       listing of these, re-run `rustc -W help` with a crate filename.");
874         }
875         (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
876         (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
877         (true, l, g) => {
878             if l > 0 {
879                 println!("Lint checks provided by plugins loaded by this crate:\n");
880                 print_lints(plugin);
881             }
882             if g > 0 {
883                 println!("Lint groups provided by plugins loaded by this crate:\n");
884                 print_lint_groups(plugin_groups);
885             }
886         }
887     }
888 }
889
890 fn describe_debug_flags() {
891     println!("\nAvailable debug options:\n");
892     print_flag_list("-Z", config::DB_OPTIONS);
893 }
894
895 fn describe_codegen_flags() {
896     println!("\nAvailable codegen options:\n");
897     print_flag_list("-C", config::CG_OPTIONS);
898 }
899
900 fn print_flag_list<T>(cmdline_opt: &str,
901                       flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
902     let max_len = flag_list.iter()
903                            .map(|&(name, _, opt_type_desc, _)| {
904                                let extra_len = match opt_type_desc {
905                                    Some(..) => 4,
906                                    None => 0,
907                                };
908                                name.chars().count() + extra_len
909                            })
910                            .max()
911                            .unwrap_or(0);
912
913     for &(name, _, opt_type_desc, desc) in flag_list {
914         let (width, extra) = match opt_type_desc {
915             Some(..) => (max_len - 4, "=val"),
916             None => (max_len, ""),
917         };
918         println!("    {} {:>width$}{} -- {}",
919                  cmdline_opt,
920                  name.replace("_", "-"),
921                  extra,
922                  desc,
923                  width = width);
924     }
925 }
926
927 /// Process command line options. Emits messages as appropriate. If compilation
928 /// should continue, returns a getopts::Matches object parsed from args,
929 /// otherwise returns None.
930 ///
931 /// The compiler's handling of options is a little complicated as it ties into
932 /// our stability story, and it's even *more* complicated by historical
933 /// accidents. The current intention of each compiler option is to have one of
934 /// three modes:
935 ///
936 /// 1. An option is stable and can be used everywhere.
937 /// 2. An option is unstable, but was historically allowed on the stable
938 ///    channel.
939 /// 3. An option is unstable, and can only be used on nightly.
940 ///
941 /// Like unstable library and language features, however, unstable options have
942 /// always required a form of "opt in" to indicate that you're using them. This
943 /// provides the easy ability to scan a code base to check to see if anything
944 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
945 ///
946 /// All options behind `-Z` are considered unstable by default. Other top-level
947 /// options can also be considered unstable, and they were unlocked through the
948 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
949 /// instability in both cases, though.
950 ///
951 /// So with all that in mind, the comments below have some more detail about the
952 /// contortions done here to get things to work out correctly.
953 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
954     // Throw away the first argument, the name of the binary
955     let args = &args[1..];
956
957     if args.is_empty() {
958         // user did not write `-v` nor `-Z unstable-options`, so do not
959         // include that extra information.
960         usage(false, false);
961         return None;
962     }
963
964     // Parse with *all* options defined in the compiler, we don't worry about
965     // option stability here we just want to parse as much as possible.
966     let all_groups: Vec<getopts::OptGroup> = config::rustc_optgroups()
967                                                  .into_iter()
968                                                  .map(|x| x.opt_group)
969                                                  .collect();
970     let matches = match getopts::getopts(&args, &all_groups) {
971         Ok(m) => m,
972         Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
973     };
974
975     // For all options we just parsed, we check a few aspects:
976     //
977     // * If the option is stable, we're all good
978     // * If the option wasn't passed, we're all good
979     // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
980     //   ourselves), then we require the `-Z unstable-options` flag to unlock
981     //   this option that was passed.
982     // * If we're a nightly compiler, then unstable options are now unlocked, so
983     //   we're good to go.
984     // * Otherwise, if we're a truly unstable option then we generate an error
985     //   (unstable option being used on stable)
986     // * If we're a historically stable-but-should-be-unstable option then we
987     //   emit a warning that we're going to turn this into an error soon.
988     nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
989
990     if matches.opt_present("h") || matches.opt_present("help") {
991         // Only show unstable options in --help if we *really* accept unstable
992         // options, which catches the case where we got `-Z unstable-options` on
993         // the stable channel of Rust which was accidentally allowed
994         // historically.
995         usage(matches.opt_present("verbose"),
996               nightly_options::is_unstable_enabled(&matches));
997         return None;
998     }
999
1000     // Don't handle -W help here, because we might first load plugins.
1001     let r = matches.opt_strs("Z");
1002     if r.iter().any(|x| *x == "help") {
1003         describe_debug_flags();
1004         return None;
1005     }
1006
1007     let cg_flags = matches.opt_strs("C");
1008     if cg_flags.iter().any(|x| *x == "help") {
1009         describe_codegen_flags();
1010         return None;
1011     }
1012
1013     if cg_flags.iter().any(|x| *x == "no-stack-check") {
1014         early_warn(ErrorOutputType::default(),
1015                    "the --no-stack-check flag is deprecated and does nothing");
1016     }
1017
1018     if cg_flags.contains(&"passes=list".to_string()) {
1019         rustc_trans::print_passes();
1020         return None;
1021     }
1022
1023     if matches.opt_present("version") {
1024         version("rustc", &matches);
1025         return None;
1026     }
1027
1028     Some(matches)
1029 }
1030
1031 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1032     match *input {
1033         Input::File(ref ifile) => {
1034             parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1035         }
1036         Input::Str { ref name, ref input } => {
1037             parse::parse_crate_attrs_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
1038         }
1039     }
1040 }
1041
1042 /// Runs `f` in a suitable thread for running `rustc`; returns a
1043 /// `Result` with either the return value of `f` or -- if a panic
1044 /// occurs -- the panic value.
1045 pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<Any + Send>>
1046     where F: FnOnce() -> R + Send + 'static,
1047           R: Send + 'static,
1048 {
1049     // Temporarily have stack size set to 16MB to deal with nom-using crates failing
1050     const STACK_SIZE: usize = 16 * 1024 * 1024; // 16MB
1051
1052     let mut cfg = thread::Builder::new().name("rustc".to_string());
1053
1054     // FIXME: Hacks on hacks. If the env is trying to override the stack size
1055     // then *don't* set it explicitly.
1056     if env::var_os("RUST_MIN_STACK").is_none() {
1057         cfg = cfg.stack_size(STACK_SIZE);
1058     }
1059
1060     let thread = cfg.spawn(f);
1061     thread.unwrap().join()
1062 }
1063
1064 /// Run a procedure which will detect panics in the compiler and print nicer
1065 /// error messages rather than just failing the test.
1066 ///
1067 /// The diagnostic emitter yielded to the procedure should be used for reporting
1068 /// errors of the compiler.
1069 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
1070     struct Sink(Arc<Mutex<Vec<u8>>>);
1071     impl Write for Sink {
1072         fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1073             Write::write(&mut *self.0.lock().unwrap(), data)
1074         }
1075         fn flush(&mut self) -> io::Result<()> {
1076             Ok(())
1077         }
1078     }
1079
1080     let data = Arc::new(Mutex::new(Vec::new()));
1081     let err = Sink(data.clone());
1082
1083     let result = in_rustc_thread(move || {
1084         io::set_panic(Some(box err));
1085         f()
1086     });
1087
1088     if let Err(value) = result {
1089         // Thread panicked without emitting a fatal diagnostic
1090         if !value.is::<errors::FatalError>() {
1091             let emitter =
1092                 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None));
1093             let handler = errors::Handler::with_emitter(true, false, emitter);
1094
1095             // a .span_bug or .bug call has already printed what
1096             // it wants to print.
1097             if !value.is::<errors::ExplicitBug>() {
1098                 handler.emit(&MultiSpan::new(),
1099                              "unexpected panic",
1100                              errors::Level::Bug);
1101             }
1102
1103             let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1104                       format!("we would appreciate a bug report: {}", BUG_REPORT_URL)];
1105             for note in &xs {
1106                 handler.emit(&MultiSpan::new(),
1107                              &note,
1108                              errors::Level::Note);
1109             }
1110             if match env::var_os("RUST_BACKTRACE") {
1111                 Some(val) => &val != "0",
1112                 None => false,
1113             } {
1114                 handler.emit(&MultiSpan::new(),
1115                              "run with `RUST_BACKTRACE=1` for a backtrace",
1116                              errors::Level::Note);
1117             }
1118
1119             writeln!(io::stderr(), "{}", str::from_utf8(&data.lock().unwrap()).unwrap()).unwrap();
1120         }
1121
1122         exit_on_err();
1123     }
1124 }
1125
1126 fn exit_on_err() -> ! {
1127     // Panic so the process returns a failure code, but don't pollute the
1128     // output with some unnecessary panic messages, we've already
1129     // printed everything that we needed to.
1130     io::set_panic(Some(box io::sink()));
1131     panic!();
1132 }
1133
1134 pub fn diagnostics_registry() -> errors::registry::Registry {
1135     use errors::registry::Registry;
1136
1137     let mut all_errors = Vec::new();
1138     all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1139     all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1140     all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
1141     all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1142     all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1143     all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
1144     all_errors.extend_from_slice(&rustc_const_eval::DIAGNOSTICS);
1145     all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1146
1147     Registry::new(&all_errors)
1148 }
1149
1150 fn get_args() -> Vec<String> {
1151     env::args_os().enumerate()
1152         .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1153              early_error(ErrorOutputType::default(),
1154                          &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1155          }))
1156         .collect()
1157 }
1158
1159 pub fn main() {
1160     env_logger::init().unwrap();
1161     let result = run(|| run_compiler(&get_args(),
1162                                      &mut RustcDefaultCalls,
1163                                      None,
1164                                      None));
1165     process::exit(result as i32);
1166 }