5 //! This API is completely unstable and subject to change.
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
9 #![feature(box_syntax)]
10 #![cfg_attr(unix, feature(libc))]
12 #![feature(rustc_diagnostic_macros)]
13 #![feature(set_stdio)]
15 #![feature(integer_atomics)]
17 #![recursion_limit="256"]
19 pub extern crate getopts;
25 use pretty::{PpMode, UserIdentifiedItem};
27 //use rustc_resolve as resolve;
28 use rustc_save_analysis as save;
29 use rustc_save_analysis::DumpHandler;
30 use rustc::session::{config, Session, DiagnosticOutput};
31 use rustc::session::config::{Input, PrintRequest, ErrorOutputType, OutputType};
32 use rustc::session::config::nightly_options;
33 use rustc::session::{early_error, early_warn};
34 use rustc::lint::Lint;
36 use rustc::hir::def_id::LOCAL_CRATE;
37 use rustc::util::common::{ErrorReported, install_panic_hook, print_time_passes_entry};
38 use rustc::util::common::{set_time_depth, time};
39 use rustc_metadata::locator;
40 use rustc_metadata::cstore::CStore;
41 use rustc_codegen_utils::codegen_backend::CodegenBackend;
42 use rustc_interface::interface;
43 use rustc_interface::util::get_codegen_sysroot;
44 use rustc_data_structures::sync::SeqCst;
46 use rustc_serialize::json::ToJson;
50 use std::default::Default;
52 use std::ffi::OsString;
53 use std::io::{self, Read, Write};
55 use std::panic::{self, catch_unwind};
56 use std::path::PathBuf;
57 use std::process::{self, Command, Stdio};
59 use std::time::Instant;
62 use syntax::source_map::FileLoader;
63 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
64 use syntax::parse::{self, PResult};
65 use syntax::symbol::sym;
66 use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
70 /// Exit status code used for successful compilation and help output.
71 pub const EXIT_SUCCESS: i32 = 0;
73 /// Exit status code used for compilation failures and invalid flags.
74 pub const EXIT_FAILURE: i32 = 1;
76 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
79 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
81 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
83 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
85 pub fn source_name(input: &Input) -> FileName {
87 Input::File(ref ifile) => ifile.clone().into(),
88 Input::Str { ref name, .. } => name.clone(),
92 pub fn abort_on_err<T>(result: Result<T, ErrorReported>, sess: &Session) -> T {
95 sess.abort_if_errors();
96 panic!("error reported but abort_if_errors didn't abort???");
102 pub trait Callbacks {
103 /// Called before creating the compiler instance
104 fn config(&mut self, _config: &mut interface::Config) {}
105 /// Called after parsing. Return value instructs the compiler whether to
106 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
107 fn after_parsing(&mut self, _compiler: &interface::Compiler) -> Compilation {
108 Compilation::Continue
110 /// Called after expansion. Return value instructs the compiler whether to
111 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
112 fn after_expansion(&mut self, _compiler: &interface::Compiler) -> Compilation {
113 Compilation::Continue
115 /// Called after analysis. Return value instructs the compiler whether to
116 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
117 fn after_analysis(&mut self, _compiler: &interface::Compiler) -> Compilation {
118 Compilation::Continue
122 pub struct DefaultCallbacks;
124 impl Callbacks for DefaultCallbacks {}
127 pub struct TimePassesCallbacks {
131 impl Callbacks for TimePassesCallbacks {
132 fn config(&mut self, config: &mut interface::Config) {
134 config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time;
138 // Parse args and run the compiler. This is the primary entry point for rustc.
139 // See comments on CompilerCalls below for details about the callbacks argument.
140 // The FileLoader provides a way to load files from sources other than the file system.
143 callbacks: &mut (dyn Callbacks + Send),
144 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
145 emitter: Option<Box<dyn Write + Send>>
146 ) -> interface::Result<()> {
147 let diagnostic_output = emitter.map(|emitter| DiagnosticOutput::Raw(emitter))
148 .unwrap_or(DiagnosticOutput::Default);
149 let matches = match handle_options(args) {
150 Some(matches) => matches,
151 None => return Ok(()),
154 install_panic_hook();
156 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
158 let mut dummy_config = |sopts, cfg, diagnostic_output| {
159 let mut config = interface::Config {
162 input: Input::File(PathBuf::new()),
170 lint_caps: Default::default(),
172 callbacks.config(&mut config);
176 if let Some(ref code) = matches.opt_str("explain") {
177 handle_explain(code, sopts.error_format);
181 let (odir, ofile) = make_output(&matches);
182 let (input, input_file_path, input_err) = match make_input(&matches.free) {
185 match matches.free.len() {
187 let config = dummy_config(sopts, cfg, diagnostic_output);
188 interface::run_compiler(config, |compiler| {
189 let sopts = &compiler.session().opts;
190 if sopts.describe_lints {
193 &*compiler.session().lint_store.borrow(),
198 let should_stop = RustcDefaultCalls::print_crate_info(
199 &***compiler.codegen_backend(),
206 if should_stop == Compilation::Stop {
209 early_error(sopts.error_format, "no input filename given")
213 1 => panic!("make_input should have provided valid inputs"),
214 _ => early_error(sopts.error_format, &format!(
215 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
223 if let Some(err) = input_err {
224 // Immediately stop compilation if there was an issue reading
225 // the input (for example if the input stream is not UTF-8).
226 interface::run_compiler(dummy_config(sopts, cfg, diagnostic_output), |compiler| {
227 compiler.session().err(&err.to_string());
229 return Err(ErrorReported);
232 let mut config = interface::Config {
236 input_path: input_file_path,
243 lint_caps: Default::default(),
246 callbacks.config(&mut config);
248 interface::run_compiler(config, |compiler| {
249 let sess = compiler.session();
250 let should_stop = RustcDefaultCalls::print_crate_info(
251 &***compiler.codegen_backend(),
253 Some(compiler.input()),
254 compiler.output_dir(),
255 compiler.output_file(),
256 ).and_then(|| RustcDefaultCalls::list_metadata(
263 if should_stop == Compilation::Stop {
264 return sess.compile_status();
267 let pretty_info = parse_pretty(sess, &matches);
271 if let Some((ppm, opt_uii)) = pretty_info {
272 if ppm.needs_ast_map(&opt_uii) {
273 pretty::visit_crate(sess, &mut compiler.parse()?.peek_mut(), ppm);
274 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
275 let expanded_crate = compiler.expansion()?.take().0;
276 pretty::print_after_hir_lowering(
282 compiler.output_file().as_ref().map(|p| &**p),
286 return sess.compile_status();
288 let mut krate = compiler.parse()?.take();
289 pretty::visit_crate(sess, &mut krate, ppm);
290 pretty::print_after_parsing(
295 compiler.output_file().as_ref().map(|p| &**p),
297 return sess.compile_status();
301 if callbacks.after_parsing(compiler) == Compilation::Stop {
302 return sess.compile_status();
305 if sess.opts.debugging_opts.parse_only ||
306 sess.opts.debugging_opts.show_span.is_some() ||
307 sess.opts.debugging_opts.ast_json_noexpand {
308 return sess.compile_status();
311 compiler.register_plugins()?;
313 // Lint plugins are registered; now we can process command line flags.
314 if sess.opts.describe_lints {
315 describe_lints(&sess, &sess.lint_store.borrow(), true);
316 return sess.compile_status();
319 compiler.expansion()?;
320 if callbacks.after_expansion(compiler) == Compilation::Stop {
321 return sess.compile_status();
324 compiler.prepare_outputs()?;
326 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
327 && sess.opts.output_types.len() == 1
329 return sess.compile_status();
332 compiler.global_ctxt()?;
334 if sess.opts.debugging_opts.no_analysis ||
335 sess.opts.debugging_opts.ast_json {
336 return sess.compile_status();
339 if sess.opts.debugging_opts.save_analysis {
340 let expanded_crate = &compiler.expansion()?.peek().0;
341 let crate_name = compiler.crate_name()?.peek().clone();
342 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
343 let result = tcx.analysis(LOCAL_CRATE);
345 time(sess, "save analysis", || {
352 DumpHandler::new(compiler.output_dir().as_ref().map(|p| &**p), &crate_name)
357 // AST will be dropped *after* the `after_analysis` callback
358 // (needed by the RLS)
361 // Drop AST after creating GlobalCtxt to free memory
362 mem::drop(compiler.expansion()?.take());
365 compiler.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
367 if callbacks.after_analysis(compiler) == Compilation::Stop {
368 return sess.compile_status();
371 if sess.opts.debugging_opts.save_analysis {
372 mem::drop(compiler.expansion()?.take());
375 compiler.ongoing_codegen()?;
377 // Drop GlobalCtxt after starting codegen to free memory
378 mem::drop(compiler.global_ctxt()?.take());
380 if sess.opts.debugging_opts.print_type_sizes {
381 sess.code_stats.borrow().print_type_sizes();
386 if sess.opts.debugging_opts.perf_stats {
387 sess.print_perf_stats();
390 if sess.print_fuel_crate.is_some() {
391 eprintln!("Fuel used by {}: {}",
392 sess.print_fuel_crate.as_ref().unwrap(),
393 sess.print_fuel.load(SeqCst));
401 pub fn set_sigpipe_handler() {
403 // Set the SIGPIPE signal handler, so that an EPIPE
404 // will cause rustc to terminate, as expected.
405 assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
410 pub fn set_sigpipe_handler() {}
412 // Extract output directory and file from matches.
413 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
414 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
415 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
419 // Extract input (string or file and optional path) from matches.
420 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
421 if free_matches.len() == 1 {
422 let ifile = &free_matches[0];
424 let mut src = String::new();
425 let err = if io::stdin().read_to_string(&mut src).is_err() {
426 Some(io::Error::new(io::ErrorKind::InvalidData,
427 "couldn't read from stdin, as it did not contain valid UTF-8"))
431 Some((Input::Str { name: FileName::anon_source_code(&src), input: src },
434 Some((Input::File(PathBuf::from(ifile)),
435 Some(PathBuf::from(ifile)), None))
442 fn parse_pretty(sess: &Session,
443 matches: &getopts::Matches)
444 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
445 let pretty = if sess.opts.debugging_opts.unstable_options {
446 matches.opt_default("pretty", "normal").map(|a| {
447 // stable pretty-print variants only
448 pretty::parse_pretty(sess, &a, false)
454 if pretty.is_none() {
455 sess.opts.debugging_opts.unpretty.as_ref().map(|a| {
456 // extended with unstable pretty-print variants
457 pretty::parse_pretty(sess, &a, true)
464 // Whether to stop or continue compilation.
465 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
466 pub enum Compilation {
472 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
474 Compilation::Stop => Compilation::Stop,
475 Compilation::Continue => next(),
480 /// CompilerCalls instance for a regular rustc build.
481 #[derive(Copy, Clone)]
482 pub struct RustcDefaultCalls;
484 // FIXME remove these and use winapi 0.3 instead
485 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
487 fn stdout_isatty() -> bool {
488 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
492 fn stdout_isatty() -> bool {
495 type HANDLE = *mut u8;
496 type LPDWORD = *mut u32;
497 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
499 fn GetStdHandle(which: DWORD) -> HANDLE;
500 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
503 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
505 GetConsoleMode(handle, &mut out) != 0
509 fn handle_explain(code: &str,
510 output: ErrorOutputType) {
511 let descriptions = rustc_interface::util::diagnostics_registry();
512 let normalised = if code.starts_with("E") {
515 format!("E{0:0>4}", code)
517 match descriptions.find_description(&normalised) {
518 Some(ref description) => {
519 let mut is_in_code_block = false;
520 let mut text = String::new();
522 // Slice off the leading newline and print.
523 for line in description[1..].lines() {
524 let indent_level = line.find(|c: char| !c.is_whitespace())
525 .unwrap_or_else(|| line.len());
526 let dedented_line = &line[indent_level..];
527 if dedented_line.starts_with("```") {
528 is_in_code_block = !is_in_code_block;
529 text.push_str(&line[..(indent_level+3)]);
530 } else if is_in_code_block && dedented_line.starts_with("# ") {
539 show_content_with_pager(&text);
545 early_error(output, &format!("no extended information for {}", code));
550 fn show_content_with_pager(content: &String) {
551 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
552 OsString::from("more.com")
554 OsString::from("less")
557 let mut fallback_to_println = false;
559 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
561 if let Some(pipe) = pager.stdin.as_mut() {
562 if pipe.write_all(content.as_bytes()).is_err() {
563 fallback_to_println = true;
567 if pager.wait().is_err() {
568 fallback_to_println = true;
572 fallback_to_println = true;
576 // If pager fails for whatever reason, we should still print the content
577 // to standard output
578 if fallback_to_println {
579 print!("{}", content);
583 impl RustcDefaultCalls {
584 pub fn list_metadata(sess: &Session,
586 matches: &getopts::Matches,
589 let r = matches.opt_strs("Z");
590 if r.iter().any(|s| *s == "ls") {
592 &Input::File(ref ifile) => {
593 let path = &(*ifile);
594 let mut v = Vec::new();
595 locator::list_file_metadata(&sess.target.target,
597 &*cstore.metadata_loader,
600 println!("{}", String::from_utf8(v).unwrap());
602 &Input::Str { .. } => {
603 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
606 return Compilation::Stop;
609 Compilation::Continue
613 fn print_crate_info(codegen_backend: &dyn CodegenBackend,
615 input: Option<&Input>,
616 odir: &Option<PathBuf>,
617 ofile: &Option<PathBuf>)
619 use rustc::session::config::PrintRequest::*;
620 // PrintRequest::NativeStaticLibs is special - printed during linking
621 // (empty iterator returns true)
622 if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
623 return Compilation::Continue;
626 let attrs = match input {
629 let result = parse_crate_attrs(sess, input);
631 Ok(attrs) => Some(attrs),
632 Err(mut parse_error) => {
634 return Compilation::Stop;
639 for req in &sess.opts.prints {
642 let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
644 println!("{}", targets.join("\n"));
646 Sysroot => println!("{}", sess.sysroot.display()),
647 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
648 FileNames | CrateName => {
649 let input = input.unwrap_or_else(||
650 early_error(ErrorOutputType::default(), "no input file provided"));
651 let attrs = attrs.as_ref().unwrap();
652 let t_outputs = rustc_interface::util::build_output_filenames(
659 let id = rustc_codegen_utils::link::find_crate_name(Some(sess), attrs, input);
660 if *req == PrintRequest::CrateName {
664 let crate_types = rustc_interface::util::collect_crate_types(sess, attrs);
665 for &style in &crate_types {
666 let fname = rustc_codegen_utils::link::filename_for_input(
672 println!("{}", fname.file_name().unwrap().to_string_lossy());
676 let allow_unstable_cfg = UnstableFeatures::from_environment()
679 let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| {
680 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
681 path: ast::Path::from_ident(ast::Ident::with_empty_ctxt(name)),
682 node: ast::MetaItemKind::Word,
686 // Note that crt-static is a specially recognized cfg
687 // directive that's printed out here as part of
688 // rust-lang/rust#37406, but in general the
689 // `target_feature` cfg is gated under
690 // rust-lang/rust#29717. For now this is just
691 // specifically allowing the crt-static cfg and that's
692 // it, this is intended to get into Cargo and then go
693 // through to build scripts.
694 let value = value.as_ref().map(|s| s.as_str());
695 let value = value.as_ref().map(|s| s.as_ref());
696 if name != sym::target_feature || value != Some("crt-static") {
697 if !allow_unstable_cfg && gated_cfg.is_some() {
702 if let Some(value) = value {
703 Some(format!("{}=\"{}\"", name, value))
705 Some(name.to_string())
707 }).collect::<Vec<String>>();
714 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
715 codegen_backend.print(*req, sess);
717 // Any output here interferes with Cargo's parsing of other printed output
718 PrintRequest::NativeStaticLibs => {}
721 return Compilation::Stop;
725 /// Returns a version string such as "0.12.0-dev".
726 fn release_str() -> Option<&'static str> {
727 option_env!("CFG_RELEASE")
730 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
731 fn commit_hash_str() -> Option<&'static str> {
732 option_env!("CFG_VER_HASH")
735 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
736 fn commit_date_str() -> Option<&'static str> {
737 option_env!("CFG_VER_DATE")
740 /// Prints version information
741 pub fn version(binary: &str, matches: &getopts::Matches) {
742 let verbose = matches.opt_present("verbose");
744 println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
747 fn unw(x: Option<&str>) -> &str {
748 x.unwrap_or("unknown")
750 println!("binary: {}", binary);
751 println!("commit-hash: {}", unw(commit_hash_str()));
752 println!("commit-date: {}", unw(commit_date_str()));
753 println!("host: {}", config::host_triple());
754 println!("release: {}", unw(release_str()));
755 get_codegen_sysroot("llvm")().print_version();
759 fn usage(verbose: bool, include_unstable_options: bool) {
760 let groups = if verbose {
761 config::rustc_optgroups()
763 config::rustc_short_optgroups()
765 let mut options = getopts::Options::new();
766 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
767 (option.apply)(&mut options);
769 let message = "Usage: rustc [OPTIONS] INPUT";
770 let nightly_help = if nightly_options::is_nightly_build() {
771 "\n -Z help Print unstable compiler options"
775 let verbose_help = if verbose {
778 "\n --help -v Print the full set of options rustc accepts"
780 println!("{}\nAdditional help:
781 -C help Print codegen options
783 Print 'lint' options and default settings{}{}\n",
784 options.usage(message),
789 fn print_wall_help() {
791 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
792 default. Use `rustc -W help` to see all available lints. It's more common to put
793 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
794 the command line flag directly.
798 fn describe_lints(sess: &Session, lint_store: &lint::LintStore, loaded_plugins: bool) {
800 Available lint options:
801 -W <foo> Warn about <foo>
805 -F <foo> Forbid <foo> \
806 (deny <foo> and all attempts to override)
810 fn sort_lints(sess: &Session, lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
811 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
812 // The sort doesn't case-fold but it's doubtful we care.
813 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess), x.name));
817 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
818 -> Vec<(&'static str, Vec<lint::LintId>)> {
819 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
820 lints.sort_by_key(|l| l.0);
824 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
827 .partition(|&(_, p)| p);
828 let plugin = sort_lints(sess, plugin);
829 let builtin = sort_lints(sess, builtin);
831 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
834 .partition(|&(.., p)| p);
835 let plugin_groups = sort_lint_groups(plugin_groups);
836 let builtin_groups = sort_lint_groups(builtin_groups);
838 let max_name_len = plugin.iter()
840 .map(|&s| s.name.chars().count())
843 let padded = |x: &str| {
844 let mut s = " ".repeat(max_name_len - x.chars().count());
849 println!("Lint checks provided by rustc:\n");
850 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
851 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
853 let print_lints = |lints: Vec<&Lint>| {
855 let name = lint.name_lower().replace("_", "-");
856 println!(" {} {:7.7} {}",
858 lint.default_level.as_str(),
864 print_lints(builtin);
866 let max_name_len = max("warnings".len(),
868 .chain(&builtin_groups)
869 .map(|&(s, _)| s.chars().count())
873 let padded = |x: &str| {
874 let mut s = " ".repeat(max_name_len - x.chars().count());
879 println!("Lint groups provided by rustc:\n");
880 println!(" {} {}", padded("name"), "sub-lints");
881 println!(" {} {}", padded("----"), "---------");
882 println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
884 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
885 for (name, to) in lints {
886 let name = name.to_lowercase().replace("_", "-");
887 let desc = to.into_iter()
888 .map(|x| x.to_string().replace("_", "-"))
889 .collect::<Vec<String>>()
891 println!(" {} {}", padded(&name), desc);
896 print_lint_groups(builtin_groups);
898 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
899 (false, 0, _) | (false, _, 0) => {
900 println!("Compiler plugins can provide additional lints and lint groups. To see a \
901 listing of these, re-run `rustc -W help` with a crate filename.");
903 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
904 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
907 println!("Lint checks provided by plugins loaded by this crate:\n");
911 println!("Lint groups provided by plugins loaded by this crate:\n");
912 print_lint_groups(plugin_groups);
918 fn describe_debug_flags() {
919 println!("\nAvailable options:\n");
920 print_flag_list("-Z", config::DB_OPTIONS);
923 fn describe_codegen_flags() {
924 println!("\nAvailable codegen options:\n");
925 print_flag_list("-C", config::CG_OPTIONS);
928 fn print_flag_list<T>(cmdline_opt: &str,
929 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
930 let max_len = flag_list.iter()
931 .map(|&(name, _, opt_type_desc, _)| {
932 let extra_len = match opt_type_desc {
936 name.chars().count() + extra_len
941 for &(name, _, opt_type_desc, desc) in flag_list {
942 let (width, extra) = match opt_type_desc {
943 Some(..) => (max_len - 4, "=val"),
944 None => (max_len, ""),
946 println!(" {} {:>width$}{} -- {}",
948 name.replace("_", "-"),
955 /// Process command line options. Emits messages as appropriate. If compilation
956 /// should continue, returns a getopts::Matches object parsed from args,
957 /// otherwise returns `None`.
959 /// The compiler's handling of options is a little complicated as it ties into
960 /// our stability story, and it's even *more* complicated by historical
961 /// accidents. The current intention of each compiler option is to have one of
964 /// 1. An option is stable and can be used everywhere.
965 /// 2. An option is unstable, but was historically allowed on the stable
967 /// 3. An option is unstable, and can only be used on nightly.
969 /// Like unstable library and language features, however, unstable options have
970 /// always required a form of "opt in" to indicate that you're using them. This
971 /// provides the easy ability to scan a code base to check to see if anything
972 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
974 /// All options behind `-Z` are considered unstable by default. Other top-level
975 /// options can also be considered unstable, and they were unlocked through the
976 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
977 /// instability in both cases, though.
979 /// So with all that in mind, the comments below have some more detail about the
980 /// contortions done here to get things to work out correctly.
981 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
982 // Throw away the first argument, the name of the binary
983 let args = &args[1..];
986 // user did not write `-v` nor `-Z unstable-options`, so do not
987 // include that extra information.
992 // Parse with *all* options defined in the compiler, we don't worry about
993 // option stability here we just want to parse as much as possible.
994 let mut options = getopts::Options::new();
995 for option in config::rustc_optgroups() {
996 (option.apply)(&mut options);
998 let matches = options.parse(args).unwrap_or_else(|f|
999 early_error(ErrorOutputType::default(), &f.to_string()));
1001 // For all options we just parsed, we check a few aspects:
1003 // * If the option is stable, we're all good
1004 // * If the option wasn't passed, we're all good
1005 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1006 // ourselves), then we require the `-Z unstable-options` flag to unlock
1007 // this option that was passed.
1008 // * If we're a nightly compiler, then unstable options are now unlocked, so
1009 // we're good to go.
1010 // * Otherwise, if we're a truly unstable option then we generate an error
1011 // (unstable option being used on stable)
1012 // * If we're a historically stable-but-should-be-unstable option then we
1013 // emit a warning that we're going to turn this into an error soon.
1014 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1016 if matches.opt_present("h") || matches.opt_present("help") {
1017 // Only show unstable options in --help if we *really* accept unstable
1018 // options, which catches the case where we got `-Z unstable-options` on
1019 // the stable channel of Rust which was accidentally allowed
1021 usage(matches.opt_present("verbose"),
1022 nightly_options::is_unstable_enabled(&matches));
1026 // Handle the special case of -Wall.
1027 let wall = matches.opt_strs("W");
1028 if wall.iter().any(|x| *x == "all") {
1033 // Don't handle -W help here, because we might first load plugins.
1034 let r = matches.opt_strs("Z");
1035 if r.iter().any(|x| *x == "help") {
1036 describe_debug_flags();
1040 let cg_flags = matches.opt_strs("C");
1042 if cg_flags.iter().any(|x| *x == "help") {
1043 describe_codegen_flags();
1047 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1048 early_warn(ErrorOutputType::default(),
1049 "the --no-stack-check flag is deprecated and does nothing");
1052 if cg_flags.iter().any(|x| *x == "passes=list") {
1053 get_codegen_sysroot("llvm")().print_passes();
1057 if matches.opt_present("version") {
1058 version("rustc", &matches);
1065 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1067 Input::File(ref ifile) => {
1068 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1070 Input::Str { ref name, ref input } => {
1071 parse::parse_crate_attrs_from_source_str(name.clone(),
1078 /// Gets a list of extra command-line flags provided by the user, as strings.
1080 /// This function is used during ICEs to show more information useful for
1081 /// debugging, since some ICEs only happens with non-default compiler flags
1082 /// (and the users don't always report them).
1083 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1084 let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1086 // Avoid printing help because of empty args. This can suggest the compiler
1087 // itself is not the program root (consider RLS).
1092 let matches = if let Some(matches) = handle_options(&args) {
1098 let mut result = Vec::new();
1099 let mut excluded_cargo_defaults = false;
1100 for flag in ICE_REPORT_COMPILER_FLAGS {
1101 let prefix = if flag.len() == 1 { "-" } else { "--" };
1103 for content in &matches.opt_strs(flag) {
1104 // Split always returns the first element
1105 let name = if let Some(first) = content.split('=').next() {
1111 let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) {
1117 if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
1118 result.push(format!("{}{} {}", prefix, flag, content));
1120 excluded_cargo_defaults = true;
1125 if !result.is_empty() {
1126 Some((result, excluded_cargo_defaults))
1132 /// Runs a procedure which will detect panics in the compiler and print nicer
1133 /// error messages rather than just failing the test.
1135 /// The diagnostic emitter yielded to the procedure should be used for reporting
1136 /// errors of the compiler.
1137 pub fn report_ices_to_stderr_if_any<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
1138 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1139 if value.is::<errors::FatalErrorMarker>() {
1142 // Thread panicked without emitting a fatal diagnostic
1146 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
1150 let handler = errors::Handler::with_emitter(true, None, emitter);
1152 // a .span_bug or .bug call has already printed what
1153 // it wants to print.
1154 if !value.is::<errors::ExplicitBug>() {
1155 handler.emit(&MultiSpan::new(),
1157 errors::Level::Bug);
1160 let mut xs: Vec<Cow<'static, str>> = vec![
1161 "the compiler unexpectedly panicked. this is a bug.".into(),
1162 format!("we would appreciate a bug report: {}", BUG_REPORT_URL).into(),
1163 format!("rustc {} running on {}",
1164 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1165 config::host_triple()).into(),
1168 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1169 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1171 if excluded_cargo_defaults {
1172 xs.push("some of the compiler flags provided by cargo are hidden".into());
1177 handler.emit(&MultiSpan::new(),
1179 errors::Level::Note);
1182 panic::resume_unwind(Box::new(errors::FatalErrorMarker));
1187 /// This allows tools to enable rust logging without having to magically match rustc's
1188 /// log crate version
1189 pub fn init_rustc_env_logger() {
1190 env_logger::init_from_env("RUSTC_LOG");
1194 let start = Instant::now();
1195 init_rustc_env_logger();
1196 let mut callbacks = TimePassesCallbacks::default();
1197 let result = report_ices_to_stderr_if_any(|| {
1198 let args = env::args_os().enumerate()
1199 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1200 early_error(ErrorOutputType::default(),
1201 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1203 .collect::<Vec<_>>();
1204 run_compiler(&args, &mut callbacks, None, None)
1205 }).and_then(|result| result);
1206 let exit_code = match result {
1207 Ok(_) => EXIT_SUCCESS,
1208 Err(_) => EXIT_FAILURE,
1210 // The extra `\t` is necessary to align this label with the others.
1212 print_time_passes_entry(callbacks.time_passes, "\ttotal", start.elapsed());
1213 process::exit(exit_code);