]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/mod.rs
Rollup merge of #48641 - alexcrichton:no-hash-l-paths, r=michaelwoerister
[rust.git] / src / librustc / session / mod.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 pub use self::code_stats::{CodeStats, DataTypeKind, FieldInfo};
12 pub use self::code_stats::{SizeKind, TypeSizeInfo, VariantInfo};
13
14 use hir::def_id::CrateNum;
15 use ich::Fingerprint;
16
17 use ich;
18 use lint;
19 use lint::builtin::BuiltinLintDiagnostics;
20 use middle::allocator::AllocatorKind;
21 use middle::dependency_format;
22 use session::search_paths::PathKind;
23 use session::config::{BorrowckMode, DebugInfoLevel, OutputType, Epoch};
24 use ty::tls;
25 use util::nodemap::{FxHashMap, FxHashSet};
26 use util::common::{duration_to_secs_str, ErrorReported};
27
28 use rustc_data_structures::sync::Lrc;
29
30 use syntax::ast::NodeId;
31 use errors::{self, DiagnosticBuilder, DiagnosticId};
32 use errors::emitter::{Emitter, EmitterWriter};
33 use syntax::json::JsonEmitter;
34 use syntax::feature_gate;
35 use syntax::symbol::Symbol;
36 use syntax::parse;
37 use syntax::parse::ParseSess;
38 use syntax::{ast, codemap};
39 use syntax::feature_gate::AttributeType;
40 use syntax_pos::{Span, MultiSpan};
41
42 use rustc_back::{LinkerFlavor, PanicStrategy};
43 use rustc_back::target::Target;
44 use rustc_data_structures::flock;
45 use jobserver::Client;
46
47 use std::cell::{self, Cell, RefCell};
48 use std::collections::HashMap;
49 use std::env;
50 use std::fmt;
51 use std::io::Write;
52 use std::path::{Path, PathBuf};
53 use std::sync::{Once, ONCE_INIT};
54 use std::time::Duration;
55
56 mod code_stats;
57 pub mod config;
58 pub mod filesearch;
59 pub mod search_paths;
60
61 /// Represents the data associated with a compilation
62 /// session for a single crate.
63 pub struct Session {
64     pub target: config::Config,
65     pub host: Target,
66     pub opts: config::Options,
67     pub parse_sess: ParseSess,
68     /// For a library crate, this is always none
69     pub entry_fn: RefCell<Option<(NodeId, Span)>>,
70     pub entry_type: Cell<Option<config::EntryFnType>>,
71     pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
72     pub derive_registrar_fn: Cell<Option<ast::NodeId>>,
73     pub default_sysroot: Option<PathBuf>,
74     /// The name of the root source file of the crate, in the local file system.
75     /// `None` means that there is no source file.
76     pub local_crate_source_file: Option<PathBuf>,
77     /// The directory the compiler has been executed in plus a flag indicating
78     /// if the value stored here has been affected by path remapping.
79     pub working_dir: (PathBuf, bool),
80     pub lint_store: RefCell<lint::LintStore>,
81     pub buffered_lints: RefCell<Option<lint::LintBuffer>>,
82     /// Set of (DiagnosticId, Option<Span>, message) tuples tracking
83     /// (sub)diagnostics that have been set once, but should not be set again,
84     /// in order to avoid redundantly verbose output (Issue #24690, #44953).
85     pub one_time_diagnostics: RefCell<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
86     pub plugin_llvm_passes: RefCell<Vec<String>>,
87     pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
88     pub crate_types: RefCell<Vec<config::CrateType>>,
89     pub dependency_formats: RefCell<dependency_format::Dependencies>,
90         /// The crate_disambiguator is constructed out of all the `-C metadata`
91     /// arguments passed to the compiler. Its value together with the crate-name
92     /// forms a unique global identifier for the crate. It is used to allow
93     /// multiple crates with the same name to coexist. See the
94     /// trans::back::symbol_names module for more information.
95     pub crate_disambiguator: RefCell<Option<CrateDisambiguator>>,
96     pub features: RefCell<feature_gate::Features>,
97
98     /// The maximum recursion limit for potentially infinitely recursive
99     /// operations such as auto-dereference and monomorphization.
100     pub recursion_limit: Cell<usize>,
101
102     /// The maximum length of types during monomorphization.
103     pub type_length_limit: Cell<usize>,
104
105     /// The metadata::creader module may inject an allocator/panic_runtime
106     /// dependency if it didn't already find one, and this tracks what was
107     /// injected.
108     pub injected_allocator: Cell<Option<CrateNum>>,
109     pub allocator_kind: Cell<Option<AllocatorKind>>,
110     pub injected_panic_runtime: Cell<Option<CrateNum>>,
111
112     /// Map from imported macro spans (which consist of
113     /// the localized span for the macro body) to the
114     /// macro name and definition span in the source crate.
115     pub imported_macro_spans: RefCell<HashMap<Span, (String, Span)>>,
116
117     incr_comp_session: RefCell<IncrCompSession>,
118
119     /// A cache of attributes ignored by StableHashingContext
120     pub ignored_attr_names: FxHashSet<Symbol>,
121
122     /// Some measurements that are being gathered during compilation.
123     pub perf_stats: PerfStats,
124
125     /// Data about code being compiled, gathered during compilation.
126     pub code_stats: RefCell<CodeStats>,
127
128     next_node_id: Cell<ast::NodeId>,
129
130     /// If -zfuel=crate=n is specified, Some(crate).
131     optimization_fuel_crate: Option<String>,
132     /// If -zfuel=crate=n is specified, initially set to n. Otherwise 0.
133     optimization_fuel_limit: Cell<u64>,
134     /// We're rejecting all further optimizations.
135     out_of_fuel: Cell<bool>,
136
137     // The next two are public because the driver needs to read them.
138
139     /// If -zprint-fuel=crate, Some(crate).
140     pub print_fuel_crate: Option<String>,
141     /// Always set to zero and incremented so that we can print fuel expended by a crate.
142     pub print_fuel: Cell<u64>,
143
144     /// Loaded up early on in the initialization of this `Session` to avoid
145     /// false positives about a job server in our environment.
146     pub jobserver_from_env: Option<Client>,
147
148     /// Metadata about the allocators for the current crate being compiled
149     pub has_global_allocator: Cell<bool>,
150 }
151
152 pub struct PerfStats {
153     /// The accumulated time needed for computing the SVH of the crate
154     pub svh_time: Cell<Duration>,
155     /// The accumulated time spent on computing incr. comp. hashes
156     pub incr_comp_hashes_time: Cell<Duration>,
157     /// The number of incr. comp. hash computations performed
158     pub incr_comp_hashes_count: Cell<u64>,
159     /// The number of bytes hashed when computing ICH values
160     pub incr_comp_bytes_hashed: Cell<u64>,
161     /// The accumulated time spent on computing symbol hashes
162     pub symbol_hash_time: Cell<Duration>,
163     /// The accumulated time spent decoding def path tables from metadata
164     pub decode_def_path_tables_time: Cell<Duration>,
165 }
166
167 /// Enum to support dispatch of one-time diagnostics (in Session.diag_once)
168 enum DiagnosticBuilderMethod {
169     Note,
170     SpanNote,
171     SpanSuggestion(String), // suggestion
172     // add more variants as needed to support one-time diagnostics
173 }
174
175 /// Diagnostic message ID—used by `Session.one_time_diagnostics` to avoid
176 /// emitting the same message more than once
177 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
178 pub enum DiagnosticMessageId {
179     ErrorId(u16), // EXXXX error code as integer
180     LintId(lint::LintId),
181     StabilityId(u32) // issue number
182 }
183
184 impl From<&'static lint::Lint> for DiagnosticMessageId {
185     fn from(lint: &'static lint::Lint) -> Self {
186         DiagnosticMessageId::LintId(lint::LintId::of(lint))
187     }
188 }
189
190 impl Session {
191     pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
192         match *self.crate_disambiguator.borrow() {
193             Some(value) => value,
194             None => bug!("accessing disambiguator before initialization"),
195         }
196     }
197     pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
198                                                     sp: S,
199                                                     msg: &str)
200                                                     -> DiagnosticBuilder<'a> {
201         self.diagnostic().struct_span_warn(sp, msg)
202     }
203     pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
204                                                               sp: S,
205                                                               msg: &str,
206                                                               code: DiagnosticId)
207                                                               -> DiagnosticBuilder<'a> {
208         self.diagnostic().struct_span_warn_with_code(sp, msg, code)
209     }
210     pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
211         self.diagnostic().struct_warn(msg)
212     }
213     pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
214                                                    sp: S,
215                                                    msg: &str)
216                                                    -> DiagnosticBuilder<'a> {
217         self.diagnostic().struct_span_err(sp, msg)
218     }
219     pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
220                                                              sp: S,
221                                                              msg: &str,
222                                                              code: DiagnosticId)
223                                                              -> DiagnosticBuilder<'a> {
224         self.diagnostic().struct_span_err_with_code(sp, msg, code)
225     }
226     // FIXME: This method should be removed (every error should have an associated error code).
227     pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
228         self.diagnostic().struct_err(msg)
229     }
230     pub fn struct_err_with_code<'a>(
231         &'a self,
232         msg: &str,
233         code: DiagnosticId,
234     ) -> DiagnosticBuilder<'a> {
235         self.diagnostic().struct_err_with_code(msg, code)
236     }
237     pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
238                                                      sp: S,
239                                                      msg: &str)
240                                                      -> DiagnosticBuilder<'a> {
241         self.diagnostic().struct_span_fatal(sp, msg)
242     }
243     pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
244                                                                sp: S,
245                                                                msg: &str,
246                                                                code: DiagnosticId)
247                                                                -> DiagnosticBuilder<'a> {
248         self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
249     }
250     pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a>  {
251         self.diagnostic().struct_fatal(msg)
252     }
253
254     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
255         self.diagnostic().span_fatal(sp, msg).raise()
256     }
257     pub fn span_fatal_with_code<S: Into<MultiSpan>>(
258         &self,
259         sp: S,
260         msg: &str,
261         code: DiagnosticId,
262     ) -> ! {
263         self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
264     }
265     pub fn fatal(&self, msg: &str) -> ! {
266         self.diagnostic().fatal(msg).raise()
267     }
268     pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
269         if is_warning {
270             self.span_warn(sp, msg);
271         } else {
272             self.span_err(sp, msg);
273         }
274     }
275     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
276         self.diagnostic().span_err(sp, msg)
277     }
278     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
279         self.diagnostic().span_err_with_code(sp, &msg, code)
280     }
281     pub fn err(&self, msg: &str) {
282         self.diagnostic().err(msg)
283     }
284     pub fn err_count(&self) -> usize {
285         self.diagnostic().err_count()
286     }
287     pub fn has_errors(&self) -> bool {
288         self.diagnostic().has_errors()
289     }
290     pub fn abort_if_errors(&self) {
291         self.diagnostic().abort_if_errors();
292     }
293     pub fn compile_status(&self) -> Result<(), CompileIncomplete> {
294         compile_result_from_err_count(self.err_count())
295     }
296     pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
297         where F: FnOnce() -> T
298     {
299         let old_count = self.err_count();
300         let result = f();
301         let errors = self.err_count() - old_count;
302         if errors == 0 {
303             Ok(result)
304         } else {
305             Err(ErrorReported)
306         }
307     }
308     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
309         self.diagnostic().span_warn(sp, msg)
310     }
311     pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
312         self.diagnostic().span_warn_with_code(sp, msg, code)
313     }
314     pub fn warn(&self, msg: &str) {
315         self.diagnostic().warn(msg)
316     }
317     pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
318         match opt_sp {
319             Some(sp) => self.span_warn(sp, msg),
320             None => self.warn(msg),
321         }
322     }
323     /// Delay a span_bug() call until abort_if_errors()
324     pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
325         self.diagnostic().delay_span_bug(sp, msg)
326     }
327     pub fn note_without_error(&self, msg: &str) {
328         self.diagnostic().note_without_error(msg)
329     }
330     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
331         self.diagnostic().span_note_without_error(sp, msg)
332     }
333     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
334         self.diagnostic().span_unimpl(sp, msg)
335     }
336     pub fn unimpl(&self, msg: &str) -> ! {
337         self.diagnostic().unimpl(msg)
338     }
339
340     pub fn buffer_lint<S: Into<MultiSpan>>(&self,
341                                            lint: &'static lint::Lint,
342                                            id: ast::NodeId,
343                                            sp: S,
344                                            msg: &str) {
345         match *self.buffered_lints.borrow_mut() {
346             Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(),
347                                                     msg, BuiltinLintDiagnostics::Normal),
348             None => bug!("can't buffer lints after HIR lowering"),
349         }
350     }
351
352     pub fn buffer_lint_with_diagnostic<S: Into<MultiSpan>>(&self,
353         lint: &'static lint::Lint, id: ast::NodeId, sp: S,
354         msg: &str, diagnostic: BuiltinLintDiagnostics) {
355         match *self.buffered_lints.borrow_mut() {
356             Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(),
357                                                     msg, diagnostic),
358             None => bug!("can't buffer lints after HIR lowering"),
359         }
360     }
361
362     pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
363         let id = self.next_node_id.get();
364
365         match id.as_usize().checked_add(count) {
366             Some(next) => {
367                 self.next_node_id.set(ast::NodeId::new(next));
368             }
369             None => bug!("Input too large, ran out of node ids!")
370         }
371
372         id
373     }
374     pub fn next_node_id(&self) -> NodeId {
375         self.reserve_node_ids(1)
376     }
377     pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
378         &self.parse_sess.span_diagnostic
379     }
380
381     /// Analogous to calling methods on the given `DiagnosticBuilder`, but
382     /// deduplicates on lint ID, span (if any), and message for this `Session`
383     fn diag_once<'a, 'b>(&'a self,
384                          diag_builder: &'b mut DiagnosticBuilder<'a>,
385                          method: DiagnosticBuilderMethod,
386                          msg_id: DiagnosticMessageId,
387                          message: &str,
388                          span_maybe: Option<Span>) {
389
390         let id_span_message = (msg_id, span_maybe, message.to_owned());
391         let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
392         if fresh {
393             match method {
394                 DiagnosticBuilderMethod::Note => {
395                     diag_builder.note(message);
396                 },
397                 DiagnosticBuilderMethod::SpanNote => {
398                     let span = span_maybe.expect("span_note needs a span");
399                     diag_builder.span_note(span, message);
400                 },
401                 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
402                     let span = span_maybe.expect("span_suggestion needs a span");
403                     diag_builder.span_suggestion(span, message, suggestion);
404                 }
405             }
406         }
407     }
408
409     pub fn diag_span_note_once<'a, 'b>(&'a self,
410                                        diag_builder: &'b mut DiagnosticBuilder<'a>,
411                                        msg_id: DiagnosticMessageId, span: Span, message: &str) {
412         self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanNote,
413                        msg_id, message, Some(span));
414     }
415
416     pub fn diag_note_once<'a, 'b>(&'a self,
417                                   diag_builder: &'b mut DiagnosticBuilder<'a>,
418                                   msg_id: DiagnosticMessageId, message: &str) {
419         self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
420     }
421
422     pub fn diag_span_suggestion_once<'a, 'b>(&'a self,
423                                              diag_builder: &'b mut DiagnosticBuilder<'a>,
424                                              msg_id: DiagnosticMessageId,
425                                              span: Span,
426                                              message: &str,
427                                              suggestion: String) {
428         self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanSuggestion(suggestion),
429                        msg_id, message, Some(span));
430     }
431
432     pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
433         self.parse_sess.codemap()
434     }
435     pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
436     pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
437     pub fn profile_queries(&self) -> bool {
438         self.opts.debugging_opts.profile_queries ||
439             self.opts.debugging_opts.profile_queries_and_keys
440     }
441     pub fn profile_queries_and_keys(&self) -> bool {
442         self.opts.debugging_opts.profile_queries_and_keys
443     }
444     pub fn count_llvm_insns(&self) -> bool {
445         self.opts.debugging_opts.count_llvm_insns
446     }
447     pub fn time_llvm_passes(&self) -> bool {
448         self.opts.debugging_opts.time_llvm_passes
449     }
450     pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
451     pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
452     pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
453     pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
454     pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
455     pub fn print_llvm_passes(&self) -> bool {
456         self.opts.debugging_opts.print_llvm_passes
457     }
458
459     /// If true, we should use NLL-style region checking instead of
460     /// lexical style.
461     pub fn nll(&self) -> bool {
462         self.features.borrow().nll || self.opts.debugging_opts.nll
463     }
464
465     /// If true, we should use the MIR-based borrowck (we may *also* use
466     /// the AST-based borrowck).
467     pub fn use_mir(&self) -> bool {
468         self.borrowck_mode().use_mir()
469     }
470
471     /// If true, we should gather causal information during NLL
472     /// checking. This will eventually be the normal thing, but right
473     /// now it is too unoptimized.
474     pub fn nll_dump_cause(&self) -> bool {
475         self.opts.debugging_opts.nll_dump_cause
476     }
477
478     /// If true, we should enable two-phase borrows checks. This is
479     /// done with either `-Ztwo-phase-borrows` or with
480     /// `#![feature(nll)]`.
481     pub fn two_phase_borrows(&self) -> bool {
482         self.features.borrow().nll || self.opts.debugging_opts.two_phase_borrows
483     }
484
485     /// What mode(s) of borrowck should we run? AST? MIR? both?
486     /// (Also considers the `#![feature(nll)]` setting.)
487     pub fn borrowck_mode(&self) -> BorrowckMode {
488         match self.opts.borrowck_mode {
489             mode @ BorrowckMode::Mir |
490             mode @ BorrowckMode::Compare => mode,
491
492             mode @ BorrowckMode::Ast => {
493                 if self.nll() {
494                     BorrowckMode::Mir
495                 } else {
496                     mode
497                 }
498             }
499
500         }
501     }
502
503     /// Should we emit EndRegion MIR statements? These are consumed by
504     /// MIR borrowck, but not when NLL is used. They are also consumed
505     /// by the validation stuff.
506     pub fn emit_end_regions(&self) -> bool {
507         // FIXME(#46875) -- we should not emit end regions when NLL is enabled,
508         // but for now we can't stop doing so because it causes false positives
509         self.opts.debugging_opts.emit_end_regions ||
510             self.opts.debugging_opts.mir_emit_validate > 0 ||
511             self.use_mir()
512     }
513
514     /// Calculates the flavor of LTO to use for this compilation.
515     pub fn lto(&self) -> config::Lto {
516         // If our target has codegen requirements ignore the command line
517         if self.target.target.options.requires_lto {
518             return config::Lto::Fat
519         }
520
521         // If the user specified something, return that. If they only said `-C
522         // lto` and we've for whatever reason forced off ThinLTO via the CLI,
523         // then ensure we can't use a ThinLTO.
524         match self.opts.cg.lto {
525             config::Lto::No => {}
526             config::Lto::Yes if self.opts.cli_forced_thinlto_off => {
527                 return config::Lto::Fat
528             }
529             other => return other,
530         }
531
532         // Ok at this point the target doesn't require anything and the user
533         // hasn't asked for anything. Our next decision is whether or not
534         // we enable "auto" ThinLTO where we use multiple codegen units and
535         // then do ThinLTO over those codegen units. The logic below will
536         // either return `No` or `ThinLocal`.
537
538         // If processing command line options determined that we're incompatible
539         // with ThinLTO (e.g. `-C lto --emit llvm-ir`) then return that option.
540         if self.opts.cli_forced_thinlto_off {
541             return config::Lto::No
542         }
543
544         // If `-Z thinlto` specified process that, but note that this is mostly
545         // a deprecated option now that `-C lto=thin` exists.
546         if let Some(enabled) = self.opts.debugging_opts.thinlto {
547             if enabled {
548                 return config::Lto::ThinLocal
549             } else {
550                 return config::Lto::No
551             }
552         }
553
554         // If there's only one codegen unit and LTO isn't enabled then there's
555         // no need for ThinLTO so just return false.
556         if self.codegen_units() == 1 {
557             return config::Lto::No
558         }
559
560         // Right now ThinLTO isn't compatible with incremental compilation.
561         if self.opts.incremental.is_some() {
562             return config::Lto::No
563         }
564
565         // Now we're in "defaults" territory. By default we enable ThinLTO for
566         // optimized compiles (anything greater than O0).
567         match self.opts.optimize {
568             config::OptLevel::No => config::Lto::No,
569             _ => config::Lto::ThinLocal,
570         }
571     }
572
573     /// Returns the panic strategy for this compile session. If the user explicitly selected one
574     /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
575     pub fn panic_strategy(&self) -> PanicStrategy {
576         self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
577     }
578     pub fn linker_flavor(&self) -> LinkerFlavor {
579         self.opts.debugging_opts.linker_flavor.unwrap_or(self.target.target.linker_flavor)
580     }
581
582     pub fn fewer_names(&self) -> bool {
583         let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly) ||
584                          self.opts.output_types.contains_key(&OutputType::Bitcode);
585         self.opts.debugging_opts.fewer_names || !more_names
586     }
587
588     pub fn no_landing_pads(&self) -> bool {
589         self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
590     }
591     pub fn unstable_options(&self) -> bool {
592         self.opts.debugging_opts.unstable_options
593     }
594     pub fn nonzeroing_move_hints(&self) -> bool {
595         self.opts.debugging_opts.enable_nonzeroing_move_hints
596     }
597     pub fn overflow_checks(&self) -> bool {
598         self.opts.cg.overflow_checks
599             .or(self.opts.debugging_opts.force_overflow_checks)
600             .unwrap_or(self.opts.debug_assertions)
601     }
602
603     pub fn crt_static(&self) -> bool {
604         // If the target does not opt in to crt-static support, use its default.
605         if self.target.target.options.crt_static_respected {
606             self.crt_static_feature()
607         } else {
608             self.target.target.options.crt_static_default
609         }
610     }
611
612     pub fn crt_static_feature(&self) -> bool {
613         let requested_features = self.opts.cg.target_feature.split(',');
614         let found_negative = requested_features.clone().any(|r| r == "-crt-static");
615         let found_positive = requested_features.clone().any(|r| r == "+crt-static");
616
617         // If the target we're compiling for requests a static crt by default,
618         // then see if the `-crt-static` feature was passed to disable that.
619         // Otherwise if we don't have a static crt by default then see if the
620         // `+crt-static` feature was passed.
621         if self.target.target.options.crt_static_default {
622             !found_negative
623         } else {
624             found_positive
625         }
626     }
627
628     pub fn must_not_eliminate_frame_pointers(&self) -> bool {
629         self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
630         !self.target.target.options.eliminate_frame_pointer
631     }
632
633     /// Returns the symbol name for the registrar function,
634     /// given the crate Svh and the function DefIndex.
635     pub fn generate_plugin_registrar_symbol(&self,
636                                             disambiguator: CrateDisambiguator)
637                                             -> String {
638         format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
639     }
640
641     pub fn generate_derive_registrar_symbol(&self,
642                                             disambiguator: CrateDisambiguator)
643                                             -> String {
644         format!("__rustc_derive_registrar_{}__", disambiguator.to_fingerprint().to_hex())
645     }
646
647     pub fn sysroot<'a>(&'a self) -> &'a Path {
648         match self.opts.maybe_sysroot {
649             Some (ref sysroot) => sysroot,
650             None => self.default_sysroot.as_ref()
651                         .expect("missing sysroot and default_sysroot in Session")
652         }
653     }
654     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
655         filesearch::FileSearch::new(self.sysroot(),
656                                     &self.opts.target_triple,
657                                     &self.opts.search_paths,
658                                     kind)
659     }
660     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
661         filesearch::FileSearch::new(
662             self.sysroot(),
663             config::host_triple(),
664             &self.opts.search_paths,
665             kind)
666     }
667
668     pub fn set_incr_session_load_dep_graph(&self, load: bool) {
669         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
670
671         match *incr_comp_session {
672             IncrCompSession::Active { ref mut load_dep_graph, .. } => {
673                 *load_dep_graph = load;
674             }
675             _ => {}
676         }
677     }
678
679     pub fn incr_session_load_dep_graph(&self) -> bool {
680         let incr_comp_session = self.incr_comp_session.borrow();
681         match *incr_comp_session {
682             IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
683             _ => false,
684         }
685     }
686
687     pub fn init_incr_comp_session(&self,
688                                   session_dir: PathBuf,
689                                   lock_file: flock::Lock,
690                                   load_dep_graph: bool) {
691         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
692
693         if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
694             bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
695         }
696
697         *incr_comp_session = IncrCompSession::Active {
698             session_directory: session_dir,
699             lock_file,
700             load_dep_graph,
701         };
702     }
703
704     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
705         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
706
707         if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
708             bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
709         }
710
711         // Note: This will also drop the lock file, thus unlocking the directory
712         *incr_comp_session = IncrCompSession::Finalized {
713             session_directory: new_directory_path,
714         };
715     }
716
717     pub fn mark_incr_comp_session_as_invalid(&self) {
718         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
719
720         let session_directory = match *incr_comp_session {
721             IncrCompSession::Active { ref session_directory, .. } => {
722                 session_directory.clone()
723             }
724             IncrCompSession::InvalidBecauseOfErrors { .. } => return,
725             _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
726                       *incr_comp_session),
727         };
728
729         // Note: This will also drop the lock file, thus unlocking the directory
730         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
731             session_directory,
732         };
733     }
734
735     pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
736         let incr_comp_session = self.incr_comp_session.borrow();
737         cell::Ref::map(incr_comp_session, |incr_comp_session| {
738             match *incr_comp_session {
739                 IncrCompSession::NotInitialized => {
740                     bug!("Trying to get session directory from IncrCompSession `{:?}`",
741                         *incr_comp_session)
742                 }
743                 IncrCompSession::Active { ref session_directory, .. } |
744                 IncrCompSession::Finalized { ref session_directory } |
745                 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
746                     session_directory
747                 }
748             }
749         })
750     }
751
752     pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
753         if self.opts.incremental.is_some() {
754             Some(self.incr_comp_session_dir())
755         } else {
756             None
757         }
758     }
759
760     pub fn print_perf_stats(&self) {
761         println!("Total time spent computing SVHs:               {}",
762                  duration_to_secs_str(self.perf_stats.svh_time.get()));
763         println!("Total time spent computing incr. comp. hashes: {}",
764                  duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
765         println!("Total number of incr. comp. hashes computed:   {}",
766                  self.perf_stats.incr_comp_hashes_count.get());
767         println!("Total number of bytes hashed for incr. comp.:  {}",
768                  self.perf_stats.incr_comp_bytes_hashed.get());
769         if self.perf_stats.incr_comp_hashes_count.get() != 0 {
770             println!("Average bytes hashed per incr. comp. HIR node: {}",
771                     self.perf_stats.incr_comp_bytes_hashed.get() /
772                     self.perf_stats.incr_comp_hashes_count.get());
773         } else {
774             println!("Average bytes hashed per incr. comp. HIR node: N/A");
775         }
776         println!("Total time spent computing symbol hashes:      {}",
777                  duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
778         println!("Total time spent decoding DefPath tables:      {}",
779                  duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
780     }
781
782     /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
783     /// This expends fuel if applicable, and records fuel if applicable.
784     pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
785         let mut ret = true;
786         match self.optimization_fuel_crate {
787             Some(ref c) if c == crate_name => {
788                 let fuel = self.optimization_fuel_limit.get();
789                 ret = fuel != 0;
790                 if fuel == 0 && !self.out_of_fuel.get() {
791                     println!("optimization-fuel-exhausted: {}", msg());
792                     self.out_of_fuel.set(true);
793                 } else if fuel > 0 {
794                     self.optimization_fuel_limit.set(fuel-1);
795                 }
796             }
797             _ => {}
798         }
799         match self.print_fuel_crate {
800             Some(ref c) if c == crate_name=> {
801                 self.print_fuel.set(self.print_fuel.get()+1);
802             },
803             _ => {}
804         }
805         ret
806     }
807
808     /// Returns the number of query threads that should be used for this
809     /// compilation
810     pub fn query_threads(&self) -> usize {
811         self.opts.debugging_opts.query_threads.unwrap_or(1)
812     }
813
814     /// Returns the number of codegen units that should be used for this
815     /// compilation
816     pub fn codegen_units(&self) -> usize {
817         if let Some(n) = self.opts.cli_forced_codegen_units {
818             return n
819         }
820         if let Some(n) = self.target.target.options.default_codegen_units {
821             return n as usize
822         }
823
824         // Why is 16 codegen units the default all the time?
825         //
826         // The main reason for enabling multiple codegen units by default is to
827         // leverage the ability for the trans backend to do translation and
828         // codegen in parallel. This allows us, especially for large crates, to
829         // make good use of all available resources on the machine once we've
830         // hit that stage of compilation. Large crates especially then often
831         // take a long time in trans/codegen and this helps us amortize that
832         // cost.
833         //
834         // Note that a high number here doesn't mean that we'll be spawning a
835         // large number of threads in parallel. The backend of rustc contains
836         // global rate limiting through the `jobserver` crate so we'll never
837         // overload the system with too much work, but rather we'll only be
838         // optimizing when we're otherwise cooperating with other instances of
839         // rustc.
840         //
841         // Rather a high number here means that we should be able to keep a lot
842         // of idle cpus busy. By ensuring that no codegen unit takes *too* long
843         // to build we'll be guaranteed that all cpus will finish pretty closely
844         // to one another and we should make relatively optimal use of system
845         // resources
846         //
847         // Note that the main cost of codegen units is that it prevents LLVM
848         // from inlining across codegen units. Users in general don't have a lot
849         // of control over how codegen units are split up so it's our job in the
850         // compiler to ensure that undue performance isn't lost when using
851         // codegen units (aka we can't require everyone to slap `#[inline]` on
852         // everything).
853         //
854         // If we're compiling at `-O0` then the number doesn't really matter too
855         // much because performance doesn't matter and inlining is ok to lose.
856         // In debug mode we just want to try to guarantee that no cpu is stuck
857         // doing work that could otherwise be farmed to others.
858         //
859         // In release mode, however (O1 and above) performance does indeed
860         // matter! To recover the loss in performance due to inlining we'll be
861         // enabling ThinLTO by default (the function for which is just below).
862         // This will ensure that we recover any inlining wins we otherwise lost
863         // through codegen unit partitioning.
864         //
865         // ---
866         //
867         // Ok that's a lot of words but the basic tl;dr; is that we want a high
868         // number here -- but not too high. Additionally we're "safe" to have it
869         // always at the same number at all optimization levels.
870         //
871         // As a result 16 was chosen here! Mostly because it was a power of 2
872         // and most benchmarks agreed it was roughly a local optimum. Not very
873         // scientific.
874         16
875     }
876
877     pub fn teach(&self, code: &DiagnosticId) -> bool {
878         self.opts.debugging_opts.teach && !self.parse_sess.span_diagnostic.code_emitted(code)
879     }
880
881     /// Are we allowed to use features from the Rust 2018 epoch?
882     pub fn rust_2018(&self) -> bool {
883         self.opts.debugging_opts.epoch >= Epoch::Epoch2018
884     }
885
886     pub fn epoch(&self) -> Epoch {
887         self.opts.debugging_opts.epoch
888     }
889 }
890
891 pub fn build_session(sopts: config::Options,
892                      local_crate_source_file: Option<PathBuf>,
893                      registry: errors::registry::Registry)
894                      -> Session {
895     let file_path_mapping = sopts.file_path_mapping();
896
897     build_session_with_codemap(sopts,
898                                local_crate_source_file,
899                                registry,
900                                Lrc::new(codemap::CodeMap::new(file_path_mapping)),
901                                None)
902 }
903
904 pub fn build_session_with_codemap(sopts: config::Options,
905                                   local_crate_source_file: Option<PathBuf>,
906                                   registry: errors::registry::Registry,
907                                   codemap: Lrc<codemap::CodeMap>,
908                                   emitter_dest: Option<Box<dyn Write + Send>>)
909                                   -> Session {
910     // FIXME: This is not general enough to make the warning lint completely override
911     // normal diagnostic warnings, since the warning lint can also be denied and changed
912     // later via the source code.
913     let warnings_allow = sopts.lint_opts
914         .iter()
915         .filter(|&&(ref key, _)| *key == "warnings")
916         .map(|&(_, ref level)| *level == lint::Allow)
917         .last()
918         .unwrap_or(false);
919     let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
920
921     let can_emit_warnings = !(warnings_allow || cap_lints_allow);
922
923     let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
924
925     let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;
926
927     let emitter: Box<dyn Emitter> = match (sopts.error_format, emitter_dest) {
928         (config::ErrorOutputType::HumanReadable(color_config), None) => {
929             Box::new(EmitterWriter::stderr(color_config, Some(codemap.clone()),
930                      false, sopts.debugging_opts.teach)
931                      .ui_testing(sopts.debugging_opts.ui_testing))
932         }
933         (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
934             Box::new(EmitterWriter::new(dst, Some(codemap.clone()),
935                      false, false)
936                      .ui_testing(sopts.debugging_opts.ui_testing))
937         }
938         (config::ErrorOutputType::Json(pretty), None) => {
939             Box::new(JsonEmitter::stderr(Some(registry), codemap.clone(),
940                      pretty, sopts.debugging_opts.approximate_suggestions)
941                      .ui_testing(sopts.debugging_opts.ui_testing))
942         }
943         (config::ErrorOutputType::Json(pretty), Some(dst)) => {
944             Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone(),
945                      pretty, sopts.debugging_opts.approximate_suggestions)
946                      .ui_testing(sopts.debugging_opts.ui_testing))
947         }
948         (config::ErrorOutputType::Short(color_config), None) => {
949             Box::new(EmitterWriter::stderr(color_config, Some(codemap.clone()), true, false))
950         }
951         (config::ErrorOutputType::Short(_), Some(dst)) => {
952             Box::new(EmitterWriter::new(dst, Some(codemap.clone()), true, false))
953         }
954     };
955
956     let diagnostic_handler =
957         errors::Handler::with_emitter_and_flags(
958             emitter,
959             errors::HandlerFlags {
960                 can_emit_warnings,
961                 treat_err_as_bug,
962                 external_macro_backtrace,
963                 .. Default::default()
964             });
965
966     build_session_(sopts,
967                    local_crate_source_file,
968                    diagnostic_handler,
969                    codemap)
970 }
971
972 pub fn build_session_(sopts: config::Options,
973                       local_crate_source_file: Option<PathBuf>,
974                       span_diagnostic: errors::Handler,
975                       codemap: Lrc<codemap::CodeMap>)
976                       -> Session {
977     let host = match Target::search(config::host_triple()) {
978         Ok(t) => t,
979         Err(e) => {
980             span_diagnostic.fatal(&format!("Error loading host specification: {}", e)).raise();
981         }
982     };
983     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
984
985     let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
986     let default_sysroot = match sopts.maybe_sysroot {
987         Some(_) => None,
988         None => Some(filesearch::get_or_default_sysroot())
989     };
990
991     let file_path_mapping = sopts.file_path_mapping();
992
993     let local_crate_source_file = local_crate_source_file.map(|path| {
994         file_path_mapping.map_prefix(path).0
995     });
996
997     let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
998     let optimization_fuel_limit = Cell::new(sopts.debugging_opts.fuel.as_ref()
999         .map(|i| i.1).unwrap_or(0));
1000     let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1001     let print_fuel = Cell::new(0);
1002
1003     let working_dir = match env::current_dir() {
1004         Ok(dir) => dir,
1005         Err(e) => {
1006             p_s.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1007         }
1008     };
1009     let working_dir = file_path_mapping.map_prefix(working_dir);
1010
1011     let sess = Session {
1012         target: target_cfg,
1013         host,
1014         opts: sopts,
1015         parse_sess: p_s,
1016         // For a library crate, this is always none
1017         entry_fn: RefCell::new(None),
1018         entry_type: Cell::new(None),
1019         plugin_registrar_fn: Cell::new(None),
1020         derive_registrar_fn: Cell::new(None),
1021         default_sysroot,
1022         local_crate_source_file,
1023         working_dir,
1024         lint_store: RefCell::new(lint::LintStore::new()),
1025         buffered_lints: RefCell::new(Some(lint::LintBuffer::new())),
1026         one_time_diagnostics: RefCell::new(FxHashSet()),
1027         plugin_llvm_passes: RefCell::new(Vec::new()),
1028         plugin_attributes: RefCell::new(Vec::new()),
1029         crate_types: RefCell::new(Vec::new()),
1030         dependency_formats: RefCell::new(FxHashMap()),
1031         crate_disambiguator: RefCell::new(None),
1032         features: RefCell::new(feature_gate::Features::new()),
1033         recursion_limit: Cell::new(64),
1034         type_length_limit: Cell::new(1048576),
1035         next_node_id: Cell::new(NodeId::new(1)),
1036         injected_allocator: Cell::new(None),
1037         allocator_kind: Cell::new(None),
1038         injected_panic_runtime: Cell::new(None),
1039         imported_macro_spans: RefCell::new(HashMap::new()),
1040         incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
1041         ignored_attr_names: ich::compute_ignored_attr_names(),
1042         perf_stats: PerfStats {
1043             svh_time: Cell::new(Duration::from_secs(0)),
1044             incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
1045             incr_comp_hashes_count: Cell::new(0),
1046             incr_comp_bytes_hashed: Cell::new(0),
1047             symbol_hash_time: Cell::new(Duration::from_secs(0)),
1048             decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
1049         },
1050         code_stats: RefCell::new(CodeStats::new()),
1051         optimization_fuel_crate,
1052         optimization_fuel_limit,
1053         print_fuel_crate,
1054         print_fuel,
1055         out_of_fuel: Cell::new(false),
1056         // Note that this is unsafe because it may misinterpret file descriptors
1057         // on Unix as jobserver file descriptors. We hopefully execute this near
1058         // the beginning of the process though to ensure we don't get false
1059         // positives, or in other words we try to execute this before we open
1060         // any file descriptors ourselves.
1061         //
1062         // Also note that we stick this in a global because there could be
1063         // multiple `Session` instances in this process, and the jobserver is
1064         // per-process.
1065         jobserver_from_env: unsafe {
1066             static mut GLOBAL_JOBSERVER: *mut Option<Client> = 0 as *mut _;
1067             static INIT: Once = ONCE_INIT;
1068             INIT.call_once(|| {
1069                 GLOBAL_JOBSERVER = Box::into_raw(Box::new(Client::from_env()));
1070             });
1071             (*GLOBAL_JOBSERVER).clone()
1072         },
1073         has_global_allocator: Cell::new(false),
1074     };
1075
1076     sess
1077 }
1078
1079 /// Hash value constructed out of all the `-C metadata` arguments passed to the
1080 /// compiler. Together with the crate-name forms a unique global identifier for
1081 /// the crate.
1082 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
1083 pub struct CrateDisambiguator(Fingerprint);
1084
1085 impl CrateDisambiguator {
1086     pub fn to_fingerprint(self) -> Fingerprint {
1087         self.0
1088     }
1089 }
1090
1091 impl From<Fingerprint> for CrateDisambiguator {
1092     fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
1093         CrateDisambiguator(fingerprint)
1094     }
1095 }
1096
1097 impl_stable_hash_for!(tuple_struct CrateDisambiguator { fingerprint });
1098
1099 /// Holds data on the current incremental compilation session, if there is one.
1100 #[derive(Debug)]
1101 pub enum IncrCompSession {
1102     /// This is the state the session will be in until the incr. comp. dir is
1103     /// needed.
1104     NotInitialized,
1105     /// This is the state during which the session directory is private and can
1106     /// be modified.
1107     Active {
1108         session_directory: PathBuf,
1109         lock_file: flock::Lock,
1110         load_dep_graph: bool,
1111     },
1112     /// This is the state after the session directory has been finalized. In this
1113     /// state, the contents of the directory must not be modified any more.
1114     Finalized {
1115         session_directory: PathBuf,
1116     },
1117     /// This is an error state that is reached when some compilation error has
1118     /// occurred. It indicates that the contents of the session directory must
1119     /// not be used, since they might be invalid.
1120     InvalidBecauseOfErrors {
1121         session_directory: PathBuf,
1122     }
1123 }
1124
1125 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1126     let emitter: Box<dyn Emitter> = match output {
1127         config::ErrorOutputType::HumanReadable(color_config) => {
1128             Box::new(EmitterWriter::stderr(color_config, None, false, false))
1129         }
1130         config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1131         config::ErrorOutputType::Short(color_config) => {
1132             Box::new(EmitterWriter::stderr(color_config, None, true, false))
1133         }
1134     };
1135     let handler = errors::Handler::with_emitter(true, false, emitter);
1136     handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
1137     errors::FatalError.raise();
1138 }
1139
1140 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1141     let emitter: Box<dyn Emitter> = match output {
1142         config::ErrorOutputType::HumanReadable(color_config) => {
1143             Box::new(EmitterWriter::stderr(color_config, None, false, false))
1144         }
1145         config::ErrorOutputType::Json(pretty) => Box::new(JsonEmitter::basic(pretty)),
1146         config::ErrorOutputType::Short(color_config) => {
1147             Box::new(EmitterWriter::stderr(color_config, None, true, false))
1148         }
1149     };
1150     let handler = errors::Handler::with_emitter(true, false, emitter);
1151     handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
1152 }
1153
1154 #[derive(Copy, Clone, Debug)]
1155 pub enum CompileIncomplete {
1156     Stopped,
1157     Errored(ErrorReported)
1158 }
1159 impl From<ErrorReported> for CompileIncomplete {
1160     fn from(err: ErrorReported) -> CompileIncomplete {
1161         CompileIncomplete::Errored(err)
1162     }
1163 }
1164 pub type CompileResult = Result<(), CompileIncomplete>;
1165
1166 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
1167     if err_count == 0 {
1168         Ok(())
1169     } else {
1170         Err(CompileIncomplete::Errored(ErrorReported))
1171     }
1172 }
1173
1174 #[cold]
1175 #[inline(never)]
1176 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
1177     // this wrapper mostly exists so I don't have to write a fully
1178     // qualified path of None::<Span> inside the bug!() macro definition
1179     opt_span_bug_fmt(file, line, None::<Span>, args);
1180 }
1181
1182 #[cold]
1183 #[inline(never)]
1184 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
1185                                         line: u32,
1186                                         span: S,
1187                                         args: fmt::Arguments) -> ! {
1188     opt_span_bug_fmt(file, line, Some(span), args);
1189 }
1190
1191 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
1192                                         line: u32,
1193                                         span: Option<S>,
1194                                         args: fmt::Arguments) -> ! {
1195     tls::with_opt(move |tcx| {
1196         let msg = format!("{}:{}: {}", file, line, args);
1197         match (tcx, span) {
1198             (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
1199             (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
1200             (None, _) => panic!(msg)
1201         }
1202     });
1203     unreachable!();
1204 }