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