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