]> git.lizzy.rs Git - rust.git/blob - src/librustc_session/session.rs
Rollup merge of #69477 - Pulkit07:issue69298, r=cramertj
[rust.git] / src / librustc_session / session.rs
1 use crate::code_stats::CodeStats;
2 pub use crate::code_stats::{DataTypeKind, FieldInfo, SizeKind, VariantInfo};
3
4 use crate::cgu_reuse_tracker::CguReuseTracker;
5 use rustc_data_structures::fingerprint::Fingerprint;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7
8 use crate::config::{self, OutputType, PrintRequest, Sanitizer, SwitchWithOptPath};
9 use crate::filesearch;
10 use crate::lint;
11 use crate::search_paths::{PathKind, SearchPath};
12 use rustc_data_structures::profiling::duration_to_secs_str;
13 use rustc_errors::ErrorReported;
14
15 use rustc_data_structures::base_n;
16 use rustc_data_structures::impl_stable_hash_via_hash;
17 use rustc_data_structures::sync::{
18     self, AtomicU64, AtomicUsize, Lock, Lrc, Once, OneThread, Ordering, Ordering::SeqCst,
19 };
20
21 use crate::parse::ParseSess;
22 use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitterWriter;
23 use rustc_errors::emitter::HumanReadableErrorType;
24 use rustc_errors::emitter::{Emitter, EmitterWriter};
25 use rustc_errors::json::JsonEmitter;
26 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticId};
27 use rustc_span::edition::Edition;
28 use rustc_span::source_map;
29 use rustc_span::{MultiSpan, Span};
30
31 use rustc_data_structures::flock;
32 use rustc_data_structures::jobserver::{self, Client};
33 use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
34 use rustc_target::spec::{PanicStrategy, RelroLevel, Target, TargetTriple};
35
36 use std::cell::{self, RefCell};
37 use std::env;
38 use std::fmt;
39 use std::io::Write;
40 use std::num::NonZeroU32;
41 use std::path::PathBuf;
42 use std::sync::Arc;
43 use std::time::Duration;
44
45 pub struct OptimizationFuel {
46     /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
47     remaining: u64,
48     /// We're rejecting all further optimizations.
49     out_of_fuel: bool,
50 }
51
52 /// Represents the data associated with a compilation
53 /// session for a single crate.
54 pub struct Session {
55     pub target: config::Config,
56     pub host: Target,
57     pub opts: config::Options,
58     pub host_tlib_path: SearchPath,
59     /// `None` if the host and target are the same.
60     pub target_tlib_path: Option<SearchPath>,
61     pub parse_sess: ParseSess,
62     pub sysroot: PathBuf,
63     /// The name of the root source file of the crate, in the local file system.
64     /// `None` means that there is no source file.
65     pub local_crate_source_file: Option<PathBuf>,
66     /// The directory the compiler has been executed in plus a flag indicating
67     /// if the value stored here has been affected by path remapping.
68     pub working_dir: (PathBuf, bool),
69
70     /// Set of `(DiagnosticId, Option<Span>, message)` tuples tracking
71     /// (sub)diagnostics that have been set once, but should not be set again,
72     /// in order to avoid redundantly verbose output (Issue #24690, #44953).
73     pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
74     pub crate_types: Once<Vec<config::CrateType>>,
75     /// The `crate_disambiguator` is constructed out of all the `-C metadata`
76     /// arguments passed to the compiler. Its value together with the crate-name
77     /// forms a unique global identifier for the crate. It is used to allow
78     /// multiple crates with the same name to coexist. See the
79     /// `rustc_codegen_llvm::back::symbol_names` module for more information.
80     pub crate_disambiguator: Once<CrateDisambiguator>,
81
82     features: Once<rustc_feature::Features>,
83
84     /// The maximum recursion limit for potentially infinitely recursive
85     /// operations such as auto-dereference and monomorphization.
86     pub recursion_limit: Once<usize>,
87
88     /// The maximum length of types during monomorphization.
89     pub type_length_limit: Once<usize>,
90
91     /// Map from imported macro spans (which consist of
92     /// the localized span for the macro body) to the
93     /// macro name and definition span in the source crate.
94     pub imported_macro_spans: OneThread<RefCell<FxHashMap<Span, (String, Span)>>>,
95
96     incr_comp_session: OneThread<RefCell<IncrCompSession>>,
97     /// Used for incremental compilation tests. Will only be populated if
98     /// `-Zquery-dep-graph` is specified.
99     pub cgu_reuse_tracker: CguReuseTracker,
100
101     /// Used by `-Z self-profile`.
102     pub prof: SelfProfilerRef,
103
104     /// Some measurements that are being gathered during compilation.
105     pub perf_stats: PerfStats,
106
107     /// Data about code being compiled, gathered during compilation.
108     pub code_stats: CodeStats,
109
110     /// If `-zfuel=crate=n` is specified, `Some(crate)`.
111     optimization_fuel_crate: Option<String>,
112
113     /// Tracks fuel info if `-zfuel=crate=n` is specified.
114     optimization_fuel: Lock<OptimizationFuel>,
115
116     // The next two are public because the driver needs to read them.
117     /// If `-zprint-fuel=crate`, `Some(crate)`.
118     pub print_fuel_crate: Option<String>,
119     /// Always set to zero and incremented so that we can print fuel expended by a crate.
120     pub print_fuel: AtomicU64,
121
122     /// Loaded up early on in the initialization of this `Session` to avoid
123     /// false positives about a job server in our environment.
124     pub jobserver: Client,
125
126     /// Cap lint level specified by a driver specifically.
127     pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
128
129     /// `Span`s of trait methods that weren't found to avoid emitting object safety errors
130     pub trait_methods_not_found: Lock<FxHashSet<Span>>,
131
132     /// Mapping from ident span to path span for paths that don't exist as written, but that
133     /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
134     pub confused_type_with_std_module: Lock<FxHashMap<Span, Span>>,
135
136     /// Path for libraries that will take preference over libraries shipped by Rust.
137     /// Used by windows-gnu targets to priortize system mingw-w64 libraries.
138     pub system_library_path: OneThread<RefCell<Option<Option<PathBuf>>>>,
139 }
140
141 pub struct PerfStats {
142     /// The accumulated time spent on computing symbol hashes.
143     pub symbol_hash_time: Lock<Duration>,
144     /// The accumulated time spent decoding def path tables from metadata.
145     pub decode_def_path_tables_time: Lock<Duration>,
146     /// Total number of values canonicalized queries constructed.
147     pub queries_canonicalized: AtomicUsize,
148     /// Number of times this query is invoked.
149     pub normalize_ty_after_erasing_regions: AtomicUsize,
150     /// Number of times this query is invoked.
151     pub normalize_projection_ty: AtomicUsize,
152 }
153
154 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
155 enum DiagnosticBuilderMethod {
156     Note,
157     SpanNote,
158     SpanSuggestion(String), // suggestion
159                             // Add more variants as needed to support one-time diagnostics.
160 }
161
162 /// Diagnostic message ID, used by `Session.one_time_diagnostics` to avoid
163 /// emitting the same message more than once.
164 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
165 pub enum DiagnosticMessageId {
166     ErrorId(u16), // EXXXX error code as integer
167     LintId(lint::LintId),
168     StabilityId(Option<NonZeroU32>), // issue number
169 }
170
171 impl From<&'static lint::Lint> for DiagnosticMessageId {
172     fn from(lint: &'static lint::Lint) -> Self {
173         DiagnosticMessageId::LintId(lint::LintId::of(lint))
174     }
175 }
176
177 impl Session {
178     pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
179         *self.crate_disambiguator.get()
180     }
181
182     pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
183         self.diagnostic().struct_span_warn(sp, msg)
184     }
185     pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
186         &self,
187         sp: S,
188         msg: &str,
189         code: DiagnosticId,
190     ) -> DiagnosticBuilder<'_> {
191         self.diagnostic().struct_span_warn_with_code(sp, msg, code)
192     }
193     pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
194         self.diagnostic().struct_warn(msg)
195     }
196     pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
197         self.diagnostic().struct_span_err(sp, msg)
198     }
199     pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
200         &self,
201         sp: S,
202         msg: &str,
203         code: DiagnosticId,
204     ) -> DiagnosticBuilder<'_> {
205         self.diagnostic().struct_span_err_with_code(sp, msg, code)
206     }
207     // FIXME: This method should be removed (every error should have an associated error code).
208     pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
209         self.diagnostic().struct_err(msg)
210     }
211     pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
212         self.diagnostic().struct_err_with_code(msg, code)
213     }
214     pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
215         self.diagnostic().struct_span_fatal(sp, msg)
216     }
217     pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
218         &self,
219         sp: S,
220         msg: &str,
221         code: DiagnosticId,
222     ) -> DiagnosticBuilder<'_> {
223         self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
224     }
225     pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
226         self.diagnostic().struct_fatal(msg)
227     }
228
229     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
230         self.diagnostic().span_fatal(sp, msg).raise()
231     }
232     pub fn span_fatal_with_code<S: Into<MultiSpan>>(
233         &self,
234         sp: S,
235         msg: &str,
236         code: DiagnosticId,
237     ) -> ! {
238         self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
239     }
240     pub fn fatal(&self, msg: &str) -> ! {
241         self.diagnostic().fatal(msg).raise()
242     }
243     pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
244         if is_warning {
245             self.span_warn(sp, msg);
246         } else {
247             self.span_err(sp, msg);
248         }
249     }
250     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
251         self.diagnostic().span_err(sp, msg)
252     }
253     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
254         self.diagnostic().span_err_with_code(sp, &msg, code)
255     }
256     pub fn err(&self, msg: &str) {
257         self.diagnostic().err(msg)
258     }
259     pub fn err_count(&self) -> usize {
260         self.diagnostic().err_count()
261     }
262     pub fn has_errors(&self) -> bool {
263         self.diagnostic().has_errors()
264     }
265     pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
266         self.diagnostic().has_errors_or_delayed_span_bugs()
267     }
268     pub fn abort_if_errors(&self) {
269         self.diagnostic().abort_if_errors();
270     }
271     pub fn compile_status(&self) -> Result<(), ErrorReported> {
272         if self.has_errors() {
273             self.diagnostic().emit_stashed_diagnostics();
274             Err(ErrorReported)
275         } else {
276             Ok(())
277         }
278     }
279     // FIXME(matthewjasper) Remove this method, it should never be needed.
280     pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
281     where
282         F: FnOnce() -> T,
283     {
284         let old_count = self.err_count();
285         let result = f();
286         let errors = self.err_count() - old_count;
287         if errors == 0 { Ok(result) } else { Err(ErrorReported) }
288     }
289     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
290         self.diagnostic().span_warn(sp, msg)
291     }
292     pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
293         self.diagnostic().span_warn_with_code(sp, msg, code)
294     }
295     pub fn warn(&self, msg: &str) {
296         self.diagnostic().warn(msg)
297     }
298     pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
299         match opt_sp {
300             Some(sp) => self.span_warn(sp, msg),
301             None => self.warn(msg),
302         }
303     }
304     /// Delay a span_bug() call until abort_if_errors()
305     pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
306         self.diagnostic().delay_span_bug(sp, msg)
307     }
308     pub fn note_without_error(&self, msg: &str) {
309         self.diagnostic().note_without_error(msg)
310     }
311     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
312         self.diagnostic().span_note_without_error(sp, msg)
313     }
314
315     pub fn diagnostic(&self) -> &rustc_errors::Handler {
316         &self.parse_sess.span_diagnostic
317     }
318
319     /// Analogous to calling methods on the given `DiagnosticBuilder`, but
320     /// deduplicates on lint ID, span (if any), and message for this `Session`
321     fn diag_once<'a, 'b>(
322         &'a self,
323         diag_builder: &'b mut DiagnosticBuilder<'a>,
324         method: DiagnosticBuilderMethod,
325         msg_id: DiagnosticMessageId,
326         message: &str,
327         span_maybe: Option<Span>,
328     ) {
329         let id_span_message = (msg_id, span_maybe, message.to_owned());
330         let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
331         if fresh {
332             match method {
333                 DiagnosticBuilderMethod::Note => {
334                     diag_builder.note(message);
335                 }
336                 DiagnosticBuilderMethod::SpanNote => {
337                     let span = span_maybe.expect("`span_note` needs a span");
338                     diag_builder.span_note(span, message);
339                 }
340                 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
341                     let span = span_maybe.expect("`span_suggestion_*` needs a span");
342                     diag_builder.span_suggestion(
343                         span,
344                         message,
345                         suggestion,
346                         Applicability::Unspecified,
347                     );
348                 }
349             }
350         }
351     }
352
353     pub fn diag_span_note_once<'a, 'b>(
354         &'a self,
355         diag_builder: &'b mut DiagnosticBuilder<'a>,
356         msg_id: DiagnosticMessageId,
357         span: Span,
358         message: &str,
359     ) {
360         self.diag_once(
361             diag_builder,
362             DiagnosticBuilderMethod::SpanNote,
363             msg_id,
364             message,
365             Some(span),
366         );
367     }
368
369     pub fn diag_note_once<'a, 'b>(
370         &'a self,
371         diag_builder: &'b mut DiagnosticBuilder<'a>,
372         msg_id: DiagnosticMessageId,
373         message: &str,
374     ) {
375         self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
376     }
377
378     pub fn diag_span_suggestion_once<'a, 'b>(
379         &'a self,
380         diag_builder: &'b mut DiagnosticBuilder<'a>,
381         msg_id: DiagnosticMessageId,
382         span: Span,
383         message: &str,
384         suggestion: String,
385     ) {
386         self.diag_once(
387             diag_builder,
388             DiagnosticBuilderMethod::SpanSuggestion(suggestion),
389             msg_id,
390             message,
391             Some(span),
392         );
393     }
394
395     #[inline]
396     pub fn source_map(&self) -> &source_map::SourceMap {
397         self.parse_sess.source_map()
398     }
399     pub fn verbose(&self) -> bool {
400         self.opts.debugging_opts.verbose
401     }
402     pub fn time_passes(&self) -> bool {
403         self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
404     }
405     pub fn instrument_mcount(&self) -> bool {
406         self.opts.debugging_opts.instrument_mcount
407     }
408     pub fn time_llvm_passes(&self) -> bool {
409         self.opts.debugging_opts.time_llvm_passes
410     }
411     pub fn meta_stats(&self) -> bool {
412         self.opts.debugging_opts.meta_stats
413     }
414     pub fn asm_comments(&self) -> bool {
415         self.opts.debugging_opts.asm_comments
416     }
417     pub fn verify_llvm_ir(&self) -> bool {
418         self.opts.debugging_opts.verify_llvm_ir || cfg!(always_verify_llvm_ir)
419     }
420     pub fn borrowck_stats(&self) -> bool {
421         self.opts.debugging_opts.borrowck_stats
422     }
423     pub fn print_llvm_passes(&self) -> bool {
424         self.opts.debugging_opts.print_llvm_passes
425     }
426     pub fn binary_dep_depinfo(&self) -> bool {
427         self.opts.debugging_opts.binary_dep_depinfo
428     }
429
430     /// Gets the features enabled for the current compilation session.
431     /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
432     /// dependency tracking. Use tcx.features() instead.
433     #[inline]
434     pub fn features_untracked(&self) -> &rustc_feature::Features {
435         self.features.get()
436     }
437
438     pub fn init_features(&self, features: rustc_feature::Features) {
439         self.features.set(features);
440     }
441
442     /// Calculates the flavor of LTO to use for this compilation.
443     pub fn lto(&self) -> config::Lto {
444         // If our target has codegen requirements ignore the command line
445         if self.target.target.options.requires_lto {
446             return config::Lto::Fat;
447         }
448
449         // If the user specified something, return that. If they only said `-C
450         // lto` and we've for whatever reason forced off ThinLTO via the CLI,
451         // then ensure we can't use a ThinLTO.
452         match self.opts.cg.lto {
453             config::LtoCli::Unspecified => {
454                 // The compiler was invoked without the `-Clto` flag. Fall
455                 // through to the default handling
456             }
457             config::LtoCli::No => {
458                 // The user explicitly opted out of any kind of LTO
459                 return config::Lto::No;
460             }
461             config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
462                 // All of these mean fat LTO
463                 return config::Lto::Fat;
464             }
465             config::LtoCli::Thin => {
466                 return if self.opts.cli_forced_thinlto_off {
467                     config::Lto::Fat
468                 } else {
469                     config::Lto::Thin
470                 };
471             }
472         }
473
474         // Ok at this point the target doesn't require anything and the user
475         // hasn't asked for anything. Our next decision is whether or not
476         // we enable "auto" ThinLTO where we use multiple codegen units and
477         // then do ThinLTO over those codegen units. The logic below will
478         // either return `No` or `ThinLocal`.
479
480         // If processing command line options determined that we're incompatible
481         // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
482         if self.opts.cli_forced_thinlto_off {
483             return config::Lto::No;
484         }
485
486         // If `-Z thinlto` specified process that, but note that this is mostly
487         // a deprecated option now that `-C lto=thin` exists.
488         if let Some(enabled) = self.opts.debugging_opts.thinlto {
489             if enabled {
490                 return config::Lto::ThinLocal;
491             } else {
492                 return config::Lto::No;
493             }
494         }
495
496         // If there's only one codegen unit and LTO isn't enabled then there's
497         // no need for ThinLTO so just return false.
498         if self.codegen_units() == 1 {
499             return config::Lto::No;
500         }
501
502         // Now we're in "defaults" territory. By default we enable ThinLTO for
503         // optimized compiles (anything greater than O0).
504         match self.opts.optimize {
505             config::OptLevel::No => config::Lto::No,
506             _ => config::Lto::ThinLocal,
507         }
508     }
509
510     /// Returns the panic strategy for this compile session. If the user explicitly selected one
511     /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
512     pub fn panic_strategy(&self) -> PanicStrategy {
513         self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
514     }
515     pub fn fewer_names(&self) -> bool {
516         let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
517             || self.opts.output_types.contains_key(&OutputType::Bitcode);
518
519         // Address sanitizer and memory sanitizer use alloca name when reporting an issue.
520         let more_names = match self.opts.debugging_opts.sanitizer {
521             Some(Sanitizer::Address) => true,
522             Some(Sanitizer::Memory) => true,
523             _ => more_names,
524         };
525
526         self.opts.debugging_opts.fewer_names || !more_names
527     }
528
529     pub fn no_landing_pads(&self) -> bool {
530         self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
531     }
532     pub fn unstable_options(&self) -> bool {
533         self.opts.debugging_opts.unstable_options
534     }
535     pub fn overflow_checks(&self) -> bool {
536         self.opts
537             .cg
538             .overflow_checks
539             .or(self.opts.debugging_opts.force_overflow_checks)
540             .unwrap_or(self.opts.debug_assertions)
541     }
542
543     pub fn crt_static(&self) -> bool {
544         // If the target does not opt in to crt-static support, use its default.
545         if self.target.target.options.crt_static_respected {
546             self.crt_static_feature()
547         } else {
548             self.target.target.options.crt_static_default
549         }
550     }
551
552     pub fn crt_static_feature(&self) -> bool {
553         let requested_features = self.opts.cg.target_feature.split(',');
554         let found_negative = requested_features.clone().any(|r| r == "-crt-static");
555         let found_positive = requested_features.clone().any(|r| r == "+crt-static");
556
557         // If the target we're compiling for requests a static crt by default,
558         // then see if the `-crt-static` feature was passed to disable that.
559         // Otherwise if we don't have a static crt by default then see if the
560         // `+crt-static` feature was passed.
561         if self.target.target.options.crt_static_default { !found_negative } else { found_positive }
562     }
563
564     pub fn must_not_eliminate_frame_pointers(&self) -> bool {
565         // "mcount" function relies on stack pointer.
566         // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
567         if self.instrument_mcount() {
568             true
569         } else if let Some(x) = self.opts.cg.force_frame_pointers {
570             x
571         } else {
572             !self.target.target.options.eliminate_frame_pointer
573         }
574     }
575
576     /// Returns the symbol name for the registrar function,
577     /// given the crate `Svh` and the function `DefIndex`.
578     pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
579         format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
580     }
581
582     pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
583         format!("__rustc_proc_macro_decls_{}__", disambiguator.to_fingerprint().to_hex())
584     }
585
586     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
587         filesearch::FileSearch::new(
588             &self.sysroot,
589             self.opts.target_triple.triple(),
590             &self.opts.search_paths,
591             // `target_tlib_path == None` means it's the same as `host_tlib_path`.
592             self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
593             kind,
594         )
595     }
596     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
597         filesearch::FileSearch::new(
598             &self.sysroot,
599             config::host_triple(),
600             &self.opts.search_paths,
601             &self.host_tlib_path,
602             kind,
603         )
604     }
605
606     pub fn set_incr_session_load_dep_graph(&self, load: bool) {
607         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
608
609         if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
610             *load_dep_graph = load;
611         }
612     }
613
614     pub fn incr_session_load_dep_graph(&self) -> bool {
615         let incr_comp_session = self.incr_comp_session.borrow();
616         match *incr_comp_session {
617             IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
618             _ => false,
619         }
620     }
621
622     pub fn init_incr_comp_session(
623         &self,
624         session_dir: PathBuf,
625         lock_file: flock::Lock,
626         load_dep_graph: bool,
627     ) {
628         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
629
630         if let IncrCompSession::NotInitialized = *incr_comp_session {
631         } else {
632             panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
633         }
634
635         *incr_comp_session =
636             IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
637     }
638
639     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
640         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
641
642         if let IncrCompSession::Active { .. } = *incr_comp_session {
643         } else {
644             panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
645         }
646
647         // Note: this will also drop the lock file, thus unlocking the directory.
648         *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
649     }
650
651     pub fn mark_incr_comp_session_as_invalid(&self) {
652         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
653
654         let session_directory = match *incr_comp_session {
655             IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
656             IncrCompSession::InvalidBecauseOfErrors { .. } => return,
657             _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
658         };
659
660         // Note: this will also drop the lock file, thus unlocking the directory.
661         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
662     }
663
664     pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
665         let incr_comp_session = self.incr_comp_session.borrow();
666         cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
667             IncrCompSession::NotInitialized => panic!(
668                 "trying to get session directory from `IncrCompSession`: {:?}",
669                 *incr_comp_session,
670             ),
671             IncrCompSession::Active { ref session_directory, .. }
672             | IncrCompSession::Finalized { ref session_directory }
673             | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
674                 session_directory
675             }
676         })
677     }
678
679     pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
680         self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
681     }
682
683     pub fn print_perf_stats(&self) {
684         println!(
685             "Total time spent computing symbol hashes:      {}",
686             duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
687         );
688         println!(
689             "Total time spent decoding DefPath tables:      {}",
690             duration_to_secs_str(*self.perf_stats.decode_def_path_tables_time.lock())
691         );
692         println!(
693             "Total queries canonicalized:                   {}",
694             self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
695         );
696         println!(
697             "normalize_ty_after_erasing_regions:            {}",
698             self.perf_stats.normalize_ty_after_erasing_regions.load(Ordering::Relaxed)
699         );
700         println!(
701             "normalize_projection_ty:                       {}",
702             self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
703         );
704     }
705
706     /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
707     /// This expends fuel if applicable, and records fuel if applicable.
708     pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
709         let mut ret = true;
710         if let Some(ref c) = self.optimization_fuel_crate {
711             if c == crate_name {
712                 assert_eq!(self.threads(), 1);
713                 let mut fuel = self.optimization_fuel.lock();
714                 ret = fuel.remaining != 0;
715                 if fuel.remaining == 0 && !fuel.out_of_fuel {
716                     eprintln!("optimization-fuel-exhausted: {}", msg());
717                     fuel.out_of_fuel = true;
718                 } else if fuel.remaining > 0 {
719                     fuel.remaining -= 1;
720                 }
721             }
722         }
723         if let Some(ref c) = self.print_fuel_crate {
724             if c == crate_name {
725                 assert_eq!(self.threads(), 1);
726                 self.print_fuel.fetch_add(1, SeqCst);
727             }
728         }
729         ret
730     }
731
732     /// Returns the number of query threads that should be used for this
733     /// compilation
734     pub fn threads(&self) -> usize {
735         self.opts.debugging_opts.threads
736     }
737
738     /// Returns the number of codegen units that should be used for this
739     /// compilation
740     pub fn codegen_units(&self) -> usize {
741         if let Some(n) = self.opts.cli_forced_codegen_units {
742             return n;
743         }
744         if let Some(n) = self.target.target.options.default_codegen_units {
745             return n as usize;
746         }
747
748         // Why is 16 codegen units the default all the time?
749         //
750         // The main reason for enabling multiple codegen units by default is to
751         // leverage the ability for the codegen backend to do codegen and
752         // optimization in parallel. This allows us, especially for large crates, to
753         // make good use of all available resources on the machine once we've
754         // hit that stage of compilation. Large crates especially then often
755         // take a long time in codegen/optimization and this helps us amortize that
756         // cost.
757         //
758         // Note that a high number here doesn't mean that we'll be spawning a
759         // large number of threads in parallel. The backend of rustc contains
760         // global rate limiting through the `jobserver` crate so we'll never
761         // overload the system with too much work, but rather we'll only be
762         // optimizing when we're otherwise cooperating with other instances of
763         // rustc.
764         //
765         // Rather a high number here means that we should be able to keep a lot
766         // of idle cpus busy. By ensuring that no codegen unit takes *too* long
767         // to build we'll be guaranteed that all cpus will finish pretty closely
768         // to one another and we should make relatively optimal use of system
769         // resources
770         //
771         // Note that the main cost of codegen units is that it prevents LLVM
772         // from inlining across codegen units. Users in general don't have a lot
773         // of control over how codegen units are split up so it's our job in the
774         // compiler to ensure that undue performance isn't lost when using
775         // codegen units (aka we can't require everyone to slap `#[inline]` on
776         // everything).
777         //
778         // If we're compiling at `-O0` then the number doesn't really matter too
779         // much because performance doesn't matter and inlining is ok to lose.
780         // In debug mode we just want to try to guarantee that no cpu is stuck
781         // doing work that could otherwise be farmed to others.
782         //
783         // In release mode, however (O1 and above) performance does indeed
784         // matter! To recover the loss in performance due to inlining we'll be
785         // enabling ThinLTO by default (the function for which is just below).
786         // This will ensure that we recover any inlining wins we otherwise lost
787         // through codegen unit partitioning.
788         //
789         // ---
790         //
791         // Ok that's a lot of words but the basic tl;dr; is that we want a high
792         // number here -- but not too high. Additionally we're "safe" to have it
793         // always at the same number at all optimization levels.
794         //
795         // As a result 16 was chosen here! Mostly because it was a power of 2
796         // and most benchmarks agreed it was roughly a local optimum. Not very
797         // scientific.
798         16
799     }
800
801     pub fn teach(&self, code: &DiagnosticId) -> bool {
802         self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
803     }
804
805     pub fn rust_2015(&self) -> bool {
806         self.opts.edition == Edition::Edition2015
807     }
808
809     /// Are we allowed to use features from the Rust 2018 edition?
810     pub fn rust_2018(&self) -> bool {
811         self.opts.edition >= Edition::Edition2018
812     }
813
814     pub fn edition(&self) -> Edition {
815         self.opts.edition
816     }
817
818     /// Returns `true` if we cannot skip the PLT for shared library calls.
819     pub fn needs_plt(&self) -> bool {
820         // Check if the current target usually needs PLT to be enabled.
821         // The user can use the command line flag to override it.
822         let needs_plt = self.target.target.options.needs_plt;
823
824         let dbg_opts = &self.opts.debugging_opts;
825
826         let relro_level = dbg_opts.relro_level.unwrap_or(self.target.target.options.relro_level);
827
828         // Only enable this optimization by default if full relro is also enabled.
829         // In this case, lazy binding was already unavailable, so nothing is lost.
830         // This also ensures `-Wl,-z,now` is supported by the linker.
831         let full_relro = RelroLevel::Full == relro_level;
832
833         // If user didn't explicitly forced us to use / skip the PLT,
834         // then try to skip it where possible.
835         dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
836     }
837 }
838
839 pub fn build_session(
840     sopts: config::Options,
841     local_crate_source_file: Option<PathBuf>,
842     registry: rustc_errors::registry::Registry,
843 ) -> Session {
844     let file_path_mapping = sopts.file_path_mapping();
845
846     build_session_with_source_map(
847         sopts,
848         local_crate_source_file,
849         registry,
850         Lrc::new(source_map::SourceMap::new(file_path_mapping)),
851         DiagnosticOutput::Default,
852         Default::default(),
853     )
854 }
855
856 fn default_emitter(
857     sopts: &config::Options,
858     registry: rustc_errors::registry::Registry,
859     source_map: &Lrc<source_map::SourceMap>,
860     emitter_dest: Option<Box<dyn Write + Send>>,
861 ) -> Box<dyn Emitter + sync::Send> {
862     let macro_backtrace = sopts.debugging_opts.macro_backtrace;
863     match (sopts.error_format, emitter_dest) {
864         (config::ErrorOutputType::HumanReadable(kind), dst) => {
865             let (short, color_config) = kind.unzip();
866
867             if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
868                 let emitter = AnnotateSnippetEmitterWriter::new(
869                     Some(source_map.clone()),
870                     short,
871                     macro_backtrace,
872                 );
873                 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing()))
874             } else {
875                 let emitter = match dst {
876                     None => EmitterWriter::stderr(
877                         color_config,
878                         Some(source_map.clone()),
879                         short,
880                         sopts.debugging_opts.teach,
881                         sopts.debugging_opts.terminal_width,
882                         macro_backtrace,
883                     ),
884                     Some(dst) => EmitterWriter::new(
885                         dst,
886                         Some(source_map.clone()),
887                         short,
888                         false, // no teach messages when writing to a buffer
889                         false, // no colors when writing to a buffer
890                         None,  // no terminal width
891                         macro_backtrace,
892                     ),
893                 };
894                 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing()))
895             }
896         }
897         (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
898             JsonEmitter::stderr(
899                 Some(registry),
900                 source_map.clone(),
901                 pretty,
902                 json_rendered,
903                 macro_backtrace,
904             )
905             .ui_testing(sopts.debugging_opts.ui_testing()),
906         ),
907         (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
908             JsonEmitter::new(
909                 dst,
910                 Some(registry),
911                 source_map.clone(),
912                 pretty,
913                 json_rendered,
914                 macro_backtrace,
915             )
916             .ui_testing(sopts.debugging_opts.ui_testing()),
917         ),
918     }
919 }
920
921 pub enum DiagnosticOutput {
922     Default,
923     Raw(Box<dyn Write + Send>),
924 }
925
926 pub fn build_session_with_source_map(
927     sopts: config::Options,
928     local_crate_source_file: Option<PathBuf>,
929     registry: rustc_errors::registry::Registry,
930     source_map: Lrc<source_map::SourceMap>,
931     diagnostics_output: DiagnosticOutput,
932     lint_caps: FxHashMap<lint::LintId, lint::Level>,
933 ) -> Session {
934     // FIXME: This is not general enough to make the warning lint completely override
935     // normal diagnostic warnings, since the warning lint can also be denied and changed
936     // later via the source code.
937     let warnings_allow = sopts
938         .lint_opts
939         .iter()
940         .filter(|&&(ref key, _)| *key == "warnings")
941         .map(|&(_, ref level)| *level == lint::Allow)
942         .last()
943         .unwrap_or(false);
944     let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
945     let can_emit_warnings = !(warnings_allow || cap_lints_allow);
946
947     let write_dest = match diagnostics_output {
948         DiagnosticOutput::Default => None,
949         DiagnosticOutput::Raw(write) => Some(write),
950     };
951     let emitter = default_emitter(&sopts, registry, &source_map, write_dest);
952
953     let diagnostic_handler = rustc_errors::Handler::with_emitter_and_flags(
954         emitter,
955         sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
956     );
957
958     build_session_(sopts, local_crate_source_file, diagnostic_handler, source_map, lint_caps)
959 }
960
961 fn build_session_(
962     sopts: config::Options,
963     local_crate_source_file: Option<PathBuf>,
964     span_diagnostic: rustc_errors::Handler,
965     source_map: Lrc<source_map::SourceMap>,
966     driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
967 ) -> Session {
968     let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
969     {
970         let directory =
971             if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
972
973         let profiler = SelfProfiler::new(
974             directory,
975             sopts.crate_name.as_ref().map(|s| &s[..]),
976             &sopts.debugging_opts.self_profile_events,
977         );
978         match profiler {
979             Ok(profiler) => Some(Arc::new(profiler)),
980             Err(e) => {
981                 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
982                 None
983             }
984         }
985     } else {
986         None
987     };
988
989     let host_triple = TargetTriple::from_triple(config::host_triple());
990     let host = Target::search(&host_triple).unwrap_or_else(|e| {
991         span_diagnostic.fatal(&format!("Error loading host specification: {}", e)).raise()
992     });
993     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
994
995     let parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
996     let sysroot = match &sopts.maybe_sysroot {
997         Some(sysroot) => sysroot.clone(),
998         None => filesearch::get_or_default_sysroot(),
999     };
1000
1001     let host_triple = config::host_triple();
1002     let target_triple = sopts.target_triple.triple();
1003     let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1004     let target_tlib_path = if host_triple == target_triple {
1005         None
1006     } else {
1007         Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1008     };
1009
1010     let file_path_mapping = sopts.file_path_mapping();
1011
1012     let local_crate_source_file =
1013         local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1014
1015     let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1016     let optimization_fuel = Lock::new(OptimizationFuel {
1017         remaining: sopts.debugging_opts.fuel.as_ref().map(|i| i.1).unwrap_or(0),
1018         out_of_fuel: false,
1019     });
1020     let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1021     let print_fuel = AtomicU64::new(0);
1022
1023     let working_dir = env::current_dir().unwrap_or_else(|e| {
1024         parse_sess.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1025     });
1026     let working_dir = file_path_mapping.map_prefix(working_dir);
1027
1028     let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1029         CguReuseTracker::new()
1030     } else {
1031         CguReuseTracker::new_disabled()
1032     };
1033
1034     let prof = SelfProfilerRef::new(
1035         self_profiler,
1036         sopts.debugging_opts.time_passes || sopts.debugging_opts.time,
1037         sopts.debugging_opts.time_passes,
1038     );
1039
1040     let sess = Session {
1041         target: target_cfg,
1042         host,
1043         opts: sopts,
1044         host_tlib_path,
1045         target_tlib_path,
1046         parse_sess,
1047         sysroot,
1048         local_crate_source_file,
1049         working_dir,
1050         one_time_diagnostics: Default::default(),
1051         crate_types: Once::new(),
1052         crate_disambiguator: Once::new(),
1053         features: Once::new(),
1054         recursion_limit: Once::new(),
1055         type_length_limit: Once::new(),
1056         imported_macro_spans: OneThread::new(RefCell::new(FxHashMap::default())),
1057         incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1058         cgu_reuse_tracker,
1059         prof,
1060         perf_stats: PerfStats {
1061             symbol_hash_time: Lock::new(Duration::from_secs(0)),
1062             decode_def_path_tables_time: Lock::new(Duration::from_secs(0)),
1063             queries_canonicalized: AtomicUsize::new(0),
1064             normalize_ty_after_erasing_regions: AtomicUsize::new(0),
1065             normalize_projection_ty: AtomicUsize::new(0),
1066         },
1067         code_stats: Default::default(),
1068         optimization_fuel_crate,
1069         optimization_fuel,
1070         print_fuel_crate,
1071         print_fuel,
1072         jobserver: jobserver::client(),
1073         driver_lint_caps,
1074         trait_methods_not_found: Lock::new(Default::default()),
1075         confused_type_with_std_module: Lock::new(Default::default()),
1076         system_library_path: OneThread::new(RefCell::new(Default::default())),
1077     };
1078
1079     validate_commandline_args_with_session_available(&sess);
1080
1081     sess
1082 }
1083
1084 // If it is useful to have a Session available already for validating a
1085 // commandline argument, you can do so here.
1086 fn validate_commandline_args_with_session_available(sess: &Session) {
1087     // Since we don't know if code in an rlib will be linked to statically or
1088     // dynamically downstream, rustc generates `__imp_` symbols that help the
1089     // MSVC linker deal with this lack of knowledge (#27438). Unfortunately,
1090     // these manually generated symbols confuse LLD when it tries to merge
1091     // bitcode during ThinLTO. Therefore we disallow dynamic linking on MSVC
1092     // when compiling for LLD ThinLTO. This way we can validly just not generate
1093     // the `dllimport` attributes and `__imp_` symbols in that case.
1094     if sess.opts.cg.linker_plugin_lto.enabled()
1095         && sess.opts.cg.prefer_dynamic
1096         && sess.target.target.options.is_like_msvc
1097     {
1098         sess.err(
1099             "Linker plugin based LTO is not supported together with \
1100                   `-C prefer-dynamic` when targeting MSVC",
1101         );
1102     }
1103
1104     // Make sure that any given profiling data actually exists so LLVM can't
1105     // decide to silently skip PGO.
1106     if let Some(ref path) = sess.opts.cg.profile_use {
1107         if !path.exists() {
1108             sess.err(&format!(
1109                 "File `{}` passed to `-C profile-use` does not exist.",
1110                 path.display()
1111             ));
1112         }
1113     }
1114
1115     // PGO does not work reliably with panic=unwind on Windows. Let's make it
1116     // an error to combine the two for now. It always runs into an assertions
1117     // if LLVM is built with assertions, but without assertions it sometimes
1118     // does not crash and will probably generate a corrupted binary.
1119     // We should only display this error if we're actually going to run PGO.
1120     // If we're just supposed to print out some data, don't show the error (#61002).
1121     if sess.opts.cg.profile_generate.enabled()
1122         && sess.target.target.options.is_like_msvc
1123         && sess.panic_strategy() == PanicStrategy::Unwind
1124         && sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs)
1125     {
1126         sess.err(
1127             "Profile-guided optimization does not yet work in conjunction \
1128                   with `-Cpanic=unwind` on Windows when targeting MSVC. \
1129                   See issue #61002 <https://github.com/rust-lang/rust/issues/61002> \
1130                   for more information.",
1131         );
1132     }
1133
1134     // Sanitizers can only be used on some tested platforms.
1135     if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
1136         const ASAN_SUPPORTED_TARGETS: &[&str] = &[
1137             "x86_64-unknown-linux-gnu",
1138             "x86_64-apple-darwin",
1139             "x86_64-fuchsia",
1140             "aarch64-fuchsia",
1141         ];
1142         const TSAN_SUPPORTED_TARGETS: &[&str] =
1143             &["x86_64-unknown-linux-gnu", "x86_64-apple-darwin"];
1144         const LSAN_SUPPORTED_TARGETS: &[&str] =
1145             &["x86_64-unknown-linux-gnu", "x86_64-apple-darwin"];
1146         const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
1147
1148         let supported_targets = match *sanitizer {
1149             Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
1150             Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
1151             Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
1152             Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
1153         };
1154
1155         if !supported_targets.contains(&&*sess.opts.target_triple.triple()) {
1156             sess.err(&format!(
1157                 "{:?}Sanitizer only works with the `{}` target",
1158                 sanitizer,
1159                 supported_targets.join("` or `")
1160             ));
1161         }
1162     }
1163 }
1164
1165 /// Hash value constructed out of all the `-C metadata` arguments passed to the
1166 /// compiler. Together with the crate-name forms a unique global identifier for
1167 /// the crate.
1168 #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)]
1169 pub struct CrateDisambiguator(Fingerprint);
1170
1171 impl CrateDisambiguator {
1172     pub fn to_fingerprint(self) -> Fingerprint {
1173         self.0
1174     }
1175 }
1176
1177 impl fmt::Display for CrateDisambiguator {
1178     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1179         let (a, b) = self.0.as_value();
1180         let as_u128 = a as u128 | ((b as u128) << 64);
1181         f.write_str(&base_n::encode(as_u128, base_n::CASE_INSENSITIVE))
1182     }
1183 }
1184
1185 impl From<Fingerprint> for CrateDisambiguator {
1186     fn from(fingerprint: Fingerprint) -> CrateDisambiguator {
1187         CrateDisambiguator(fingerprint)
1188     }
1189 }
1190
1191 impl_stable_hash_via_hash!(CrateDisambiguator);
1192
1193 /// Holds data on the current incremental compilation session, if there is one.
1194 #[derive(Debug)]
1195 pub enum IncrCompSession {
1196     /// This is the state the session will be in until the incr. comp. dir is
1197     /// needed.
1198     NotInitialized,
1199     /// This is the state during which the session directory is private and can
1200     /// be modified.
1201     Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1202     /// This is the state after the session directory has been finalized. In this
1203     /// state, the contents of the directory must not be modified any more.
1204     Finalized { session_directory: PathBuf },
1205     /// This is an error state that is reached when some compilation error has
1206     /// occurred. It indicates that the contents of the session directory must
1207     /// not be used, since they might be invalid.
1208     InvalidBecauseOfErrors { session_directory: PathBuf },
1209 }
1210
1211 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1212     let emitter: Box<dyn Emitter + sync::Send> = match output {
1213         config::ErrorOutputType::HumanReadable(kind) => {
1214             let (short, color_config) = kind.unzip();
1215             Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1216         }
1217         config::ErrorOutputType::Json { pretty, json_rendered } => {
1218             Box::new(JsonEmitter::basic(pretty, json_rendered, false))
1219         }
1220     };
1221     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1222     handler.struct_fatal(msg).emit();
1223     rustc_errors::FatalError.raise();
1224 }
1225
1226 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1227     let emitter: Box<dyn Emitter + sync::Send> = match output {
1228         config::ErrorOutputType::HumanReadable(kind) => {
1229             let (short, color_config) = kind.unzip();
1230             Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1231         }
1232         config::ErrorOutputType::Json { pretty, json_rendered } => {
1233             Box::new(JsonEmitter::basic(pretty, json_rendered, false))
1234         }
1235     };
1236     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1237     handler.struct_warn(msg).emit();
1238 }
1239
1240 pub type CompileResult = Result<(), ErrorReported>;