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