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