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