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