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