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