]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/lib.rs
Rollup merge of #63055 - Mark-Simulacrum:save-analysis-clean-2, r=Xanewok
[rust.git] / src / librustc_driver / lib.rs
1 //! The Rust compiler.
2 //!
3 //! # Note
4 //!
5 //! This API is completely unstable and subject to change.
6
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
8
9 #![feature(box_syntax)]
10 #![cfg_attr(unix, feature(libc))]
11 #![feature(nll)]
12 #![feature(rustc_diagnostic_macros)]
13 #![feature(set_stdio)]
14 #![feature(no_debug)]
15 #![feature(integer_atomics)]
16
17 #![recursion_limit="256"]
18
19 pub extern crate getopts;
20 #[cfg(unix)]
21 extern crate libc;
22 #[macro_use]
23 extern crate log;
24
25 use pretty::{PpMode, UserIdentifiedItem};
26
27 //use rustc_resolve as resolve;
28 use rustc_save_analysis as save;
29 use rustc_save_analysis::DumpHandler;
30 use rustc::session::{config, Session, DiagnosticOutput};
31 use rustc::session::config::{Input, PrintRequest, ErrorOutputType, OutputType};
32 use rustc::session::config::nightly_options;
33 use rustc::session::{early_error, early_warn};
34 use rustc::lint::Lint;
35 use rustc::lint;
36 use rustc::hir::def_id::LOCAL_CRATE;
37 use rustc::util::common::{ErrorReported, install_panic_hook, print_time_passes_entry};
38 use rustc::util::common::{set_time_depth, time};
39 use rustc_metadata::locator;
40 use rustc_metadata::cstore::CStore;
41 use rustc_codegen_utils::codegen_backend::CodegenBackend;
42 use rustc_interface::interface;
43 use rustc_interface::util::get_codegen_sysroot;
44 use rustc_data_structures::sync::SeqCst;
45
46 use rustc_serialize::json::ToJson;
47
48 use std::borrow::Cow;
49 use std::cmp::max;
50 use std::default::Default;
51 use std::env;
52 use std::ffi::OsString;
53 use std::io::{self, Read, Write};
54 use std::mem;
55 use std::panic::{self, catch_unwind};
56 use std::path::PathBuf;
57 use std::process::{self, Command, Stdio};
58 use std::str;
59 use std::time::Instant;
60
61 use syntax::ast;
62 use syntax::source_map::FileLoader;
63 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
64 use syntax::parse::{self, PResult};
65 use syntax::symbol::sym;
66 use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
67
68 pub mod pretty;
69
70 /// Exit status code used for successful compilation and help output.
71 pub const EXIT_SUCCESS: i32 = 0;
72
73 /// Exit status code used for compilation failures and invalid flags.
74 pub const EXIT_FAILURE: i32 = 1;
75
76 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
77                               md#bug-reports";
78
79 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
80
81 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
82
83 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
84
85 pub fn source_name(input: &Input) -> FileName {
86     match *input {
87         Input::File(ref ifile) => ifile.clone().into(),
88         Input::Str { ref name, .. } => name.clone(),
89     }
90 }
91
92 pub fn abort_on_err<T>(result: Result<T, ErrorReported>, sess: &Session) -> T {
93     match result {
94         Err(..) => {
95             sess.abort_if_errors();
96             panic!("error reported but abort_if_errors didn't abort???");
97         }
98         Ok(x) => x,
99     }
100 }
101
102 pub trait Callbacks {
103     /// Called before creating the compiler instance
104     fn config(&mut self, _config: &mut interface::Config) {}
105     /// Called after parsing. Return value instructs the compiler whether to
106     /// continue the compilation afterwards (defaults to `Compilation::Continue`)
107     fn after_parsing(&mut self, _compiler: &interface::Compiler) -> Compilation {
108         Compilation::Continue
109     }
110     /// Called after expansion. Return value instructs the compiler whether to
111     /// continue the compilation afterwards (defaults to `Compilation::Continue`)
112     fn after_expansion(&mut self, _compiler: &interface::Compiler) -> Compilation {
113         Compilation::Continue
114     }
115     /// Called after analysis. Return value instructs the compiler whether to
116     /// continue the compilation afterwards (defaults to `Compilation::Continue`)
117     fn after_analysis(&mut self, _compiler: &interface::Compiler) -> Compilation {
118         Compilation::Continue
119     }
120 }
121
122 pub struct DefaultCallbacks;
123
124 impl Callbacks for DefaultCallbacks {}
125
126 #[derive(Default)]
127 pub struct TimePassesCallbacks {
128     time_passes: bool,
129 }
130
131 impl Callbacks for TimePassesCallbacks {
132     fn config(&mut self, config: &mut interface::Config) {
133         self.time_passes =
134             config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time;
135     }
136 }
137
138 // Parse args and run the compiler. This is the primary entry point for rustc.
139 // See comments on CompilerCalls below for details about the callbacks argument.
140 // The FileLoader provides a way to load files from sources other than the file system.
141 pub fn run_compiler(
142     args: &[String],
143     callbacks: &mut (dyn Callbacks + Send),
144     file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
145     emitter: Option<Box<dyn Write + Send>>
146 ) -> interface::Result<()> {
147     let diagnostic_output = emitter.map(|emitter| DiagnosticOutput::Raw(emitter))
148                                    .unwrap_or(DiagnosticOutput::Default);
149     let matches = match handle_options(args) {
150         Some(matches) => matches,
151         None => return Ok(()),
152     };
153
154     install_panic_hook();
155
156     let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
157
158     let mut dummy_config = |sopts, cfg, diagnostic_output| {
159         let mut config = interface::Config {
160             opts: sopts,
161             crate_cfg: cfg,
162             input: Input::File(PathBuf::new()),
163             input_path: None,
164             output_file: None,
165             output_dir: None,
166             file_loader: None,
167             diagnostic_output,
168             stderr: None,
169             crate_name: None,
170             lint_caps: Default::default(),
171         };
172         callbacks.config(&mut config);
173         config
174     };
175
176     if let Some(ref code) = matches.opt_str("explain") {
177         handle_explain(code, sopts.error_format);
178         return Ok(());
179     }
180
181     let (odir, ofile) = make_output(&matches);
182     let (input, input_file_path, input_err) = match make_input(&matches.free) {
183         Some(v) => v,
184         None => {
185             match matches.free.len() {
186                 0 => {
187                     let config = dummy_config(sopts, cfg, diagnostic_output);
188                     interface::run_compiler(config, |compiler| {
189                         let sopts = &compiler.session().opts;
190                         if sopts.describe_lints {
191                             describe_lints(
192                                 compiler.session(),
193                                 &*compiler.session().lint_store.borrow(),
194                                 false
195                             );
196                             return;
197                         }
198                         let should_stop = RustcDefaultCalls::print_crate_info(
199                             &***compiler.codegen_backend(),
200                             compiler.session(),
201                             None,
202                             &odir,
203                             &ofile
204                         );
205
206                         if should_stop == Compilation::Stop {
207                             return;
208                         }
209                         early_error(sopts.error_format, "no input filename given")
210                     });
211                     return Ok(());
212                 }
213                 1 => panic!("make_input should have provided valid inputs"),
214                 _ => early_error(sopts.error_format, &format!(
215                     "multiple input filenames provided (first two filenames are `{}` and `{}`)",
216                     matches.free[0],
217                     matches.free[1],
218                 )),
219             }
220         }
221     };
222
223     if let Some(err) = input_err {
224         // Immediately stop compilation if there was an issue reading
225         // the input (for example if the input stream is not UTF-8).
226         interface::run_compiler(dummy_config(sopts, cfg, diagnostic_output), |compiler| {
227             compiler.session().err(&err.to_string());
228         });
229         return Err(ErrorReported);
230     }
231
232     let mut config = interface::Config {
233         opts: sopts,
234         crate_cfg: cfg,
235         input,
236         input_path: input_file_path,
237         output_file: ofile,
238         output_dir: odir,
239         file_loader,
240         diagnostic_output,
241         stderr: None,
242         crate_name: None,
243         lint_caps: Default::default(),
244     };
245
246     callbacks.config(&mut config);
247
248     interface::run_compiler(config, |compiler| {
249         let sess = compiler.session();
250         let should_stop = RustcDefaultCalls::print_crate_info(
251             &***compiler.codegen_backend(),
252             sess,
253             Some(compiler.input()),
254             compiler.output_dir(),
255             compiler.output_file(),
256         ).and_then(|| RustcDefaultCalls::list_metadata(
257             sess,
258             compiler.cstore(),
259             &matches,
260             compiler.input()
261         ));
262
263         if should_stop == Compilation::Stop {
264             return sess.compile_status();
265         }
266
267         let pretty_info = parse_pretty(sess, &matches);
268
269         compiler.parse()?;
270
271         if let Some((ppm, opt_uii)) = pretty_info {
272             if ppm.needs_ast_map(&opt_uii) {
273                 pretty::visit_crate(sess, &mut compiler.parse()?.peek_mut(), ppm);
274                 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
275                     let expanded_crate = compiler.expansion()?.take().0;
276                     pretty::print_after_hir_lowering(
277                         tcx,
278                         compiler.input(),
279                         &expanded_crate,
280                         ppm,
281                         opt_uii.clone(),
282                         compiler.output_file().as_ref().map(|p| &**p),
283                     );
284                     Ok(())
285                 })?;
286                 return sess.compile_status();
287             } else {
288                 let mut krate = compiler.parse()?.take();
289                 pretty::visit_crate(sess, &mut krate, ppm);
290                 pretty::print_after_parsing(
291                     sess,
292                     &compiler.input(),
293                     &krate,
294                     ppm,
295                     compiler.output_file().as_ref().map(|p| &**p),
296                 );
297                 return sess.compile_status();
298             }
299         }
300
301         if callbacks.after_parsing(compiler) == Compilation::Stop {
302             return sess.compile_status();
303         }
304
305         if sess.opts.debugging_opts.parse_only ||
306            sess.opts.debugging_opts.show_span.is_some() ||
307            sess.opts.debugging_opts.ast_json_noexpand {
308             return sess.compile_status();
309         }
310
311         compiler.register_plugins()?;
312
313         // Lint plugins are registered; now we can process command line flags.
314         if sess.opts.describe_lints {
315             describe_lints(&sess, &sess.lint_store.borrow(), true);
316             return sess.compile_status();
317         }
318
319         compiler.expansion()?;
320         if callbacks.after_expansion(compiler) == Compilation::Stop {
321             return sess.compile_status();
322         }
323
324         compiler.prepare_outputs()?;
325
326         if sess.opts.output_types.contains_key(&OutputType::DepInfo)
327             && sess.opts.output_types.len() == 1
328         {
329             return sess.compile_status();
330         }
331
332         compiler.global_ctxt()?;
333
334         if sess.opts.debugging_opts.no_analysis ||
335            sess.opts.debugging_opts.ast_json {
336             return sess.compile_status();
337         }
338
339         if sess.opts.debugging_opts.save_analysis {
340             let expanded_crate = &compiler.expansion()?.peek().0;
341             let crate_name = compiler.crate_name()?.peek().clone();
342             compiler.global_ctxt()?.peek_mut().enter(|tcx| {
343                 let result = tcx.analysis(LOCAL_CRATE);
344
345                 time(sess, "save analysis", || {
346                     save::process_crate(
347                         tcx,
348                         &expanded_crate,
349                         &crate_name,
350                         &compiler.input(),
351                         None,
352                         DumpHandler::new(compiler.output_dir().as_ref().map(|p| &**p), &crate_name)
353                     )
354                 });
355
356                 result
357                 // AST will be dropped *after* the `after_analysis` callback
358                 // (needed by the RLS)
359             })?;
360         } else {
361             // Drop AST after creating GlobalCtxt to free memory
362             mem::drop(compiler.expansion()?.take());
363         }
364
365         compiler.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
366
367         if callbacks.after_analysis(compiler) == Compilation::Stop {
368             return sess.compile_status();
369         }
370
371         if sess.opts.debugging_opts.save_analysis {
372             mem::drop(compiler.expansion()?.take());
373         }
374
375         compiler.ongoing_codegen()?;
376
377         // Drop GlobalCtxt after starting codegen to free memory
378         mem::drop(compiler.global_ctxt()?.take());
379
380         if sess.opts.debugging_opts.print_type_sizes {
381             sess.code_stats.borrow().print_type_sizes();
382         }
383
384         compiler.link()?;
385
386         if sess.opts.debugging_opts.perf_stats {
387             sess.print_perf_stats();
388         }
389
390         if sess.print_fuel_crate.is_some() {
391             eprintln!("Fuel used by {}: {}",
392                 sess.print_fuel_crate.as_ref().unwrap(),
393                 sess.print_fuel.load(SeqCst));
394         }
395
396         Ok(())
397     })
398 }
399
400 #[cfg(unix)]
401 pub fn set_sigpipe_handler() {
402     unsafe {
403         // Set the SIGPIPE signal handler, so that an EPIPE
404         // will cause rustc to terminate, as expected.
405         assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
406     }
407 }
408
409 #[cfg(windows)]
410 pub fn set_sigpipe_handler() {}
411
412 // Extract output directory and file from matches.
413 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
414     let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
415     let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
416     (odir, ofile)
417 }
418
419 // Extract input (string or file and optional path) from matches.
420 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
421     if free_matches.len() == 1 {
422         let ifile = &free_matches[0];
423         if ifile == "-" {
424             let mut src = String::new();
425             let err = if io::stdin().read_to_string(&mut src).is_err() {
426                 Some(io::Error::new(io::ErrorKind::InvalidData,
427                                     "couldn't read from stdin, as it did not contain valid UTF-8"))
428             } else {
429                 None
430             };
431             Some((Input::Str { name: FileName::anon_source_code(&src), input: src },
432                   None, err))
433         } else {
434             Some((Input::File(PathBuf::from(ifile)),
435                   Some(PathBuf::from(ifile)), None))
436         }
437     } else {
438         None
439     }
440 }
441
442 fn parse_pretty(sess: &Session,
443                 matches: &getopts::Matches)
444                 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
445     let pretty = if sess.opts.debugging_opts.unstable_options {
446         matches.opt_default("pretty", "normal").map(|a| {
447             // stable pretty-print variants only
448             pretty::parse_pretty(sess, &a, false)
449         })
450     } else {
451         None
452     };
453
454     if pretty.is_none() {
455         sess.opts.debugging_opts.unpretty.as_ref().map(|a| {
456             // extended with unstable pretty-print variants
457             pretty::parse_pretty(sess, &a, true)
458         })
459     } else {
460         pretty
461     }
462 }
463
464 // Whether to stop or continue compilation.
465 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
466 pub enum Compilation {
467     Stop,
468     Continue,
469 }
470
471 impl Compilation {
472     pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
473         match self {
474             Compilation::Stop => Compilation::Stop,
475             Compilation::Continue => next(),
476         }
477     }
478 }
479
480 /// CompilerCalls instance for a regular rustc build.
481 #[derive(Copy, Clone)]
482 pub struct RustcDefaultCalls;
483
484 // FIXME remove these and use winapi 0.3 instead
485 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
486 #[cfg(unix)]
487 fn stdout_isatty() -> bool {
488     unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
489 }
490
491 #[cfg(windows)]
492 fn stdout_isatty() -> bool {
493     type DWORD = u32;
494     type BOOL = i32;
495     type HANDLE = *mut u8;
496     type LPDWORD = *mut u32;
497     const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
498     extern "system" {
499         fn GetStdHandle(which: DWORD) -> HANDLE;
500         fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
501     }
502     unsafe {
503         let handle = GetStdHandle(STD_OUTPUT_HANDLE);
504         let mut out = 0;
505         GetConsoleMode(handle, &mut out) != 0
506     }
507 }
508
509 fn handle_explain(code: &str,
510                   output: ErrorOutputType) {
511     let descriptions = rustc_interface::util::diagnostics_registry();
512     let normalised = if code.starts_with("E") {
513         code.to_string()
514     } else {
515         format!("E{0:0>4}", code)
516     };
517     match descriptions.find_description(&normalised) {
518         Some(ref description) => {
519             let mut is_in_code_block = false;
520             let mut text = String::new();
521
522             // Slice off the leading newline and print.
523             for line in description[1..].lines() {
524                 let indent_level = line.find(|c: char| !c.is_whitespace())
525                     .unwrap_or_else(|| line.len());
526                 let dedented_line = &line[indent_level..];
527                 if dedented_line.starts_with("```") {
528                     is_in_code_block = !is_in_code_block;
529                     text.push_str(&line[..(indent_level+3)]);
530                 } else if is_in_code_block && dedented_line.starts_with("# ") {
531                     continue;
532                 } else {
533                     text.push_str(line);
534                 }
535                 text.push('\n');
536             }
537
538             if stdout_isatty() {
539                 show_content_with_pager(&text);
540             } else {
541                 print!("{}", text);
542             }
543         }
544         None => {
545             early_error(output, &format!("no extended information for {}", code));
546         }
547     }
548 }
549
550 fn show_content_with_pager(content: &String) {
551     let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
552         OsString::from("more.com")
553     } else {
554         OsString::from("less")
555     });
556
557     let mut fallback_to_println = false;
558
559     match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
560         Ok(mut pager) => {
561             if let Some(pipe) = pager.stdin.as_mut() {
562                 if pipe.write_all(content.as_bytes()).is_err() {
563                     fallback_to_println = true;
564                 }
565             }
566
567             if pager.wait().is_err() {
568                 fallback_to_println = true;
569             }
570         }
571         Err(_) => {
572             fallback_to_println = true;
573         }
574     }
575
576     // If pager fails for whatever reason, we should still print the content
577     // to standard output
578     if fallback_to_println {
579         print!("{}", content);
580     }
581 }
582
583 impl RustcDefaultCalls {
584     pub fn list_metadata(sess: &Session,
585                          cstore: &CStore,
586                          matches: &getopts::Matches,
587                          input: &Input)
588                          -> Compilation {
589         let r = matches.opt_strs("Z");
590         if r.iter().any(|s| *s == "ls") {
591             match input {
592                 &Input::File(ref ifile) => {
593                     let path = &(*ifile);
594                     let mut v = Vec::new();
595                     locator::list_file_metadata(&sess.target.target,
596                                                 path,
597                                                 &*cstore.metadata_loader,
598                                                 &mut v)
599                             .unwrap();
600                     println!("{}", String::from_utf8(v).unwrap());
601                 }
602                 &Input::Str { .. } => {
603                     early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
604                 }
605             }
606             return Compilation::Stop;
607         }
608
609         Compilation::Continue
610     }
611
612
613     fn print_crate_info(codegen_backend: &dyn CodegenBackend,
614                         sess: &Session,
615                         input: Option<&Input>,
616                         odir: &Option<PathBuf>,
617                         ofile: &Option<PathBuf>)
618                         -> Compilation {
619         use rustc::session::config::PrintRequest::*;
620         // PrintRequest::NativeStaticLibs is special - printed during linking
621         // (empty iterator returns true)
622         if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
623             return Compilation::Continue;
624         }
625
626         let attrs = match input {
627             None => None,
628             Some(input) => {
629                 let result = parse_crate_attrs(sess, input);
630                 match result {
631                     Ok(attrs) => Some(attrs),
632                     Err(mut parse_error) => {
633                         parse_error.emit();
634                         return Compilation::Stop;
635                     }
636                 }
637             }
638         };
639         for req in &sess.opts.prints {
640             match *req {
641                 TargetList => {
642                     let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
643                     targets.sort();
644                     println!("{}", targets.join("\n"));
645                 },
646                 Sysroot => println!("{}", sess.sysroot.display()),
647                 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
648                 FileNames | CrateName => {
649                     let input = input.unwrap_or_else(||
650                         early_error(ErrorOutputType::default(), "no input file provided"));
651                     let attrs = attrs.as_ref().unwrap();
652                     let t_outputs = rustc_interface::util::build_output_filenames(
653                         input,
654                         odir,
655                         ofile,
656                         attrs,
657                         sess
658                     );
659                     let id = rustc_codegen_utils::link::find_crate_name(Some(sess), attrs, input);
660                     if *req == PrintRequest::CrateName {
661                         println!("{}", id);
662                         continue;
663                     }
664                     let crate_types = rustc_interface::util::collect_crate_types(sess, attrs);
665                     for &style in &crate_types {
666                         let fname = rustc_codegen_utils::link::filename_for_input(
667                             sess,
668                             style,
669                             &id,
670                             &t_outputs
671                         );
672                         println!("{}", fname.file_name().unwrap().to_string_lossy());
673                     }
674                 }
675                 Cfg => {
676                     let allow_unstable_cfg = UnstableFeatures::from_environment()
677                         .is_nightly_build();
678
679                     let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| {
680                         let gated_cfg = GatedCfg::gate(&ast::MetaItem {
681                             path: ast::Path::from_ident(ast::Ident::with_empty_ctxt(name)),
682                             node: ast::MetaItemKind::Word,
683                             span: DUMMY_SP,
684                         });
685
686                         // Note that crt-static is a specially recognized cfg
687                         // directive that's printed out here as part of
688                         // rust-lang/rust#37406, but in general the
689                         // `target_feature` cfg is gated under
690                         // rust-lang/rust#29717. For now this is just
691                         // specifically allowing the crt-static cfg and that's
692                         // it, this is intended to get into Cargo and then go
693                         // through to build scripts.
694                         let value = value.as_ref().map(|s| s.as_str());
695                         let value = value.as_ref().map(|s| s.as_ref());
696                         if name != sym::target_feature || value != Some("crt-static") {
697                             if !allow_unstable_cfg && gated_cfg.is_some() {
698                                 return None
699                             }
700                         }
701
702                         if let Some(value) = value {
703                             Some(format!("{}=\"{}\"", name, value))
704                         } else {
705                             Some(name.to_string())
706                         }
707                     }).collect::<Vec<String>>();
708
709                     cfgs.sort();
710                     for cfg in cfgs {
711                         println!("{}", cfg);
712                     }
713                 }
714                 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
715                     codegen_backend.print(*req, sess);
716                 }
717                 // Any output here interferes with Cargo's parsing of other printed output
718                 PrintRequest::NativeStaticLibs => {}
719             }
720         }
721         return Compilation::Stop;
722     }
723 }
724
725 /// Returns a version string such as "0.12.0-dev".
726 fn release_str() -> Option<&'static str> {
727     option_env!("CFG_RELEASE")
728 }
729
730 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
731 fn commit_hash_str() -> Option<&'static str> {
732     option_env!("CFG_VER_HASH")
733 }
734
735 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
736 fn commit_date_str() -> Option<&'static str> {
737     option_env!("CFG_VER_DATE")
738 }
739
740 /// Prints version information
741 pub fn version(binary: &str, matches: &getopts::Matches) {
742     let verbose = matches.opt_present("verbose");
743
744     println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
745
746     if verbose {
747         fn unw(x: Option<&str>) -> &str {
748             x.unwrap_or("unknown")
749         }
750         println!("binary: {}", binary);
751         println!("commit-hash: {}", unw(commit_hash_str()));
752         println!("commit-date: {}", unw(commit_date_str()));
753         println!("host: {}", config::host_triple());
754         println!("release: {}", unw(release_str()));
755         get_codegen_sysroot("llvm")().print_version();
756     }
757 }
758
759 fn usage(verbose: bool, include_unstable_options: bool) {
760     let groups = if verbose {
761         config::rustc_optgroups()
762     } else {
763         config::rustc_short_optgroups()
764     };
765     let mut options = getopts::Options::new();
766     for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
767         (option.apply)(&mut options);
768     }
769     let message = "Usage: rustc [OPTIONS] INPUT";
770     let nightly_help = if nightly_options::is_nightly_build() {
771         "\n    -Z help             Print unstable compiler options"
772     } else {
773         ""
774     };
775     let verbose_help = if verbose {
776         ""
777     } else {
778         "\n    --help -v           Print the full set of options rustc accepts"
779     };
780     println!("{}\nAdditional help:
781     -C help             Print codegen options
782     -W help             \
783               Print 'lint' options and default settings{}{}\n",
784              options.usage(message),
785              nightly_help,
786              verbose_help);
787 }
788
789 fn print_wall_help() {
790     println!("
791 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
792 default. Use `rustc -W help` to see all available lints. It's more common to put
793 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
794 the command line flag directly.
795 ");
796 }
797
798 fn describe_lints(sess: &Session, lint_store: &lint::LintStore, loaded_plugins: bool) {
799     println!("
800 Available lint options:
801     -W <foo>           Warn about <foo>
802     -A <foo>           \
803               Allow <foo>
804     -D <foo>           Deny <foo>
805     -F <foo>           Forbid <foo> \
806               (deny <foo> and all attempts to override)
807
808 ");
809
810     fn sort_lints(sess: &Session, lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
811         let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
812         // The sort doesn't case-fold but it's doubtful we care.
813         lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess), x.name));
814         lints
815     }
816
817     fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
818                         -> Vec<(&'static str, Vec<lint::LintId>)> {
819         let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
820         lints.sort_by_key(|l| l.0);
821         lints
822     }
823
824     let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
825                                                    .iter()
826                                                    .cloned()
827                                                    .partition(|&(_, p)| p);
828     let plugin = sort_lints(sess, plugin);
829     let builtin = sort_lints(sess, builtin);
830
831     let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
832                                                                  .iter()
833                                                                  .cloned()
834                                                                  .partition(|&(.., p)| p);
835     let plugin_groups = sort_lint_groups(plugin_groups);
836     let builtin_groups = sort_lint_groups(builtin_groups);
837
838     let max_name_len = plugin.iter()
839                              .chain(&builtin)
840                              .map(|&s| s.name.chars().count())
841                              .max()
842                              .unwrap_or(0);
843     let padded = |x: &str| {
844         let mut s = " ".repeat(max_name_len - x.chars().count());
845         s.push_str(x);
846         s
847     };
848
849     println!("Lint checks provided by rustc:\n");
850     println!("    {}  {:7.7}  {}", padded("name"), "default", "meaning");
851     println!("    {}  {:7.7}  {}", padded("----"), "-------", "-------");
852
853     let print_lints = |lints: Vec<&Lint>| {
854         for lint in lints {
855             let name = lint.name_lower().replace("_", "-");
856             println!("    {}  {:7.7}  {}",
857                      padded(&name),
858                      lint.default_level.as_str(),
859                      lint.desc);
860         }
861         println!("\n");
862     };
863
864     print_lints(builtin);
865
866     let max_name_len = max("warnings".len(),
867                            plugin_groups.iter()
868                                         .chain(&builtin_groups)
869                                         .map(|&(s, _)| s.chars().count())
870                                         .max()
871                                         .unwrap_or(0));
872
873     let padded = |x: &str| {
874         let mut s = " ".repeat(max_name_len - x.chars().count());
875         s.push_str(x);
876         s
877     };
878
879     println!("Lint groups provided by rustc:\n");
880     println!("    {}  {}", padded("name"), "sub-lints");
881     println!("    {}  {}", padded("----"), "---------");
882     println!("    {}  {}", padded("warnings"), "all lints that are set to issue warnings");
883
884     let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
885         for (name, to) in lints {
886             let name = name.to_lowercase().replace("_", "-");
887             let desc = to.into_iter()
888                          .map(|x| x.to_string().replace("_", "-"))
889                          .collect::<Vec<String>>()
890                          .join(", ");
891             println!("    {}  {}", padded(&name), desc);
892         }
893         println!("\n");
894     };
895
896     print_lint_groups(builtin_groups);
897
898     match (loaded_plugins, plugin.len(), plugin_groups.len()) {
899         (false, 0, _) | (false, _, 0) => {
900             println!("Compiler plugins can provide additional lints and lint groups. To see a \
901                       listing of these, re-run `rustc -W help` with a crate filename.");
902         }
903         (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
904         (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
905         (true, l, g) => {
906             if l > 0 {
907                 println!("Lint checks provided by plugins loaded by this crate:\n");
908                 print_lints(plugin);
909             }
910             if g > 0 {
911                 println!("Lint groups provided by plugins loaded by this crate:\n");
912                 print_lint_groups(plugin_groups);
913             }
914         }
915     }
916 }
917
918 fn describe_debug_flags() {
919     println!("\nAvailable options:\n");
920     print_flag_list("-Z", config::DB_OPTIONS);
921 }
922
923 fn describe_codegen_flags() {
924     println!("\nAvailable codegen options:\n");
925     print_flag_list("-C", config::CG_OPTIONS);
926 }
927
928 fn print_flag_list<T>(cmdline_opt: &str,
929                       flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
930     let max_len = flag_list.iter()
931                            .map(|&(name, _, opt_type_desc, _)| {
932                                let extra_len = match opt_type_desc {
933                                    Some(..) => 4,
934                                    None => 0,
935                                };
936                                name.chars().count() + extra_len
937                            })
938                            .max()
939                            .unwrap_or(0);
940
941     for &(name, _, opt_type_desc, desc) in flag_list {
942         let (width, extra) = match opt_type_desc {
943             Some(..) => (max_len - 4, "=val"),
944             None => (max_len, ""),
945         };
946         println!("    {} {:>width$}{} -- {}",
947                  cmdline_opt,
948                  name.replace("_", "-"),
949                  extra,
950                  desc,
951                  width = width);
952     }
953 }
954
955 /// Process command line options. Emits messages as appropriate. If compilation
956 /// should continue, returns a getopts::Matches object parsed from args,
957 /// otherwise returns `None`.
958 ///
959 /// The compiler's handling of options is a little complicated as it ties into
960 /// our stability story, and it's even *more* complicated by historical
961 /// accidents. The current intention of each compiler option is to have one of
962 /// three modes:
963 ///
964 /// 1. An option is stable and can be used everywhere.
965 /// 2. An option is unstable, but was historically allowed on the stable
966 ///    channel.
967 /// 3. An option is unstable, and can only be used on nightly.
968 ///
969 /// Like unstable library and language features, however, unstable options have
970 /// always required a form of "opt in" to indicate that you're using them. This
971 /// provides the easy ability to scan a code base to check to see if anything
972 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
973 ///
974 /// All options behind `-Z` are considered unstable by default. Other top-level
975 /// options can also be considered unstable, and they were unlocked through the
976 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
977 /// instability in both cases, though.
978 ///
979 /// So with all that in mind, the comments below have some more detail about the
980 /// contortions done here to get things to work out correctly.
981 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
982     // Throw away the first argument, the name of the binary
983     let args = &args[1..];
984
985     if args.is_empty() {
986         // user did not write `-v` nor `-Z unstable-options`, so do not
987         // include that extra information.
988         usage(false, false);
989         return None;
990     }
991
992     // Parse with *all* options defined in the compiler, we don't worry about
993     // option stability here we just want to parse as much as possible.
994     let mut options = getopts::Options::new();
995     for option in config::rustc_optgroups() {
996         (option.apply)(&mut options);
997     }
998     let matches = options.parse(args).unwrap_or_else(|f|
999         early_error(ErrorOutputType::default(), &f.to_string()));
1000
1001     // For all options we just parsed, we check a few aspects:
1002     //
1003     // * If the option is stable, we're all good
1004     // * If the option wasn't passed, we're all good
1005     // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1006     //   ourselves), then we require the `-Z unstable-options` flag to unlock
1007     //   this option that was passed.
1008     // * If we're a nightly compiler, then unstable options are now unlocked, so
1009     //   we're good to go.
1010     // * Otherwise, if we're a truly unstable option then we generate an error
1011     //   (unstable option being used on stable)
1012     // * If we're a historically stable-but-should-be-unstable option then we
1013     //   emit a warning that we're going to turn this into an error soon.
1014     nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1015
1016     if matches.opt_present("h") || matches.opt_present("help") {
1017         // Only show unstable options in --help if we *really* accept unstable
1018         // options, which catches the case where we got `-Z unstable-options` on
1019         // the stable channel of Rust which was accidentally allowed
1020         // historically.
1021         usage(matches.opt_present("verbose"),
1022               nightly_options::is_unstable_enabled(&matches));
1023         return None;
1024     }
1025
1026     // Handle the special case of -Wall.
1027     let wall = matches.opt_strs("W");
1028     if wall.iter().any(|x| *x == "all") {
1029         print_wall_help();
1030         return None;
1031     }
1032
1033     // Don't handle -W help here, because we might first load plugins.
1034     let r = matches.opt_strs("Z");
1035     if r.iter().any(|x| *x == "help") {
1036         describe_debug_flags();
1037         return None;
1038     }
1039
1040     let cg_flags = matches.opt_strs("C");
1041
1042     if cg_flags.iter().any(|x| *x == "help") {
1043         describe_codegen_flags();
1044         return None;
1045     }
1046
1047     if cg_flags.iter().any(|x| *x == "no-stack-check") {
1048         early_warn(ErrorOutputType::default(),
1049                    "the --no-stack-check flag is deprecated and does nothing");
1050     }
1051
1052     if cg_flags.iter().any(|x| *x == "passes=list") {
1053         get_codegen_sysroot("llvm")().print_passes();
1054         return None;
1055     }
1056
1057     if matches.opt_present("version") {
1058         version("rustc", &matches);
1059         return None;
1060     }
1061
1062     Some(matches)
1063 }
1064
1065 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1066     match *input {
1067         Input::File(ref ifile) => {
1068             parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1069         }
1070         Input::Str { ref name, ref input } => {
1071             parse::parse_crate_attrs_from_source_str(name.clone(),
1072                                                      input.clone(),
1073                                                      &sess.parse_sess)
1074         }
1075     }
1076 }
1077
1078 /// Gets a list of extra command-line flags provided by the user, as strings.
1079 ///
1080 /// This function is used during ICEs to show more information useful for
1081 /// debugging, since some ICEs only happens with non-default compiler flags
1082 /// (and the users don't always report them).
1083 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1084     let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1085
1086     // Avoid printing help because of empty args. This can suggest the compiler
1087     // itself is not the program root (consider RLS).
1088     if args.len() < 2 {
1089         return None;
1090     }
1091
1092     let matches = if let Some(matches) = handle_options(&args) {
1093         matches
1094     } else {
1095         return None;
1096     };
1097
1098     let mut result = Vec::new();
1099     let mut excluded_cargo_defaults = false;
1100     for flag in ICE_REPORT_COMPILER_FLAGS {
1101         let prefix = if flag.len() == 1 { "-" } else { "--" };
1102
1103         for content in &matches.opt_strs(flag) {
1104             // Split always returns the first element
1105             let name = if let Some(first) = content.split('=').next() {
1106                 first
1107             } else {
1108                 &content
1109             };
1110
1111             let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) {
1112                 name
1113             } else {
1114                 content
1115             };
1116
1117             if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
1118                 result.push(format!("{}{} {}", prefix, flag, content));
1119             } else {
1120                 excluded_cargo_defaults = true;
1121             }
1122         }
1123     }
1124
1125     if !result.is_empty() {
1126         Some((result, excluded_cargo_defaults))
1127     } else {
1128         None
1129     }
1130 }
1131
1132 /// Runs a procedure which will detect panics in the compiler and print nicer
1133 /// error messages rather than just failing the test.
1134 ///
1135 /// The diagnostic emitter yielded to the procedure should be used for reporting
1136 /// errors of the compiler.
1137 pub fn report_ices_to_stderr_if_any<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
1138     catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1139         if value.is::<errors::FatalErrorMarker>() {
1140             ErrorReported
1141         } else {
1142             // Thread panicked without emitting a fatal diagnostic
1143             eprintln!("");
1144
1145             let emitter =
1146                 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
1147                                                                 None,
1148                                                                 false,
1149                                                                 false));
1150             let handler = errors::Handler::with_emitter(true, None, emitter);
1151
1152             // a .span_bug or .bug call has already printed what
1153             // it wants to print.
1154             if !value.is::<errors::ExplicitBug>() {
1155                 handler.emit(&MultiSpan::new(),
1156                              "unexpected panic",
1157                              errors::Level::Bug);
1158             }
1159
1160             let mut xs: Vec<Cow<'static, str>> = vec![
1161                 "the compiler unexpectedly panicked. this is a bug.".into(),
1162                 format!("we would appreciate a bug report: {}", BUG_REPORT_URL).into(),
1163                 format!("rustc {} running on {}",
1164                         option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1165                         config::host_triple()).into(),
1166             ];
1167
1168             if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1169                 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1170
1171                 if excluded_cargo_defaults {
1172                     xs.push("some of the compiler flags provided by cargo are hidden".into());
1173                 }
1174             }
1175
1176             for note in &xs {
1177                 handler.emit(&MultiSpan::new(),
1178                              note,
1179                              errors::Level::Note);
1180             }
1181
1182             panic::resume_unwind(Box::new(errors::FatalErrorMarker));
1183         }
1184     })
1185 }
1186
1187 /// This allows tools to enable rust logging without having to magically match rustc's
1188 /// log crate version
1189 pub fn init_rustc_env_logger() {
1190     env_logger::init_from_env("RUSTC_LOG");
1191 }
1192
1193 pub fn main() {
1194     let start = Instant::now();
1195     init_rustc_env_logger();
1196     let mut callbacks = TimePassesCallbacks::default();
1197     let result = report_ices_to_stderr_if_any(|| {
1198         let args = env::args_os().enumerate()
1199             .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1200                 early_error(ErrorOutputType::default(),
1201                             &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1202             }))
1203             .collect::<Vec<_>>();
1204         run_compiler(&args, &mut callbacks, None, None)
1205     }).and_then(|result| result);
1206     let exit_code = match result {
1207         Ok(_) => EXIT_SUCCESS,
1208         Err(_) => EXIT_FAILURE,
1209     };
1210     // The extra `\t` is necessary to align this label with the others.
1211     set_time_depth(0);
1212     print_time_passes_entry(callbacks.time_passes, "\ttotal", start.elapsed());
1213     process::exit(exit_code);
1214 }