lib.rs 44.4 KB
Newer Older
1 2 3 4 5 6
//! The Rust compiler.
//!
//! # Note
//!
//! This API is completely unstable and subject to change.

7
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
8
#![feature(nll)]
9
#![feature(once_cell)]
M
Mark Rousskov 已提交
10
#![recursion_limit = "256"]
11

J
Jose Narvaez 已提交
12
#[macro_use]
G
Gurpreet Singh 已提交
13
extern crate tracing;
14 15
#[macro_use]
extern crate lazy_static;
16

17 18
pub extern crate rustc_plugin_impl as plugin;

U
Ujjwal Sharma 已提交
19
use rustc_ast as ast;
20
use rustc_codegen_ssa::{traits::CodegenBackend, CodegenResults};
21
use rustc_data_structures::profiling::print_time_passes_entry;
22
use rustc_data_structures::sync::SeqCst;
23 24
use rustc_errors::registry::{InvalidErrorCode, Registry};
use rustc_errors::{ErrorReported, PResult};
25
use rustc_feature::{find_gated_cfg, UnstableFeatures};
26
use rustc_hir::def_id::LOCAL_CRATE;
V
Victor Ding 已提交
27
use rustc_interface::util::{collect_crate_types, get_builtin_codegen_backend};
M
Mark Rousskov 已提交
28
use rustc_interface::{interface, Queries};
29
use rustc_lint::LintStore;
M
Mark Rousskov 已提交
30
use rustc_metadata::locator;
31 32
use rustc_middle::middle::cstore::MetadataLoader;
use rustc_middle::ty::TyCtxt;
M
Mark Rousskov 已提交
33 34
use rustc_save_analysis as save;
use rustc_save_analysis::DumpHandler;
V
Victor Ding 已提交
35
use rustc_serialize::json::{self, ToJson};
36 37
use rustc_session::config::nightly_options;
use rustc_session::config::{ErrorOutputType, Input, OutputType, PrintRequest};
L
Luca Barbieri 已提交
38
use rustc_session::getopts;
39 40 41
use rustc_session::lint::{Lint, LintId};
use rustc_session::{config, DiagnosticOutput, Session};
use rustc_session::{early_error, early_warn};
42 43
use rustc_span::source_map::{FileLoader, FileName};
use rustc_span::symbol::sym;
44

45
use std::borrow::Cow;
46
use std::cmp::max;
47
use std::default::Default;
A
Alex Crichton 已提交
48
use std::env;
49
use std::ffi::OsString;
V
Victor Ding 已提交
50
use std::fs;
51
use std::io::{self, Read, Write};
52
use std::mem;
53
use std::panic::{self, catch_unwind};
54
use std::path::PathBuf;
55
use std::process::{self, Command, Stdio};
56
use std::str;
57
use std::time::Instant;
N
Nick Cameron 已提交
58

59
mod args;
M
Mark Rousskov 已提交
60
pub mod pretty;
61

62
/// Exit status code used for successful compilation and help output.
63
pub const EXIT_SUCCESS: i32 = 0;
64

65
/// Exit status code used for compilation failures and invalid flags.
66
pub const EXIT_FAILURE: i32 = 1;
67

68 69
const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
    ?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
70 71 72 73 74 75

const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];

const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];

const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
76

77
pub fn abort_on_err<T>(result: Result<T, ErrorReported>, sess: &Session) -> T {
78
    match result {
79
        Err(..) => {
80 81 82
            sess.abort_if_errors();
            panic!("error reported but abort_if_errors didn't abort???");
        }
83 84 85 86
        Ok(x) => x,
    }
}

87 88 89
pub trait Callbacks {
    /// Called before creating the compiler instance
    fn config(&mut self, _config: &mut interface::Config) {}
90 91
    /// Called after parsing. Return value instructs the compiler whether to
    /// continue the compilation afterwards (defaults to `Compilation::Continue`)
R
Ralf Jung 已提交
92 93 94 95 96
    fn after_parsing<'tcx>(
        &mut self,
        _compiler: &interface::Compiler,
        _queries: &'tcx Queries<'tcx>,
    ) -> Compilation {
97
        Compilation::Continue
98
    }
99 100
    /// Called after expansion. Return value instructs the compiler whether to
    /// continue the compilation afterwards (defaults to `Compilation::Continue`)
R
Ralf Jung 已提交
101 102 103 104 105
    fn after_expansion<'tcx>(
        &mut self,
        _compiler: &interface::Compiler,
        _queries: &'tcx Queries<'tcx>,
    ) -> Compilation {
106
        Compilation::Continue
107
    }
108 109
    /// Called after analysis. Return value instructs the compiler whether to
    /// continue the compilation afterwards (defaults to `Compilation::Continue`)
R
Ralf Jung 已提交
110 111 112 113 114
    fn after_analysis<'tcx>(
        &mut self,
        _compiler: &interface::Compiler,
        _queries: &'tcx Queries<'tcx>,
    ) -> Compilation {
115
        Compilation::Continue
116
    }
N
Nick Cameron 已提交
117 118
}

119 120 121 122 123 124 125
#[derive(Default)]
pub struct TimePassesCallbacks {
    time_passes: bool,
}

impl Callbacks for TimePassesCallbacks {
    fn config(&mut self, config: &mut interface::Config) {
126 127
        // If a --prints=... option has been given, we don't print the "total"
        // time because it will mess up the --prints output. See #64339.
M
Mark Rousskov 已提交
128 129
        self.time_passes = config.opts.prints.is_empty()
            && (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time);
130 131 132
    }
}

133 134 135 136
pub fn diagnostics_registry() -> Registry {
    Registry::new(&rustc_error_codes::DIAGNOSTICS)
}

137 138
// Parse args and run the compiler. This is the primary entry point for rustc.
// The FileLoader provides a way to load files from sources other than the file system.
139
pub fn run_compiler(
140
    at_args: &[String],
141 142
    callbacks: &mut (dyn Callbacks + Send),
    file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
M
Mark Rousskov 已提交
143
    emitter: Option<Box<dyn Write + Send>>,
144
) -> interface::Result<()> {
145 146 147 148
    let mut args = Vec::new();
    for arg in at_args {
        match args::arg_expand(arg.clone()) {
            Ok(arg) => args.extend(arg),
M
Mark Rousskov 已提交
149 150 151 152
            Err(err) => early_error(
                ErrorOutputType::default(),
                &format!("Failed to load argument file: {}", err),
            ),
153 154
        }
    }
M
Mark Rousskov 已提交
155 156
    let diagnostic_output =
        emitter.map(|emitter| DiagnosticOutput::Raw(emitter)).unwrap_or(DiagnosticOutput::Default);
157
    let matches = match handle_options(&args) {
158
        Some(matches) => matches,
159
        None => return Ok(()),
160
    };
J
John Kåre Alsaker 已提交
161

162
    let sopts = config::build_session_options(&matches);
163
    let cfg = interface::parse_cfgspecs(matches.opt_strs("cfg"));
N
Nick Cameron 已提交
164

165 166 167 168 169 170 171 172 173 174 175 176 177
    let mut dummy_config = |sopts, cfg, diagnostic_output| {
        let mut config = interface::Config {
            opts: sopts,
            crate_cfg: cfg,
            input: Input::File(PathBuf::new()),
            input_path: None,
            output_file: None,
            output_dir: None,
            file_loader: None,
            diagnostic_output,
            stderr: None,
            crate_name: None,
            lint_caps: Default::default(),
178
            register_lints: None,
179
            override_queries: None,
180
            registry: diagnostics_registry(),
181 182 183 184
        };
        callbacks.config(&mut config);
        config
    };
185

186
    if let Some(ref code) = matches.opt_str("explain") {
187
        handle_explain(diagnostics_registry(), code, sopts.error_format);
188 189
        return Ok(());
    }
190 191

    let (odir, ofile) = make_output(&matches);
192
    let (input, input_file_path, input_err) = match make_input(&matches.free) {
193
        Some(v) => v,
M
Mark Rousskov 已提交
194 195 196 197 198 199 200 201 202
        None => match matches.free.len() {
            0 => {
                let config = dummy_config(sopts, cfg, diagnostic_output);
                interface::run_compiler(config, |compiler| {
                    let sopts = &compiler.session().opts;
                    if sopts.describe_lints {
                        let lint_store = rustc_lint::new_lint_store(
                            sopts.debugging_opts.no_interleave_lints,
                            compiler.session().unstable_options(),
203
                        );
M
Mark Rousskov 已提交
204 205 206 207 208 209 210 211 212 213
                        describe_lints(compiler.session(), &lint_store, false);
                        return;
                    }
                    let should_stop = RustcDefaultCalls::print_crate_info(
                        &***compiler.codegen_backend(),
                        compiler.session(),
                        None,
                        &odir,
                        &ofile,
                    );
N
Nick Cameron 已提交
214

M
Mark Rousskov 已提交
215 216 217 218 219 220
                    if should_stop == Compilation::Stop {
                        return;
                    }
                    early_error(sopts.error_format, "no input filename given")
                });
                return Ok(());
221
            }
M
Mark Rousskov 已提交
222 223 224 225 226 227 228 229 230
            1 => panic!("make_input should have provided valid inputs"),
            _ => early_error(
                sopts.error_format,
                &format!(
                    "multiple input filenames provided (first two filenames are `{}` and `{}`)",
                    matches.free[0], matches.free[1],
                ),
            ),
        },
231
    };
232

233 234 235
    if let Some(err) = input_err {
        // Immediately stop compilation if there was an issue reading
        // the input (for example if the input stream is not UTF-8).
236 237 238 239
        interface::run_compiler(dummy_config(sopts, cfg, diagnostic_output), |compiler| {
            compiler.session().err(&err.to_string());
        });
        return Err(ErrorReported);
240 241
    }

242 243 244 245 246 247 248 249 250 251 252 253
    let mut config = interface::Config {
        opts: sopts,
        crate_cfg: cfg,
        input,
        input_path: input_file_path,
        output_file: ofile,
        output_dir: odir,
        file_loader,
        diagnostic_output,
        stderr: None,
        crate_name: None,
        lint_caps: Default::default(),
254
        register_lints: None,
255
        override_queries: None,
256
        registry: diagnostics_registry(),
257 258 259 260 261 262 263 264 265 266 267 268
    };

    callbacks.config(&mut config);

    interface::run_compiler(config, |compiler| {
        let sess = compiler.session();
        let should_stop = RustcDefaultCalls::print_crate_info(
            &***compiler.codegen_backend(),
            sess,
            Some(compiler.input()),
            compiler.output_dir(),
            compiler.output_file(),
M
Mark Rousskov 已提交
269 270 271 272 273 274 275 276
        )
        .and_then(|| {
            RustcDefaultCalls::list_metadata(
                sess,
                &*compiler.codegen_backend().metadata_loader(),
                &matches,
                compiler.input(),
            )
V
Victor Ding 已提交
277 278
        })
        .and_then(|| RustcDefaultCalls::try_process_rlink(sess, compiler));
279 280 281 282 283

        if should_stop == Compilation::Stop {
            return sess.compile_status();
        }

284
        let linker = compiler.enter(|queries| {
C
Camille GILLOT 已提交
285
            let early_exit = || sess.compile_status().map(|_| None);
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
            queries.parse()?;

            if let Some(ppm) = &sess.opts.pretty {
                if ppm.needs_ast_map() {
                    queries.global_ctxt()?.peek_mut().enter(|tcx| {
                        let expanded_crate = queries.expansion()?.take().0;
                        pretty::print_after_hir_lowering(
                            tcx,
                            compiler.input(),
                            &expanded_crate,
                            *ppm,
                            compiler.output_file().as_ref().map(|p| &**p),
                        );
                        Ok(())
                    })?;
                } else {
                    let krate = queries.parse()?.take();
                    pretty::print_after_parsing(
                        sess,
                        &compiler.input(),
                        &krate,
307
                        *ppm,
308 309
                        compiler.output_file().as_ref().map(|p| &**p),
                    );
310
                }
J
Joshua Nelson 已提交
311
                trace!("finished pretty-printing");
C
Camille GILLOT 已提交
312
                return early_exit();
313
            }
314

R
Ralf Jung 已提交
315
            if callbacks.after_parsing(compiler, queries) == Compilation::Stop {
C
Camille GILLOT 已提交
316
                return early_exit();
317
            }
N
Nick Cameron 已提交
318

M
Mark Rousskov 已提交
319 320 321 322 323
            if sess.opts.debugging_opts.parse_only
                || sess.opts.debugging_opts.show_span.is_some()
                || sess.opts.debugging_opts.ast_json_noexpand
            {
                return early_exit();
324
            }
325

326 327
            {
                let (_, lint_store) = &*queries.register_plugins()?.peek();
328

329 330 331
                // Lint plugins are registered; now we can process command line flags.
                if sess.opts.describe_lints {
                    describe_lints(&sess, &lint_store, true);
C
Camille GILLOT 已提交
332
                    return early_exit();
333 334 335 336
                }
            }

            queries.expansion()?;
R
Ralf Jung 已提交
337
            if callbacks.after_expansion(compiler, queries) == Compilation::Stop {
C
Camille GILLOT 已提交
338
                return early_exit();
339
            }
340

341 342 343 344 345
            queries.prepare_outputs()?;

            if sess.opts.output_types.contains_key(&OutputType::DepInfo)
                && sess.opts.output_types.len() == 1
            {
C
Camille GILLOT 已提交
346
                return early_exit();
347
            }
348

349
            queries.global_ctxt()?;
350

351
            // Drop AST after creating GlobalCtxt to free memory
352 353 354 355
            {
                let _timer = sess.prof.generic_activity("drop_ast");
                mem::drop(queries.expansion()?.take());
            }
356

M
Mark Rousskov 已提交
357 358
            if sess.opts.debugging_opts.no_analysis || sess.opts.debugging_opts.ast_json {
                return early_exit();
359
            }
360

361 362 363 364 365
            if sess.opts.debugging_opts.save_analysis {
                let crate_name = queries.crate_name()?.peek().clone();
                queries.global_ctxt()?.peek_mut().enter(|tcx| {
                    let result = tcx.analysis(LOCAL_CRATE);

366
                    sess.time("save_analysis", || {
367 368 369 370 371
                        save::process_crate(
                            tcx,
                            &crate_name,
                            &compiler.input(),
                            None,
C
Tidy.  
Camille GILLOT 已提交
372
                            DumpHandler::new(
M
Mark Rousskov 已提交
373 374 375
                                compiler.output_dir().as_ref().map(|p| &**p),
                                &crate_name,
                            ),
376 377
                        )
                    });
378

379 380 381
                    result
                })?;
            }
382

383
            queries.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
384

R
Ralf Jung 已提交
385
            if callbacks.after_analysis(compiler, queries) == Compilation::Stop {
C
Camille GILLOT 已提交
386
                return early_exit();
387
            }
388

389
            queries.ongoing_codegen()?;
390

391 392 393
            if sess.opts.debugging_opts.print_type_sizes {
                sess.code_stats.print_type_sizes();
            }
394

395 396
            let linker = queries.linker()?;
            Ok(Some(linker))
397
        })?;
398

399
        if let Some(linker) = linker {
J
John Kåre Alsaker 已提交
400
            let _timer = sess.timer("link");
401 402 403
            linker.link()?
        }

404 405 406 407 408
        if sess.opts.debugging_opts.perf_stats {
            sess.print_perf_stats();
        }

        if sess.print_fuel_crate.is_some() {
M
Mark Rousskov 已提交
409 410
            eprintln!(
                "Fuel used by {}: {}",
411
                sess.print_fuel_crate.as_ref().unwrap(),
M
Mark Rousskov 已提交
412 413
                sess.print_fuel.load(SeqCst)
            );
414
        }
415

416 417
        Ok(())
    })
418 419
}

420 421 422 423 424
#[cfg(unix)]
pub fn set_sigpipe_handler() {
    unsafe {
        // Set the SIGPIPE signal handler, so that an EPIPE
        // will cause rustc to terminate, as expected.
L
ljedrz 已提交
425
        assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
426 427 428 429 430 431
    }
}

#[cfg(windows)]
pub fn set_sigpipe_handler() {}

432
// Extract output directory and file from matches.
A
Alex Crichton 已提交
433
fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
A
Aaron Turon 已提交
434 435
    let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
    let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
436 437
    (odir, ofile)
}
438

439
// Extract input (string or file and optional path) from matches.
440
fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
441
    if free_matches.len() == 1 {
442
        let ifile = &free_matches[0];
443
        if ifile == "-" {
444
            let mut src = String::new();
445
            let err = if io::stdin().read_to_string(&mut src).is_err() {
M
Mark Rousskov 已提交
446 447 448 449
                Some(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "couldn't read from stdin, as it did not contain valid UTF-8",
                ))
450 451 452
            } else {
                None
            };
453
            if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
M
Mark Rousskov 已提交
454 455 456 457 458 459
                let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
                    "when UNSTABLE_RUSTDOC_TEST_PATH is set \
                                    UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
                );
                let line = isize::from_str_radix(&line, 10)
                    .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
460 461 462
                let file_name = FileName::doc_test_source_code(PathBuf::from(path), line);
                return Some((Input::Str { name: file_name, input: src }, None, err));
            }
M
Mark Rousskov 已提交
463
            Some((Input::Str { name: FileName::anon_source_code(&src), input: src }, None, err))
464
        } else {
M
Mark Rousskov 已提交
465
            Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)), None))
466 467 468
        }
    } else {
        None
469
    }
470
}
471

N
Nick Cameron 已提交
472
// Whether to stop or continue compilation.
N
Niko Matsakis 已提交
473
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
N
Nick Cameron 已提交
474 475 476 477 478 479 480 481 482
pub enum Compilation {
    Stop,
    Continue,
}

impl Compilation {
    pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
        match self {
            Compilation::Stop => Compilation::Stop,
J
Jose Narvaez 已提交
483
            Compilation::Continue => next(),
N
Nick Cameron 已提交
484 485 486 487
        }
    }
}

488
/// CompilerCalls instance for a regular rustc build.
N
Niko Matsakis 已提交
489
#[derive(Copy, Clone)]
490 491
pub struct RustcDefaultCalls;

C
Cengiz Can 已提交
492 493
// FIXME remove these and use winapi 0.3 instead
// Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
494 495 496 497
#[cfg(unix)]
fn stdout_isatty() -> bool {
    unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
}
C
Cengiz Can 已提交
498

499 500
#[cfg(windows)]
fn stdout_isatty() -> bool {
501 502 503 504
    use winapi::um::consoleapi::GetConsoleMode;
    use winapi::um::processenv::GetStdHandle;
    use winapi::um::winbase::STD_OUTPUT_HANDLE;

505 506 507 508 509 510 511
    unsafe {
        let handle = GetStdHandle(STD_OUTPUT_HANDLE);
        let mut out = 0;
        GetConsoleMode(handle, &mut out) != 0
    }
}

512
fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
M
Mark Rousskov 已提交
513
    let normalised =
514
        if code.starts_with('E') { code.to_string() } else { format!("E{0:0>4}", code) };
515 516
    match registry.try_find_description(&normalised) {
        Ok(Some(description)) => {
517
            let mut is_in_code_block = false;
518
            let mut text = String::new();
519
            // Slice off the leading newline and print.
520
            for line in description.lines() {
M
Mark Rousskov 已提交
521 522
                let indent_level =
                    line.find(|c: char| !c.is_whitespace()).unwrap_or_else(|| line.len());
523 524 525
                let dedented_line = &line[indent_level..];
                if dedented_line.starts_with("```") {
                    is_in_code_block = !is_in_code_block;
526
                    text.push_str(&line[..(indent_level + 3)]);
527 528
                } else if is_in_code_block && dedented_line.starts_with("# ") {
                    continue;
529
                } else {
530
                    text.push_str(line);
531
                }
532
                text.push('\n');
533
            }
C
Cengiz Can 已提交
534 535 536 537 538
            if stdout_isatty() {
                show_content_with_pager(&text);
            } else {
                print!("{}", text);
            }
539
        }
540
        Ok(None) => {
541 542
            early_error(output, &format!("no extended information for {}", code));
        }
543 544 545
        Err(InvalidErrorCode) => {
            early_error(output, &format!("{} is not a valid error code", code));
        }
546 547 548
    }
}

549
fn show_content_with_pager(content: &String) {
M
Mark Rousskov 已提交
550 551
    let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
        if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
552 553 554 555 556 557
    });

    let mut fallback_to_println = false;

    match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
        Ok(mut pager) => {
558
            if let Some(pipe) = pager.stdin.as_mut() {
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
                if pipe.write_all(content.as_bytes()).is_err() {
                    fallback_to_println = true;
                }
            }

            if pager.wait().is_err() {
                fallback_to_println = true;
            }
        }
        Err(_) => {
            fallback_to_println = true;
        }
    }

    // If pager fails for whatever reason, we should still print the content
    // to standard output
    if fallback_to_println {
C
Cengiz Can 已提交
576
        print!("{}", content);
577 578 579
    }
}

580
impl RustcDefaultCalls {
V
Victor Ding 已提交
581 582 583 584
    fn process_rlink(sess: &Session, compiler: &interface::Compiler) -> Result<(), ErrorReported> {
        if let Input::File(file) = compiler.input() {
            // FIXME: #![crate_type] and #![crate_name] support not implemented yet
            let attrs = vec![];
585
            sess.init_crate_types(collect_crate_types(sess, &attrs));
V
Victor Ding 已提交
586 587 588 589 590 591 592 593 594
            let outputs = compiler.build_output_filenames(&sess, &attrs);
            let rlink_data = fs::read_to_string(file).unwrap_or_else(|err| {
                sess.fatal(&format!("failed to read rlink file: {}", err));
            });
            let codegen_results: CodegenResults = json::decode(&rlink_data).unwrap_or_else(|err| {
                sess.fatal(&format!("failed to decode rlink: {}", err));
            });
            compiler.codegen_backend().link(&sess, Box::new(codegen_results), &outputs)
        } else {
595
            sess.fatal("rlink must be a file")
V
Victor Ding 已提交
596 597 598 599 600 601 602 603 604 605 606 607 608
        }
    }

    pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation {
        if sess.opts.debugging_opts.link_only {
            let result = RustcDefaultCalls::process_rlink(sess, compiler);
            abort_on_err(result, sess);
            Compilation::Stop
        } else {
            Compilation::Continue
        }
    }

M
Mark Rousskov 已提交
609 610 611 612 613 614
    pub fn list_metadata(
        sess: &Session,
        metadata_loader: &dyn MetadataLoader,
        matches: &getopts::Matches,
        input: &Input,
    ) -> Compilation {
615
        let r = matches.opt_strs("Z");
L
ljedrz 已提交
616
        if r.iter().any(|s| *s == "ls") {
M
Matthias Krüger 已提交
617 618
            match *input {
                Input::File(ref ifile) => {
619
                    let path = &(*ifile);
A
Alex Crichton 已提交
620
                    let mut v = Vec::new();
M
Mark Rousskov 已提交
621 622
                    locator::list_file_metadata(&sess.target.target, path, metadata_loader, &mut v)
                        .unwrap();
A
Alex Crichton 已提交
623
                    println!("{}", String::from_utf8(v).unwrap());
624
                }
M
Matthias Krüger 已提交
625
                Input::Str { .. } => {
626
                    early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
627 628
                }
            }
N
Nick Cameron 已提交
629
            return Compilation::Stop;
630 631
        }

632
        Compilation::Continue
633 634
    }

M
Mark Rousskov 已提交
635 636 637 638 639 640 641
    fn print_crate_info(
        codegen_backend: &dyn CodegenBackend,
        sess: &Session,
        input: Option<&Input>,
        odir: &Option<PathBuf>,
        ofile: &Option<PathBuf>,
    ) -> Compilation {
642
        use rustc_session::config::PrintRequest::*;
K
Kornel 已提交
643 644
        // PrintRequest::NativeStaticLibs is special - printed during linking
        // (empty iterator returns true)
645
        if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
N
Nick Cameron 已提交
646
            return Compilation::Continue;
647 648
        }

J
Jonas Schievink 已提交
649 650 651 652 653 654 655 656 657 658 659 660 661
        let attrs = match input {
            None => None,
            Some(input) => {
                let result = parse_crate_attrs(sess, input);
                match result {
                    Ok(attrs) => Some(attrs),
                    Err(mut parse_error) => {
                        parse_error.emit();
                        return Compilation::Stop;
                    }
                }
            }
        };
662 663
        for req in &sess.opts.prints {
            match *req {
664
                TargetList => {
665
                    let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
666 667
                    targets.sort();
                    println!("{}", targets.join("\n"));
M
Mark Rousskov 已提交
668
                }
N
Nicholas Nethercote 已提交
669
                Sysroot => println!("{}", sess.sysroot.display()),
670 671 672 673
                TargetLibdir => println!(
                    "{}",
                    sess.target_tlib_path.as_ref().unwrap_or(&sess.host_tlib_path).dir.display()
                ),
674 675
                TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
                FileNames | CrateName => {
M
Mark Rousskov 已提交
676 677 678
                    let input = input.unwrap_or_else(|| {
                        early_error(ErrorOutputType::default(), "no input file provided")
                    });
679
                    let attrs = attrs.as_ref().unwrap();
680
                    let t_outputs = rustc_interface::util::build_output_filenames(
M
Mark Rousskov 已提交
681
                        input, odir, ofile, attrs, sess,
682
                    );
683
                    let id = rustc_session::output::find_crate_name(sess, attrs, input);
684 685
                    if *req == PrintRequest::CrateName {
                        println!("{}", id);
J
Jose Narvaez 已提交
686
                        continue;
687
                    }
V
Victor Ding 已提交
688
                    let crate_types = collect_crate_types(sess, attrs);
689
                    for &style in &crate_types {
690 691
                        let fname =
                            rustc_session::output::filename_for_input(sess, style, &id, &t_outputs);
692
                        println!("{}", fname.file_name().unwrap().to_string_lossy());
693 694
                    }
                }
695
                Cfg => {
M
Mark Rousskov 已提交
696 697 698 699 700 701 702
                    let allow_unstable_cfg =
                        UnstableFeatures::from_environment().is_nightly_build();

                    let mut cfgs = sess
                        .parse_sess
                        .config
                        .iter()
703
                        .filter_map(|&(name, value)| {
M
Mark Rousskov 已提交
704 705 706 707 708 709 710 711
                            // Note that crt-static is a specially recognized cfg
                            // directive that's printed out here as part of
                            // rust-lang/rust#37406, but in general the
                            // `target_feature` cfg is gated under
                            // rust-lang/rust#29717. For now this is just
                            // specifically allowing the crt-static cfg and that's
                            // it, this is intended to get into Cargo and then go
                            // through to build scripts.
712
                            if (name != sym::target_feature || value != Some(sym::crt_dash_static))
M
Mark Rousskov 已提交
713 714 715 716 717 718 719 720 721 722 723 724 725
                                && !allow_unstable_cfg
                                && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
                            {
                                return None;
                            }

                            if let Some(value) = value {
                                Some(format!("{}=\"{}\"", name, value))
                            } else {
                                Some(name.to_string())
                            }
                        })
                        .collect::<Vec<String>>();
J
Jeffrey Seyfried 已提交
726 727 728 729

                    cfgs.sort();
                    for cfg in cfgs {
                        println!("{}", cfg);
730 731
                    }
                }
732
                RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
I
Irina Popa 已提交
733
                    codegen_backend.print(*req, sess);
734
                }
735 736
                // Any output here interferes with Cargo's parsing of other printed output
                PrintRequest::NativeStaticLibs => {}
737 738
            }
        }
739
        Compilation::Stop
B
Brian Anderson 已提交
740 741 742
    }
}

743
/// Returns a version string such as "0.12.0-dev".
744
fn release_str() -> Option<&'static str> {
745 746 747 748
    option_env!("CFG_RELEASE")
}

/// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
749
fn commit_hash_str() -> Option<&'static str> {
750 751 752 753
    option_env!("CFG_VER_HASH")
}

/// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
754
fn commit_date_str() -> Option<&'static str> {
755 756 757
    option_env!("CFG_VER_DATE")
}

758
/// Prints version information
759 760
pub fn version(binary: &str, matches: &getopts::Matches) {
    let verbose = matches.opt_present("verbose");
761

762 763
    println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));

764
    if verbose {
J
Jose Narvaez 已提交
765 766 767
        fn unw(x: Option<&str>) -> &str {
            x.unwrap_or("unknown")
        }
768
        println!("binary: {}", binary);
769 770
        println!("commit-hash: {}", unw(commit_hash_str()));
        println!("commit-date: {}", unw(commit_date_str()));
771
        println!("host: {}", config::host_triple());
772
        println!("release: {}", unw(release_str()));
773
        get_builtin_codegen_backend("llvm")().print_version();
774
    }
N
Nick Cameron 已提交
775 776
}

777
fn usage(verbose: bool, include_unstable_options: bool) {
M
Mark Rousskov 已提交
778
    let groups = if verbose { config::rustc_optgroups() } else { config::rustc_short_optgroups() };
779 780 781 782
    let mut options = getopts::Options::new();
    for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
        (option.apply)(&mut options);
    }
L
ljedrz 已提交
783
    let message = "Usage: rustc [OPTIONS] INPUT";
784
    let nightly_help = if nightly_options::is_nightly_build() {
785
        "\n    -Z help             Print unstable compiler options"
786 787 788 789
    } else {
        ""
    };
    let verbose_help = if verbose {
790 791 792 793
        ""
    } else {
        "\n    --help -v           Print the full set of options rustc accepts"
    };
794 795 796 797 798
    let at_path = if verbose && nightly_options::is_nightly_build() {
        "    @path               Read newline separated options from `path`\n"
    } else {
        ""
    };
M
Mark Rousskov 已提交
799 800
    println!(
        "{options}{at_path}\nAdditional help:
N
Nick Cameron 已提交
801
    -C help             Print codegen options
J
Jose Narvaez 已提交
802
    -W help             \
803
              Print 'lint' options and default settings{nightly}{verbose}\n",
M
Mark Rousskov 已提交
804 805 806 807 808
        options = options.usage(message),
        at_path = at_path,
        nightly = nightly_help,
        verbose = verbose_help
    );
N
Nick Cameron 已提交
809 810
}

P
Phlosioneer 已提交
811
fn print_wall_help() {
M
Mark Rousskov 已提交
812 813
    println!(
        "
814 815 816
The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
default. Use `rustc -W help` to see all available lints. It's more common to put
warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
P
Phlosioneer 已提交
817
the command line flag directly.
M
Mark Rousskov 已提交
818 819
"
    );
P
Phlosioneer 已提交
820 821
}

822
fn describe_lints(sess: &Session, lint_store: &LintStore, loaded_plugins: bool) {
M
Mark Rousskov 已提交
823 824
    println!(
        "
N
Nick Cameron 已提交
825 826
Available lint options:
    -W <foo>           Warn about <foo>
J
Jose Narvaez 已提交
827 828
    -A <foo>           \
              Allow <foo>
N
Nick Cameron 已提交
829
    -D <foo>           Deny <foo>
J
Jose Narvaez 已提交
830
    -F <foo>           Forbid <foo> \
831
              (deny <foo> and all attempts to override)
832

M
Mark Rousskov 已提交
833 834
"
    );
N
Nick Cameron 已提交
835

836
    fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
V
varkor 已提交
837
        // The sort doesn't case-fold but it's doubtful we care.
838
        lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
839 840 841
        lints
    }

M
Mark Rousskov 已提交
842
    fn sort_lint_groups(
843 844
        lints: Vec<(&'static str, Vec<LintId>, bool)>,
    ) -> Vec<(&'static str, Vec<LintId>)> {
845
        let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
S
Shotaro Yamada 已提交
846
        lints.sort_by_key(|l| l.0);
847 848 849
        lints
    }

M
Mark Rousskov 已提交
850 851
    let (plugin, builtin): (Vec<_>, _) =
        lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_plugin);
852 853
    let plugin = sort_lints(sess, plugin);
    let builtin = sort_lints(sess, builtin);
854

M
Mark Rousskov 已提交
855 856
    let (plugin_groups, builtin_groups): (Vec<_>, _) =
        lint_store.get_lint_groups().iter().cloned().partition(|&(.., p)| p);
857 858 859
    let plugin_groups = sort_lint_groups(plugin_groups);
    let builtin_groups = sort_lint_groups(builtin_groups);

M
Mark Rousskov 已提交
860 861
    let max_name_len =
        plugin.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
862
    let padded = |x: &str| {
S
Shotaro Yamada 已提交
863
        let mut s = " ".repeat(max_name_len - x.chars().count());
864 865
        s.push_str(x);
        s
866
    };
N
Nick Cameron 已提交
867

868
    println!("Lint checks provided by rustc:\n");
A
Alex Crichton 已提交
869 870
    println!("    {}  {:7.7}  {}", padded("name"), "default", "meaning");
    println!("    {}  {:7.7}  {}", padded("----"), "-------", "-------");
871

872
    let print_lints = |lints: Vec<&Lint>| {
873
        for lint in lints {
874
            let name = lint.name_lower().replace("_", "-");
M
Mark Rousskov 已提交
875
            println!("    {}  {:7.7}  {}", padded(&name), lint.default_level.as_str(), lint.desc);
876 877 878 879 880 881
        }
        println!("\n");
    };

    print_lints(builtin);

M
Mark Rousskov 已提交
882 883 884 885 886 887 888 889 890
    let max_name_len = max(
        "warnings".len(),
        plugin_groups
            .iter()
            .chain(&builtin_groups)
            .map(|&(s, _)| s.chars().count())
            .max()
            .unwrap_or(0),
    );
891

892
    let padded = |x: &str| {
S
Shotaro Yamada 已提交
893
        let mut s = " ".repeat(max_name_len - x.chars().count());
894 895
        s.push_str(x);
        s
896 897 898 899 900
    };

    println!("Lint groups provided by rustc:\n");
    println!("    {}  {}", padded("name"), "sub-lints");
    println!("    {}  {}", padded("----"), "---------");
901
    println!("    {}  {}", padded("warnings"), "all lints that are set to issue warnings");
902

903
    let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>| {
904
        for (name, to) in lints {
905
            let name = name.to_lowercase().replace("_", "-");
M
Mark Rousskov 已提交
906 907 908 909 910
            let desc = to
                .into_iter()
                .map(|x| x.to_string().replace("_", "-"))
                .collect::<Vec<String>>()
                .join(", ");
911
            println!("    {}  {}", padded(&name), desc);
K
Keegan McAllister 已提交
912
        }
913 914 915 916 917 918 919
        println!("\n");
    };

    print_lint_groups(builtin_groups);

    match (loaded_plugins, plugin.len(), plugin_groups.len()) {
        (false, 0, _) | (false, _, 0) => {
M
Mark Rousskov 已提交
920 921 922 923
            println!(
                "Compiler plugins can provide additional lints and lint groups. To see a \
                      listing of these, re-run `rustc -W help` with a crate filename."
            );
924
        }
V
Vadim Petrochenkov 已提交
925
        (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
926 927 928 929 930 931 932 933 934 935
        (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
        (true, l, g) => {
            if l > 0 {
                println!("Lint checks provided by plugins loaded by this crate:\n");
                print_lints(plugin);
            }
            if g > 0 {
                println!("Lint groups provided by plugins loaded by this crate:\n");
                print_lint_groups(plugin_groups);
            }
K
Keegan McAllister 已提交
936 937
        }
    }
N
Nick Cameron 已提交
938 939 940
}

fn describe_debug_flags() {
941
    println!("\nAvailable options:\n");
942
    print_flag_list("-Z", config::DB_OPTIONS);
N
Nick Cameron 已提交
943 944 945 946
}

fn describe_codegen_flags() {
    println!("\nAvailable codegen options:\n");
947 948 949
    print_flag_list("-C", config::CG_OPTIONS);
}

M
Mark Rousskov 已提交
950 951
fn print_flag_list<T>(
    cmdline_opt: &str,
952
    flag_list: &[(&'static str, T, &'static str, &'static str)],
M
Mark Rousskov 已提交
953
) {
954
    let max_len = flag_list.iter().map(|&(name, _, _, _)| name.chars().count()).max().unwrap_or(0);
955

956
    for &(name, _, _, desc) in flag_list {
M
Mark Rousskov 已提交
957
        println!(
958
            "    {} {:>width$}=val -- {}",
M
Mark Rousskov 已提交
959 960 961
            cmdline_opt,
            name.replace("_", "-"),
            desc,
962
            width = max_len
M
Mark Rousskov 已提交
963
        );
N
Nick Cameron 已提交
964 965 966
    }
}

967
/// Process command line options. Emits messages as appropriate. If compilation
968
/// should continue, returns a getopts::Matches object parsed from args,
A
Alexander Regueiro 已提交
969
/// otherwise returns `None`.
970
///
K
king6cong 已提交
971
/// The compiler's handling of options is a little complicated as it ties into
972 973
/// our stability story. The current intention of each compiler option is to
/// have one of two modes:
974 975
///
/// 1. An option is stable and can be used everywhere.
976
/// 2. An option is unstable, and can only be used on nightly.
977 978 979 980 981 982 983 984 985 986 987 988 989
///
/// Like unstable library and language features, however, unstable options have
/// always required a form of "opt in" to indicate that you're using them. This
/// provides the easy ability to scan a code base to check to see if anything
/// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
///
/// All options behind `-Z` are considered unstable by default. Other top-level
/// options can also be considered unstable, and they were unlocked through the
/// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
/// instability in both cases, though.
///
/// So with all that in mind, the comments below have some more detail about the
/// contortions done here to get things to work out correctly.
990
pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
991
    // Throw away the first argument, the name of the binary
992
    let args = &args[1..];
N
Nick Cameron 已提交
993

994
    if args.is_empty() {
995 996 997
        // user did not write `-v` nor `-Z unstable-options`, so do not
        // include that extra information.
        usage(false, false);
998 999
        return None;
    }
N
Nick Cameron 已提交
1000

1001 1002
    // Parse with *all* options defined in the compiler, we don't worry about
    // option stability here we just want to parse as much as possible.
1003 1004 1005 1006
    let mut options = getopts::Options::new();
    for option in config::rustc_optgroups() {
        (option.apply)(&mut options);
    }
M
Mark Rousskov 已提交
1007 1008 1009
    let matches = options
        .parse(args)
        .unwrap_or_else(|f| early_error(ErrorOutputType::default(), &f.to_string()));
1010

1011 1012 1013 1014 1015 1016 1017 1018 1019
    // For all options we just parsed, we check a few aspects:
    //
    // * If the option is stable, we're all good
    // * If the option wasn't passed, we're all good
    // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
    //   ourselves), then we require the `-Z unstable-options` flag to unlock
    //   this option that was passed.
    // * If we're a nightly compiler, then unstable options are now unlocked, so
    //   we're good to go.
1020
    // * Otherwise, if we're an unstable option then we generate an error
1021
    //   (unstable option being used on stable)
1022
    nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1023

N
Nick Cameron 已提交
1024
    if matches.opt_present("h") || matches.opt_present("help") {
1025 1026
        // Only show unstable options in --help if we accept unstable options.
        usage(matches.opt_present("verbose"), nightly_options::is_unstable_enabled(&matches));
N
Nick Cameron 已提交
1027 1028 1029
        return None;
    }

P
Phlosioneer 已提交
1030 1031 1032 1033 1034 1035
    // Handle the special case of -Wall.
    let wall = matches.opt_strs("W");
    if wall.iter().any(|x| *x == "all") {
        print_wall_help();
        return None;
    }
N
Nick Cameron 已提交
1036

1037
    // Don't handle -W help here, because we might first load plugins.
N
Nick Cameron 已提交
1038
    let r = matches.opt_strs("Z");
1039
    if r.iter().any(|x| *x == "help") {
N
Nick Cameron 已提交
1040 1041 1042 1043 1044
        describe_debug_flags();
        return None;
    }

    let cg_flags = matches.opt_strs("C");
1045

1046
    if cg_flags.iter().any(|x| *x == "help") {
N
Nick Cameron 已提交
1047 1048 1049 1050
        describe_codegen_flags();
        return None;
    }

1051
    if cg_flags.iter().any(|x| *x == "no-stack-check") {
M
Mark Rousskov 已提交
1052 1053 1054 1055
        early_warn(
            ErrorOutputType::default(),
            "the --no-stack-check flag is deprecated and does nothing",
        );
1056 1057
    }

L
ljedrz 已提交
1058
    if cg_flags.iter().any(|x| *x == "passes=list") {
1059
        get_builtin_codegen_backend("llvm")().print_passes();
N
Nick Cameron 已提交
1060 1061 1062
        return None;
    }

1063
    if matches.opt_present("version") {
1064 1065
        version("rustc", &matches);
        return None;
N
Nick Cameron 已提交
1066 1067 1068 1069 1070
    }

    Some(matches)
}

1071
fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1072
    match input {
M
Mark Rousskov 已提交
1073 1074 1075 1076 1077 1078
        Input::File(ifile) => rustc_parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess),
        Input::Str { name, input } => rustc_parse::parse_crate_attrs_from_source_str(
            name.clone(),
            input.clone(),
            &sess.parse_sess,
        ),
1079
    }
N
Nick Cameron 已提交
1080 1081
}

A
Alexander Regueiro 已提交
1082
/// Gets a list of extra command-line flags provided by the user, as strings.
1083 1084 1085 1086 1087
///
/// This function is used during ICEs to show more information useful for
/// debugging, since some ICEs only happens with non-default compiler flags
/// (and the users don't always report them).
fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1088
    let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1089

1090 1091 1092 1093 1094 1095
    // Avoid printing help because of empty args. This can suggest the compiler
    // itself is not the program root (consider RLS).
    if args.len() < 2 {
        return None;
    }

1096
    let matches = handle_options(&args)?;
1097 1098 1099 1100 1101 1102 1103
    let mut result = Vec::new();
    let mut excluded_cargo_defaults = false;
    for flag in ICE_REPORT_COMPILER_FLAGS {
        let prefix = if flag.len() == 1 { "-" } else { "--" };

        for content in &matches.opt_strs(flag) {
            // Split always returns the first element
M
Mark Rousskov 已提交
1104
            let name = if let Some(first) = content.split('=').next() { first } else { &content };
1105

M
Mark Rousskov 已提交
1106 1107
            let content =
                if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) { name } else { content };
1108 1109 1110 1111 1112 1113 1114 1115 1116

            if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
                result.push(format!("{}{} {}", prefix, flag, content));
            } else {
                excluded_cargo_defaults = true;
            }
        }
    }

M
Mark Rousskov 已提交
1117
    if !result.is_empty() { Some((result, excluded_cargo_defaults)) } else { None }
1118 1119
}

1120
/// Runs a closure and catches unwinds triggered by fatal errors.
N
Nick Cameron 已提交
1121
///
1122
/// The compiler currently unwinds with a special sentinel value to abort
1123 1124 1125
/// compilation on fatal errors. This function catches that sentinel and turns
/// the panic into a `Result` instead.
pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
1126
    catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1127
        if value.is::<rustc_errors::FatalErrorMarker>() {
1128
            ErrorReported
1129
        } else {
1130 1131 1132 1133
            panic::resume_unwind(value);
        }
    })
}
N
Nick Cameron 已提交
1134

1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
/// Variant of `catch_fatal_errors` for the `interface::Result` return type
/// that also computes the exit code.
pub fn catch_with_exit_code(f: impl FnOnce() -> interface::Result<()>) -> i32 {
    let result = catch_fatal_errors(f).and_then(|result| result);
    match result {
        Ok(()) => EXIT_SUCCESS,
        Err(_) => EXIT_FAILURE,
    }
}

1145 1146 1147
lazy_static! {
    static ref DEFAULT_HOOK: Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static> = {
        let hook = panic::take_hook();
1148
        panic::set_hook(Box::new(|info| report_ice(info, BUG_REPORT_URL)));
1149 1150 1151
        hook
    };
}
1152

1153 1154 1155 1156 1157 1158 1159
/// Prints the ICE message, including backtrace and query stack.
///
/// The message will point the user at `bug_report_url` to report the ICE.
///
/// When `install_ice_hook` is called, this function will be called as the panic
/// hook.
pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
1160
    // Invoke the default handler, which prints the actual panic message and optionally a backtrace
1161 1162
    (*DEFAULT_HOOK)(info);

J
Jonas Schievink 已提交
1163
    // Separate the output with an empty line
1164 1165
    eprintln!();

1166 1167
    let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
        rustc_errors::ColorConfig::Auto,
1168 1169 1170 1171
        None,
        false,
        false,
        None,
1172
        false,
1173
    ));
1174
    let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1175 1176 1177

    // a .span_bug or .bug call has already printed what
    // it wants to print.
1178 1179
    if !info.payload().is::<rustc_errors::ExplicitBug>() {
        let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
1180
        handler.emit_diagnostic(&d);
1181
    }
1182

1183 1184
    let mut xs: Vec<Cow<'static, str>> = vec![
        "the compiler unexpectedly panicked. this is a bug.".into(),
1185
        format!("we would appreciate a bug report: {}", bug_report_url).into(),
M
Mark Rousskov 已提交
1186 1187 1188 1189 1190 1191
        format!(
            "rustc {} running on {}",
            option_env!("CFG_VERSION").unwrap_or("unknown_version"),
            config::host_triple()
        )
        .into(),
1192
    ];
1193

1194 1195
    if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
        xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1196

1197 1198
        if excluded_cargo_defaults {
            xs.push("some of the compiler flags provided by cargo are hidden".into());
1199
        }
1200 1201 1202
    }

    for note in &xs {
1203
        handler.note_without_error(&note);
1204
    }
1205 1206 1207 1208 1209

    // If backtraces are enabled, also print the query stack
    let backtrace = env::var_os("RUST_BACKTRACE").map(|x| &x != "0").unwrap_or(false);

    if backtrace {
1210
        TyCtxt::try_print_query_stack(&handler);
1211 1212 1213 1214 1215 1216
    }

    #[cfg(windows)]
    unsafe {
        if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
            // Trigger a debugger if we crashed during bootstrap
1217
            winapi::um::debugapi::DebugBreak();
1218 1219
        }
    }
1220 1221
}

1222 1223 1224
/// Installs a panic hook that will print the ICE message on unexpected panics.
///
/// A custom rustc driver can skip calling this to set up a custom ICE hook.
1225 1226
pub fn install_ice_hook() {
    lazy_static::initialize(&DEFAULT_HOOK);
N
Nick Cameron 已提交
1227
}
1228

1229
/// This allows tools to enable rust logging without having to magically match rustc's
G
Gurpreet Singh 已提交
1230
/// tracing crate version.
1231
pub fn init_rustc_env_logger() {
1232 1233 1234 1235
    init_env_logger("RUSTC_LOG")
}

/// This allows tools to enable rust logging without having to magically match rustc's
G
Gurpreet Singh 已提交
1236
/// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to choose an env var
1237 1238
/// other than `RUSTC_LOG`.
pub fn init_env_logger(env: &str) {
1239 1240 1241 1242 1243 1244
    // Don't register a dispatcher if there's no filter to print anything
    match std::env::var(env) {
        Err(_) => return,
        Ok(s) if s.is_empty() => return,
        Ok(_) => {}
    }
O
Oliver Scherer 已提交
1245 1246
    let builder = tracing_subscriber::FmtSubscriber::builder();

1247
    let builder = builder.with_env_filter(tracing_subscriber::EnvFilter::from_env(env));
O
Oliver Scherer 已提交
1248 1249

    builder.init()
1250 1251
}

1252
pub fn main() -> ! {
1253
    let start = Instant::now();
1254
    init_rustc_env_logger();
1255
    let mut callbacks = TimePassesCallbacks::default();
1256
    install_ice_hook();
1257
    let exit_code = catch_with_exit_code(|| {
M
Mark Rousskov 已提交
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
        let args = env::args_os()
            .enumerate()
            .map(|(i, arg)| {
                arg.into_string().unwrap_or_else(|arg| {
                    early_error(
                        ErrorOutputType::default(),
                        &format!("Argument {} is not valid Unicode: {:?}", i, arg),
                    )
                })
            })
B
bjorn3 已提交
1268
            .collect::<Vec<_>>();
1269
        run_compiler(&args, &mut callbacks, None, None)
1270
    });
1271 1272
    // The extra `\t` is necessary to align this label with the others.
    print_time_passes_entry(callbacks.time_passes, "\ttotal", start.elapsed());
1273
    process::exit(exit_code)
1274
}