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