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