]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_session/src/session.rs
Rollup merge of #90946 - GuillaumeGomez:def-id-remove-weird-case, r=Manishearth
[rust.git] / compiler / rustc_session / src / session.rs
1 use crate::cgu_reuse_tracker::CguReuseTracker;
2 use crate::code_stats::CodeStats;
3 pub use crate::code_stats::{DataTypeKind, FieldInfo, SizeKind, VariantInfo};
4 use crate::config::{self, CrateType, InstrumentCoverage, OptLevel, OutputType, SwitchWithOptPath};
5 use crate::parse::{add_feature_diagnostics, ParseSess};
6 use crate::search_paths::{PathKind, SearchPath};
7 use crate::{filesearch, lint};
8
9 pub use rustc_ast::attr::MarkedAttrs;
10 pub use rustc_ast::Attribute;
11 use rustc_data_structures::flock;
12 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use rustc_data_structures::jobserver::{self, Client};
14 use rustc_data_structures::profiling::{duration_to_secs_str, SelfProfiler, SelfProfilerRef};
15 use rustc_data_structures::sync::{
16     self, AtomicU64, AtomicUsize, Lock, Lrc, OnceCell, OneThread, Ordering, Ordering::SeqCst,
17 };
18 use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitterWriter;
19 use rustc_errors::emitter::{Emitter, EmitterWriter, HumanReadableErrorType};
20 use rustc_errors::json::JsonEmitter;
21 use rustc_errors::registry::Registry;
22 use rustc_errors::{
23     error_code, fallback_fluent_bundle, DiagnosticBuilder, DiagnosticId, DiagnosticMessage,
24     EmissionGuarantee, ErrorGuaranteed, FluentBundle, LazyFallbackBundle, MultiSpan,
25 };
26 use rustc_macros::HashStable_Generic;
27 pub use rustc_span::def_id::StableCrateId;
28 use rustc_span::edition::Edition;
29 use rustc_span::source_map::{FileLoader, RealFileLoader, SourceMap, Span};
30 use rustc_span::{sym, SourceFileHashAlgorithm, Symbol};
31 use rustc_target::asm::InlineAsmArch;
32 use rustc_target::spec::{CodeModel, PanicStrategy, RelocModel, RelroLevel};
33 use rustc_target::spec::{
34     DebuginfoKind, SanitizerSet, SplitDebuginfo, StackProtector, Target, TargetTriple, TlsModel,
35 };
36
37 use std::cell::{self, RefCell};
38 use std::env;
39 use std::fmt;
40 use std::io::Write;
41 use std::ops::{Div, Mul};
42 use std::path::{Path, PathBuf};
43 use std::str::FromStr;
44 use std::sync::Arc;
45 use std::time::Duration;
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 /// The behavior of the CTFE engine when an error occurs with regards to backtraces.
55 #[derive(Clone, Copy)]
56 pub enum CtfeBacktrace {
57     /// Do nothing special, return the error as usual without a backtrace.
58     Disabled,
59     /// Capture a backtrace at the point the error is created and return it in the error
60     /// (to be printed later if/when the error ever actually gets shown to the user).
61     Capture,
62     /// Capture a backtrace at the point the error is created and immediately print it out.
63     Immediate,
64 }
65
66 /// New-type wrapper around `usize` for representing limits. Ensures that comparisons against
67 /// limits are consistent throughout the compiler.
68 #[derive(Clone, Copy, Debug, HashStable_Generic)]
69 pub struct Limit(pub usize);
70
71 impl Limit {
72     /// Create a new limit from a `usize`.
73     pub fn new(value: usize) -> Self {
74         Limit(value)
75     }
76
77     /// Check that `value` is within the limit. Ensures that the same comparisons are used
78     /// throughout the compiler, as mismatches can cause ICEs, see #72540.
79     #[inline]
80     pub fn value_within_limit(&self, value: usize) -> bool {
81         value <= self.0
82     }
83 }
84
85 impl From<usize> for Limit {
86     fn from(value: usize) -> Self {
87         Self::new(value)
88     }
89 }
90
91 impl fmt::Display for Limit {
92     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93         self.0.fmt(f)
94     }
95 }
96
97 impl Div<usize> for Limit {
98     type Output = Limit;
99
100     fn div(self, rhs: usize) -> Self::Output {
101         Limit::new(self.0 / rhs)
102     }
103 }
104
105 impl Mul<usize> for Limit {
106     type Output = Limit;
107
108     fn mul(self, rhs: usize) -> Self::Output {
109         Limit::new(self.0 * rhs)
110     }
111 }
112
113 #[derive(Clone, Copy, Debug, HashStable_Generic)]
114 pub struct Limits {
115     /// The maximum recursion limit for potentially infinitely recursive
116     /// operations such as auto-dereference and monomorphization.
117     pub recursion_limit: Limit,
118     /// The size at which the `large_assignments` lint starts
119     /// being emitted.
120     pub move_size_limit: Limit,
121     /// The maximum length of types during monomorphization.
122     pub type_length_limit: Limit,
123     /// The maximum blocks a const expression can evaluate.
124     pub const_eval_limit: Limit,
125 }
126
127 /// Represents the data associated with a compilation
128 /// session for a single crate.
129 pub struct Session {
130     pub target: Target,
131     pub host: Target,
132     pub opts: config::Options,
133     pub host_tlib_path: Lrc<SearchPath>,
134     pub target_tlib_path: Lrc<SearchPath>,
135     pub parse_sess: ParseSess,
136     pub sysroot: PathBuf,
137     /// The name of the root source file of the crate, in the local file system.
138     /// `None` means that there is no source file.
139     pub local_crate_source_file: Option<PathBuf>,
140
141     crate_types: OnceCell<Vec<CrateType>>,
142     /// The `stable_crate_id` is constructed out of the crate name and all the
143     /// `-C metadata` arguments passed to the compiler. Its value forms a unique
144     /// global identifier for the crate. It is used to allow multiple crates
145     /// with the same name to coexist. See the
146     /// `rustc_codegen_llvm::back::symbol_names` module for more information.
147     pub stable_crate_id: OnceCell<StableCrateId>,
148
149     features: OnceCell<rustc_feature::Features>,
150
151     incr_comp_session: OneThread<RefCell<IncrCompSession>>,
152     /// Used for incremental compilation tests. Will only be populated if
153     /// `-Zquery-dep-graph` is specified.
154     pub cgu_reuse_tracker: CguReuseTracker,
155
156     /// Used by `-Z self-profile`.
157     pub prof: SelfProfilerRef,
158
159     /// Some measurements that are being gathered during compilation.
160     pub perf_stats: PerfStats,
161
162     /// Data about code being compiled, gathered during compilation.
163     pub code_stats: CodeStats,
164
165     /// Tracks fuel info if `-zfuel=crate=n` is specified.
166     optimization_fuel: Lock<OptimizationFuel>,
167
168     /// Always set to zero and incremented so that we can print fuel expended by a crate.
169     pub print_fuel: AtomicU64,
170
171     /// Loaded up early on in the initialization of this `Session` to avoid
172     /// false positives about a job server in our environment.
173     pub jobserver: Client,
174
175     /// Cap lint level specified by a driver specifically.
176     pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
177
178     /// Tracks the current behavior of the CTFE engine when an error occurs.
179     /// Options range from returning the error without a backtrace to returning an error
180     /// and immediately printing the backtrace to stderr.
181     /// The `Lock` is only used by miri to allow setting `ctfe_backtrace` after analysis when
182     /// `MIRI_BACKTRACE` is set. This makes it only apply to miri's errors and not to all CTFE
183     /// errors.
184     pub ctfe_backtrace: Lock<CtfeBacktrace>,
185
186     /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
187     /// const check, optionally with the relevant feature gate.  We use this to
188     /// warn about unleashing, but with a single diagnostic instead of dozens that
189     /// drown everything else in noise.
190     miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
191
192     /// Architecture to use for interpreting asm!.
193     pub asm_arch: Option<InlineAsmArch>,
194
195     /// Set of enabled features for the current target.
196     pub target_features: FxHashSet<Symbol>,
197
198     /// Set of enabled features for the current target, including unstable ones.
199     pub unstable_target_features: FxHashSet<Symbol>,
200 }
201
202 pub struct PerfStats {
203     /// The accumulated time spent on computing symbol hashes.
204     pub symbol_hash_time: Lock<Duration>,
205     /// Total number of values canonicalized queries constructed.
206     pub queries_canonicalized: AtomicUsize,
207     /// Number of times this query is invoked.
208     pub normalize_generic_arg_after_erasing_regions: AtomicUsize,
209     /// Number of times this query is invoked.
210     pub normalize_projection_ty: AtomicUsize,
211 }
212
213 /// Trait implemented by error types. This should not be implemented manually. Instead, use
214 /// `#[derive(SessionDiagnostic)]` -- see [rustc_macros::SessionDiagnostic].
215 #[rustc_diagnostic_item = "SessionDiagnostic"]
216 pub trait SessionDiagnostic<'a, T: EmissionGuarantee = ErrorGuaranteed> {
217     /// Write out as a diagnostic out of `sess`.
218     #[must_use]
219     fn into_diagnostic(self, sess: &'a ParseSess) -> DiagnosticBuilder<'a, T>;
220 }
221
222 impl Session {
223     pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
224         self.miri_unleashed_features.lock().push((span, feature_gate));
225     }
226
227     fn check_miri_unleashed_features(&self) {
228         let unleashed_features = self.miri_unleashed_features.lock();
229         if !unleashed_features.is_empty() {
230             let mut must_err = false;
231             // Create a diagnostic pointing at where things got unleashed.
232             let mut diag = self.struct_warn("skipping const checks");
233             for &(span, feature_gate) in unleashed_features.iter() {
234                 // FIXME: `span_label` doesn't do anything, so we use "help" as a hack.
235                 if let Some(gate) = feature_gate {
236                     diag.span_help(span, &format!("skipping check for `{gate}` feature"));
237                     // The unleash flag must *not* be used to just "hack around" feature gates.
238                     must_err = true;
239                 } else {
240                     diag.span_help(span, "skipping check that does not even have a feature gate");
241                 }
242             }
243             diag.emit();
244             // If we should err, make sure we did.
245             if must_err && self.has_errors().is_none() {
246                 // We have skipped a feature gate, and not run into other errors... reject.
247                 self.err(
248                     "`-Zunleash-the-miri-inside-of-you` may not be used to circumvent feature \
249                      gates, except when testing error paths in the CTFE engine",
250                 );
251             }
252         }
253     }
254
255     /// Invoked all the way at the end to finish off diagnostics printing.
256     pub fn finish_diagnostics(&self, registry: &Registry) {
257         self.check_miri_unleashed_features();
258         self.diagnostic().print_error_count(registry);
259         self.emit_future_breakage();
260     }
261
262     fn emit_future_breakage(&self) {
263         if !self.opts.json_future_incompat {
264             return;
265         }
266
267         let diags = self.diagnostic().take_future_breakage_diagnostics();
268         if diags.is_empty() {
269             return;
270         }
271         self.parse_sess.span_diagnostic.emit_future_breakage_report(diags);
272     }
273
274     pub fn local_stable_crate_id(&self) -> StableCrateId {
275         self.stable_crate_id.get().copied().unwrap()
276     }
277
278     pub fn crate_types(&self) -> &[CrateType] {
279         self.crate_types.get().unwrap().as_slice()
280     }
281
282     pub fn init_crate_types(&self, crate_types: Vec<CrateType>) {
283         self.crate_types.set(crate_types).expect("`crate_types` was initialized twice")
284     }
285
286     #[rustc_lint_diagnostics]
287     pub fn struct_span_warn<S: Into<MultiSpan>>(
288         &self,
289         sp: S,
290         msg: impl Into<DiagnosticMessage>,
291     ) -> DiagnosticBuilder<'_, ()> {
292         self.diagnostic().struct_span_warn(sp, msg)
293     }
294     #[rustc_lint_diagnostics]
295     pub fn struct_span_warn_with_expectation<S: Into<MultiSpan>>(
296         &self,
297         sp: S,
298         msg: impl Into<DiagnosticMessage>,
299         id: lint::LintExpectationId,
300     ) -> DiagnosticBuilder<'_, ()> {
301         self.diagnostic().struct_span_warn_with_expectation(sp, msg, id)
302     }
303     #[rustc_lint_diagnostics]
304     pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
305         &self,
306         sp: S,
307         msg: impl Into<DiagnosticMessage>,
308         code: DiagnosticId,
309     ) -> DiagnosticBuilder<'_, ()> {
310         self.diagnostic().struct_span_warn_with_code(sp, msg, code)
311     }
312     #[rustc_lint_diagnostics]
313     pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
314         self.diagnostic().struct_warn(msg)
315     }
316     #[rustc_lint_diagnostics]
317     pub fn struct_warn_with_expectation(
318         &self,
319         msg: impl Into<DiagnosticMessage>,
320         id: lint::LintExpectationId,
321     ) -> DiagnosticBuilder<'_, ()> {
322         self.diagnostic().struct_warn_with_expectation(msg, id)
323     }
324     #[rustc_lint_diagnostics]
325     pub fn struct_span_allow<S: Into<MultiSpan>>(
326         &self,
327         sp: S,
328         msg: impl Into<DiagnosticMessage>,
329     ) -> DiagnosticBuilder<'_, ()> {
330         self.diagnostic().struct_span_allow(sp, msg)
331     }
332     #[rustc_lint_diagnostics]
333     pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
334         self.diagnostic().struct_allow(msg)
335     }
336     #[rustc_lint_diagnostics]
337     pub fn struct_expect(
338         &self,
339         msg: impl Into<DiagnosticMessage>,
340         id: lint::LintExpectationId,
341     ) -> DiagnosticBuilder<'_, ()> {
342         self.diagnostic().struct_expect(msg, id)
343     }
344     #[rustc_lint_diagnostics]
345     pub fn struct_span_err<S: Into<MultiSpan>>(
346         &self,
347         sp: S,
348         msg: impl Into<DiagnosticMessage>,
349     ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
350         self.diagnostic().struct_span_err(sp, msg)
351     }
352     #[rustc_lint_diagnostics]
353     pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
354         &self,
355         sp: S,
356         msg: impl Into<DiagnosticMessage>,
357         code: DiagnosticId,
358     ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
359         self.diagnostic().struct_span_err_with_code(sp, msg, code)
360     }
361     // FIXME: This method should be removed (every error should have an associated error code).
362     #[rustc_lint_diagnostics]
363     pub fn struct_err(
364         &self,
365         msg: impl Into<DiagnosticMessage>,
366     ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
367         self.parse_sess.struct_err(msg)
368     }
369     #[rustc_lint_diagnostics]
370     pub fn struct_err_with_code(
371         &self,
372         msg: impl Into<DiagnosticMessage>,
373         code: DiagnosticId,
374     ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
375         self.diagnostic().struct_err_with_code(msg, code)
376     }
377     #[rustc_lint_diagnostics]
378     pub fn struct_warn_with_code(
379         &self,
380         msg: impl Into<DiagnosticMessage>,
381         code: DiagnosticId,
382     ) -> DiagnosticBuilder<'_, ()> {
383         self.diagnostic().struct_warn_with_code(msg, code)
384     }
385     #[rustc_lint_diagnostics]
386     pub fn struct_span_fatal<S: Into<MultiSpan>>(
387         &self,
388         sp: S,
389         msg: impl Into<DiagnosticMessage>,
390     ) -> DiagnosticBuilder<'_, !> {
391         self.diagnostic().struct_span_fatal(sp, msg)
392     }
393     #[rustc_lint_diagnostics]
394     pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
395         &self,
396         sp: S,
397         msg: impl Into<DiagnosticMessage>,
398         code: DiagnosticId,
399     ) -> DiagnosticBuilder<'_, !> {
400         self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
401     }
402     #[rustc_lint_diagnostics]
403     pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
404         self.diagnostic().struct_fatal(msg)
405     }
406
407     #[rustc_lint_diagnostics]
408     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) -> ! {
409         self.diagnostic().span_fatal(sp, msg)
410     }
411     #[rustc_lint_diagnostics]
412     pub fn span_fatal_with_code<S: Into<MultiSpan>>(
413         &self,
414         sp: S,
415         msg: impl Into<DiagnosticMessage>,
416         code: DiagnosticId,
417     ) -> ! {
418         self.diagnostic().span_fatal_with_code(sp, msg, code)
419     }
420     #[rustc_lint_diagnostics]
421     pub fn fatal(&self, msg: impl Into<DiagnosticMessage>) -> ! {
422         self.diagnostic().fatal(msg).raise()
423     }
424     #[rustc_lint_diagnostics]
425     pub fn span_err_or_warn<S: Into<MultiSpan>>(
426         &self,
427         is_warning: bool,
428         sp: S,
429         msg: impl Into<DiagnosticMessage>,
430     ) {
431         if is_warning {
432             self.span_warn(sp, msg);
433         } else {
434             self.span_err(sp, msg);
435         }
436     }
437     #[rustc_lint_diagnostics]
438     pub fn span_err<S: Into<MultiSpan>>(
439         &self,
440         sp: S,
441         msg: impl Into<DiagnosticMessage>,
442     ) -> ErrorGuaranteed {
443         self.diagnostic().span_err(sp, msg)
444     }
445     #[rustc_lint_diagnostics]
446     pub fn span_err_with_code<S: Into<MultiSpan>>(
447         &self,
448         sp: S,
449         msg: impl Into<DiagnosticMessage>,
450         code: DiagnosticId,
451     ) {
452         self.diagnostic().span_err_with_code(sp, msg, code)
453     }
454     #[rustc_lint_diagnostics]
455     pub fn err(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
456         self.diagnostic().err(msg)
457     }
458     pub fn create_err<'a>(
459         &'a self,
460         err: impl SessionDiagnostic<'a>,
461     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
462         self.parse_sess.create_err(err)
463     }
464     pub fn create_feature_err<'a>(
465         &'a self,
466         err: impl SessionDiagnostic<'a>,
467         feature: Symbol,
468     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
469         let mut err = self.parse_sess.create_err(err);
470         if err.code.is_none() {
471             err.code = std::option::Option::Some(error_code!(E0658));
472         }
473         add_feature_diagnostics(&mut err, &self.parse_sess, feature);
474         err
475     }
476     pub fn emit_err<'a>(&'a self, err: impl SessionDiagnostic<'a>) -> ErrorGuaranteed {
477         self.parse_sess.emit_err(err)
478     }
479     pub fn create_warning<'a>(
480         &'a self,
481         err: impl SessionDiagnostic<'a, ()>,
482     ) -> DiagnosticBuilder<'a, ()> {
483         self.parse_sess.create_warning(err)
484     }
485     pub fn emit_warning<'a>(&'a self, warning: impl SessionDiagnostic<'a, ()>) {
486         self.parse_sess.emit_warning(warning)
487     }
488     pub fn create_fatal<'a>(
489         &'a self,
490         fatal: impl SessionDiagnostic<'a, !>,
491     ) -> DiagnosticBuilder<'a, !> {
492         self.parse_sess.create_fatal(fatal)
493     }
494     pub fn emit_fatal<'a>(&'a self, fatal: impl SessionDiagnostic<'a, !>) -> ! {
495         self.parse_sess.emit_fatal(fatal)
496     }
497     #[inline]
498     pub fn err_count(&self) -> usize {
499         self.diagnostic().err_count()
500     }
501     pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
502         self.diagnostic().has_errors()
503     }
504     pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
505         self.diagnostic().has_errors_or_delayed_span_bugs()
506     }
507     pub fn abort_if_errors(&self) {
508         self.diagnostic().abort_if_errors();
509     }
510     pub fn compile_status(&self) -> Result<(), ErrorGuaranteed> {
511         if let Some(reported) = self.diagnostic().has_errors_or_lint_errors() {
512             let _ = self.diagnostic().emit_stashed_diagnostics();
513             Err(reported)
514         } else {
515             Ok(())
516         }
517     }
518     // FIXME(matthewjasper) Remove this method, it should never be needed.
519     pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorGuaranteed>
520     where
521         F: FnOnce() -> T,
522     {
523         let old_count = self.err_count();
524         let result = f();
525         if self.err_count() == old_count {
526             Ok(result)
527         } else {
528             Err(ErrorGuaranteed::unchecked_claim_error_was_emitted())
529         }
530     }
531     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) {
532         self.diagnostic().span_warn(sp, msg)
533     }
534     pub fn span_warn_with_code<S: Into<MultiSpan>>(
535         &self,
536         sp: S,
537         msg: impl Into<DiagnosticMessage>,
538         code: DiagnosticId,
539     ) {
540         self.diagnostic().span_warn_with_code(sp, msg, code)
541     }
542     pub fn warn(&self, msg: impl Into<DiagnosticMessage>) {
543         self.diagnostic().warn(msg)
544     }
545     /// Delay a span_bug() call until abort_if_errors()
546     #[track_caller]
547     pub fn delay_span_bug<S: Into<MultiSpan>>(
548         &self,
549         sp: S,
550         msg: impl Into<DiagnosticMessage>,
551     ) -> ErrorGuaranteed {
552         self.diagnostic().delay_span_bug(sp, msg)
553     }
554
555     /// Used for code paths of expensive computations that should only take place when
556     /// warnings or errors are emitted. If no messages are emitted ("good path"), then
557     /// it's likely a bug.
558     pub fn delay_good_path_bug(&self, msg: impl Into<DiagnosticMessage>) {
559         if self.opts.unstable_opts.print_type_sizes
560             || self.opts.unstable_opts.query_dep_graph
561             || self.opts.unstable_opts.dump_mir.is_some()
562             || self.opts.unstable_opts.unpretty.is_some()
563             || self.opts.output_types.contains_key(&OutputType::Mir)
564             || std::env::var_os("RUSTC_LOG").is_some()
565         {
566             return;
567         }
568
569         self.diagnostic().delay_good_path_bug(msg)
570     }
571
572     pub fn note_without_error(&self, msg: impl Into<DiagnosticMessage>) {
573         self.diagnostic().note_without_error(msg)
574     }
575     pub fn span_note_without_error<S: Into<MultiSpan>>(
576         &self,
577         sp: S,
578         msg: impl Into<DiagnosticMessage>,
579     ) {
580         self.diagnostic().span_note_without_error(sp, msg)
581     }
582     pub fn struct_note_without_error(
583         &self,
584         msg: impl Into<DiagnosticMessage>,
585     ) -> DiagnosticBuilder<'_, ()> {
586         self.diagnostic().struct_note_without_error(msg)
587     }
588
589     #[inline]
590     pub fn diagnostic(&self) -> &rustc_errors::Handler {
591         &self.parse_sess.span_diagnostic
592     }
593
594     #[inline]
595     pub fn source_map(&self) -> &SourceMap {
596         self.parse_sess.source_map()
597     }
598
599     pub fn time_passes(&self) -> bool {
600         self.opts.time_passes()
601     }
602
603     /// Returns `true` if internal lints should be added to the lint store - i.e. if
604     /// `-Zunstable-options` is provided and this isn't rustdoc (internal lints can trigger errors
605     /// to be emitted under rustdoc).
606     pub fn enable_internal_lints(&self) -> bool {
607         self.unstable_options() && !self.opts.actually_rustdoc
608     }
609
610     pub fn instrument_coverage(&self) -> bool {
611         self.opts.cg.instrument_coverage() != InstrumentCoverage::Off
612     }
613
614     pub fn instrument_coverage_except_unused_generics(&self) -> bool {
615         self.opts.cg.instrument_coverage() == InstrumentCoverage::ExceptUnusedGenerics
616     }
617
618     pub fn instrument_coverage_except_unused_functions(&self) -> bool {
619         self.opts.cg.instrument_coverage() == InstrumentCoverage::ExceptUnusedFunctions
620     }
621
622     /// Gets the features enabled for the current compilation session.
623     /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
624     /// dependency tracking. Use tcx.features() instead.
625     #[inline]
626     pub fn features_untracked(&self) -> &rustc_feature::Features {
627         self.features.get().unwrap()
628     }
629
630     pub fn init_features(&self, features: rustc_feature::Features) {
631         match self.features.set(features) {
632             Ok(()) => {}
633             Err(_) => panic!("`features` was initialized twice"),
634         }
635     }
636
637     pub fn is_sanitizer_cfi_enabled(&self) -> bool {
638         self.opts.unstable_opts.sanitizer.contains(SanitizerSet::CFI)
639     }
640
641     /// Check whether this compile session and crate type use static crt.
642     pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
643         if !self.target.crt_static_respected {
644             // If the target does not opt in to crt-static support, use its default.
645             return self.target.crt_static_default;
646         }
647
648         let requested_features = self.opts.cg.target_feature.split(',');
649         let found_negative = requested_features.clone().any(|r| r == "-crt-static");
650         let found_positive = requested_features.clone().any(|r| r == "+crt-static");
651
652         // JUSTIFICATION: necessary use of crate_types directly (see FIXME below)
653         #[allow(rustc::bad_opt_access)]
654         if found_positive || found_negative {
655             found_positive
656         } else if crate_type == Some(CrateType::ProcMacro)
657             || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
658         {
659             // FIXME: When crate_type is not available,
660             // we use compiler options to determine the crate_type.
661             // We can't check `#![crate_type = "proc-macro"]` here.
662             false
663         } else {
664             self.target.crt_static_default
665         }
666     }
667
668     pub fn is_wasi_reactor(&self) -> bool {
669         self.target.options.os == "wasi"
670             && matches!(
671                 self.opts.unstable_opts.wasi_exec_model,
672                 Some(config::WasiExecModel::Reactor)
673             )
674     }
675
676     /// Returns `true` if the target can use the current split debuginfo configuration.
677     pub fn target_can_use_split_dwarf(&self) -> bool {
678         self.target.debuginfo_kind == DebuginfoKind::Dwarf
679     }
680
681     pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
682         format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.to_u64())
683     }
684
685     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
686         filesearch::FileSearch::new(
687             &self.sysroot,
688             self.opts.target_triple.triple(),
689             &self.opts.search_paths,
690             &self.target_tlib_path,
691             kind,
692         )
693     }
694     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
695         filesearch::FileSearch::new(
696             &self.sysroot,
697             config::host_triple(),
698             &self.opts.search_paths,
699             &self.host_tlib_path,
700             kind,
701         )
702     }
703
704     /// Returns a list of directories where target-specific tool binaries are located.
705     pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
706         let rustlib_path = rustc_target::target_rustlib_path(&self.sysroot, &config::host_triple());
707         let p = PathBuf::from_iter([
708             Path::new(&self.sysroot),
709             Path::new(&rustlib_path),
710             Path::new("bin"),
711         ]);
712         if self_contained { vec![p.clone(), p.join("self-contained")] } else { vec![p] }
713     }
714
715     pub fn init_incr_comp_session(
716         &self,
717         session_dir: PathBuf,
718         lock_file: flock::Lock,
719         load_dep_graph: bool,
720     ) {
721         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
722
723         if let IncrCompSession::NotInitialized = *incr_comp_session {
724         } else {
725             panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
726         }
727
728         *incr_comp_session =
729             IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
730     }
731
732     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
733         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
734
735         if let IncrCompSession::Active { .. } = *incr_comp_session {
736         } else {
737             panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
738         }
739
740         // Note: this will also drop the lock file, thus unlocking the directory.
741         *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
742     }
743
744     pub fn mark_incr_comp_session_as_invalid(&self) {
745         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
746
747         let session_directory = match *incr_comp_session {
748             IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
749             IncrCompSession::InvalidBecauseOfErrors { .. } => return,
750             _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
751         };
752
753         // Note: this will also drop the lock file, thus unlocking the directory.
754         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
755     }
756
757     pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
758         let incr_comp_session = self.incr_comp_session.borrow();
759         cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
760             IncrCompSession::NotInitialized => panic!(
761                 "trying to get session directory from `IncrCompSession`: {:?}",
762                 *incr_comp_session,
763             ),
764             IncrCompSession::Active { ref session_directory, .. }
765             | IncrCompSession::Finalized { ref session_directory }
766             | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
767                 session_directory
768             }
769         })
770     }
771
772     pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
773         self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
774     }
775
776     pub fn print_perf_stats(&self) {
777         eprintln!(
778             "Total time spent computing symbol hashes:      {}",
779             duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
780         );
781         eprintln!(
782             "Total queries canonicalized:                   {}",
783             self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
784         );
785         eprintln!(
786             "normalize_generic_arg_after_erasing_regions:   {}",
787             self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
788         );
789         eprintln!(
790             "normalize_projection_ty:                       {}",
791             self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
792         );
793     }
794
795     /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
796     /// This expends fuel if applicable, and records fuel if applicable.
797     pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
798         let mut ret = true;
799         if let Some((ref c, _)) = self.opts.unstable_opts.fuel {
800             if c == crate_name {
801                 assert_eq!(self.threads(), 1);
802                 let mut fuel = self.optimization_fuel.lock();
803                 ret = fuel.remaining != 0;
804                 if fuel.remaining == 0 && !fuel.out_of_fuel {
805                     if self.diagnostic().can_emit_warnings() {
806                         // We only call `msg` in case we can actually emit warnings.
807                         // Otherwise, this could cause a `delay_good_path_bug` to
808                         // trigger (issue #79546).
809                         self.warn(&format!("optimization-fuel-exhausted: {}", msg()));
810                     }
811                     fuel.out_of_fuel = true;
812                 } else if fuel.remaining > 0 {
813                     fuel.remaining -= 1;
814                 }
815             }
816         }
817         if let Some(ref c) = self.opts.unstable_opts.print_fuel {
818             if c == crate_name {
819                 assert_eq!(self.threads(), 1);
820                 self.print_fuel.fetch_add(1, SeqCst);
821             }
822         }
823         ret
824     }
825
826     pub fn rust_2015(&self) -> bool {
827         self.edition() == Edition::Edition2015
828     }
829
830     /// Are we allowed to use features from the Rust 2018 edition?
831     pub fn rust_2018(&self) -> bool {
832         self.edition() >= Edition::Edition2018
833     }
834
835     /// Are we allowed to use features from the Rust 2021 edition?
836     pub fn rust_2021(&self) -> bool {
837         self.edition() >= Edition::Edition2021
838     }
839
840     /// Are we allowed to use features from the Rust 2024 edition?
841     pub fn rust_2024(&self) -> bool {
842         self.edition() >= Edition::Edition2024
843     }
844
845     /// Returns `true` if we cannot skip the PLT for shared library calls.
846     pub fn needs_plt(&self) -> bool {
847         // Check if the current target usually needs PLT to be enabled.
848         // The user can use the command line flag to override it.
849         let needs_plt = self.target.needs_plt;
850
851         let dbg_opts = &self.opts.unstable_opts;
852
853         let relro_level = dbg_opts.relro_level.unwrap_or(self.target.relro_level);
854
855         // Only enable this optimization by default if full relro is also enabled.
856         // In this case, lazy binding was already unavailable, so nothing is lost.
857         // This also ensures `-Wl,-z,now` is supported by the linker.
858         let full_relro = RelroLevel::Full == relro_level;
859
860         // If user didn't explicitly forced us to use / skip the PLT,
861         // then try to skip it where possible.
862         dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
863     }
864
865     /// Checks if LLVM lifetime markers should be emitted.
866     pub fn emit_lifetime_markers(&self) -> bool {
867         self.opts.optimize != config::OptLevel::No
868         // AddressSanitizer uses lifetimes to detect use after scope bugs.
869         // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
870         // HWAddressSanitizer will use lifetimes to detect use after scope bugs in the future.
871         || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
872     }
873
874     pub fn is_proc_macro_attr(&self, attr: &Attribute) -> bool {
875         [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
876             .iter()
877             .any(|kind| attr.has_name(*kind))
878     }
879
880     pub fn contains_name(&self, attrs: &[Attribute], name: Symbol) -> bool {
881         attrs.iter().any(|item| item.has_name(name))
882     }
883
884     pub fn find_by_name<'a>(
885         &'a self,
886         attrs: &'a [Attribute],
887         name: Symbol,
888     ) -> Option<&'a Attribute> {
889         attrs.iter().find(|attr| attr.has_name(name))
890     }
891
892     pub fn filter_by_name<'a>(
893         &'a self,
894         attrs: &'a [Attribute],
895         name: Symbol,
896     ) -> impl Iterator<Item = &'a Attribute> {
897         attrs.iter().filter(move |attr| attr.has_name(name))
898     }
899
900     pub fn first_attr_value_str_by_name(
901         &self,
902         attrs: &[Attribute],
903         name: Symbol,
904     ) -> Option<Symbol> {
905         attrs.iter().find(|at| at.has_name(name)).and_then(|at| at.value_str())
906     }
907 }
908
909 // JUSTIFICATION: defn of the suggested wrapper fns
910 #[allow(rustc::bad_opt_access)]
911 impl Session {
912     pub fn verbose(&self) -> bool {
913         self.opts.unstable_opts.verbose
914     }
915
916     pub fn instrument_mcount(&self) -> bool {
917         self.opts.unstable_opts.instrument_mcount
918     }
919
920     pub fn time_llvm_passes(&self) -> bool {
921         self.opts.unstable_opts.time_llvm_passes
922     }
923
924     pub fn meta_stats(&self) -> bool {
925         self.opts.unstable_opts.meta_stats
926     }
927
928     pub fn asm_comments(&self) -> bool {
929         self.opts.unstable_opts.asm_comments
930     }
931
932     pub fn verify_llvm_ir(&self) -> bool {
933         self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
934     }
935
936     pub fn print_llvm_passes(&self) -> bool {
937         self.opts.unstable_opts.print_llvm_passes
938     }
939
940     pub fn binary_dep_depinfo(&self) -> bool {
941         self.opts.unstable_opts.binary_dep_depinfo
942     }
943
944     pub fn mir_opt_level(&self) -> usize {
945         self.opts
946             .unstable_opts
947             .mir_opt_level
948             .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
949     }
950
951     /// Calculates the flavor of LTO to use for this compilation.
952     pub fn lto(&self) -> config::Lto {
953         // If our target has codegen requirements ignore the command line
954         if self.target.requires_lto {
955             return config::Lto::Fat;
956         }
957
958         // If the user specified something, return that. If they only said `-C
959         // lto` and we've for whatever reason forced off ThinLTO via the CLI,
960         // then ensure we can't use a ThinLTO.
961         match self.opts.cg.lto {
962             config::LtoCli::Unspecified => {
963                 // The compiler was invoked without the `-Clto` flag. Fall
964                 // through to the default handling
965             }
966             config::LtoCli::No => {
967                 // The user explicitly opted out of any kind of LTO
968                 return config::Lto::No;
969             }
970             config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
971                 // All of these mean fat LTO
972                 return config::Lto::Fat;
973             }
974             config::LtoCli::Thin => {
975                 return if self.opts.cli_forced_thinlto_off {
976                     config::Lto::Fat
977                 } else {
978                     config::Lto::Thin
979                 };
980             }
981         }
982
983         // Ok at this point the target doesn't require anything and the user
984         // hasn't asked for anything. Our next decision is whether or not
985         // we enable "auto" ThinLTO where we use multiple codegen units and
986         // then do ThinLTO over those codegen units. The logic below will
987         // either return `No` or `ThinLocal`.
988
989         // If processing command line options determined that we're incompatible
990         // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
991         if self.opts.cli_forced_thinlto_off {
992             return config::Lto::No;
993         }
994
995         // If `-Z thinlto` specified process that, but note that this is mostly
996         // a deprecated option now that `-C lto=thin` exists.
997         if let Some(enabled) = self.opts.unstable_opts.thinlto {
998             if enabled {
999                 return config::Lto::ThinLocal;
1000             } else {
1001                 return config::Lto::No;
1002             }
1003         }
1004
1005         // If there's only one codegen unit and LTO isn't enabled then there's
1006         // no need for ThinLTO so just return false.
1007         if self.codegen_units() == 1 {
1008             return config::Lto::No;
1009         }
1010
1011         // Now we're in "defaults" territory. By default we enable ThinLTO for
1012         // optimized compiles (anything greater than O0).
1013         match self.opts.optimize {
1014             config::OptLevel::No => config::Lto::No,
1015             _ => config::Lto::ThinLocal,
1016         }
1017     }
1018
1019     /// Returns the panic strategy for this compile session. If the user explicitly selected one
1020     /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
1021     pub fn panic_strategy(&self) -> PanicStrategy {
1022         self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
1023     }
1024
1025     pub fn fewer_names(&self) -> bool {
1026         if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
1027             fewer_names
1028         } else {
1029             let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
1030                 || self.opts.output_types.contains_key(&OutputType::Bitcode)
1031                 // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
1032                 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
1033             !more_names
1034         }
1035     }
1036
1037     pub fn unstable_options(&self) -> bool {
1038         self.opts.unstable_opts.unstable_options
1039     }
1040
1041     pub fn is_nightly_build(&self) -> bool {
1042         self.opts.unstable_features.is_nightly_build()
1043     }
1044
1045     pub fn overflow_checks(&self) -> bool {
1046         self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
1047     }
1048
1049     pub fn relocation_model(&self) -> RelocModel {
1050         self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
1051     }
1052
1053     pub fn code_model(&self) -> Option<CodeModel> {
1054         self.opts.cg.code_model.or(self.target.code_model)
1055     }
1056
1057     pub fn tls_model(&self) -> TlsModel {
1058         self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
1059     }
1060
1061     pub fn split_debuginfo(&self) -> SplitDebuginfo {
1062         self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
1063     }
1064
1065     pub fn stack_protector(&self) -> StackProtector {
1066         if self.target.options.supports_stack_protector {
1067             self.opts.unstable_opts.stack_protector
1068         } else {
1069             StackProtector::None
1070         }
1071     }
1072
1073     pub fn must_emit_unwind_tables(&self) -> bool {
1074         // This is used to control the emission of the `uwtable` attribute on
1075         // LLVM functions.
1076         //
1077         // Unwind tables are needed when compiling with `-C panic=unwind`, but
1078         // LLVM won't omit unwind tables unless the function is also marked as
1079         // `nounwind`, so users are allowed to disable `uwtable` emission.
1080         // Historically rustc always emits `uwtable` attributes by default, so
1081         // even they can be disabled, they're still emitted by default.
1082         //
1083         // On some targets (including windows), however, exceptions include
1084         // other events such as illegal instructions, segfaults, etc. This means
1085         // that on Windows we end up still needing unwind tables even if the `-C
1086         // panic=abort` flag is passed.
1087         //
1088         // You can also find more info on why Windows needs unwind tables in:
1089         //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
1090         //
1091         // If a target requires unwind tables, then they must be emitted.
1092         // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
1093         // value, if it is provided, or disable them, if not.
1094         self.target.requires_uwtable
1095             || self.opts.cg.force_unwind_tables.unwrap_or(
1096                 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
1097             )
1098     }
1099
1100     /// Returns the number of query threads that should be used for this
1101     /// compilation
1102     pub fn threads(&self) -> usize {
1103         self.opts.unstable_opts.threads
1104     }
1105
1106     /// Returns the number of codegen units that should be used for this
1107     /// compilation
1108     pub fn codegen_units(&self) -> usize {
1109         if let Some(n) = self.opts.cli_forced_codegen_units {
1110             return n;
1111         }
1112         if let Some(n) = self.target.default_codegen_units {
1113             return n as usize;
1114         }
1115
1116         // If incremental compilation is turned on, we default to a high number
1117         // codegen units in order to reduce the "collateral damage" small
1118         // changes cause.
1119         if self.opts.incremental.is_some() {
1120             return 256;
1121         }
1122
1123         // Why is 16 codegen units the default all the time?
1124         //
1125         // The main reason for enabling multiple codegen units by default is to
1126         // leverage the ability for the codegen backend to do codegen and
1127         // optimization in parallel. This allows us, especially for large crates, to
1128         // make good use of all available resources on the machine once we've
1129         // hit that stage of compilation. Large crates especially then often
1130         // take a long time in codegen/optimization and this helps us amortize that
1131         // cost.
1132         //
1133         // Note that a high number here doesn't mean that we'll be spawning a
1134         // large number of threads in parallel. The backend of rustc contains
1135         // global rate limiting through the `jobserver` crate so we'll never
1136         // overload the system with too much work, but rather we'll only be
1137         // optimizing when we're otherwise cooperating with other instances of
1138         // rustc.
1139         //
1140         // Rather a high number here means that we should be able to keep a lot
1141         // of idle cpus busy. By ensuring that no codegen unit takes *too* long
1142         // to build we'll be guaranteed that all cpus will finish pretty closely
1143         // to one another and we should make relatively optimal use of system
1144         // resources
1145         //
1146         // Note that the main cost of codegen units is that it prevents LLVM
1147         // from inlining across codegen units. Users in general don't have a lot
1148         // of control over how codegen units are split up so it's our job in the
1149         // compiler to ensure that undue performance isn't lost when using
1150         // codegen units (aka we can't require everyone to slap `#[inline]` on
1151         // everything).
1152         //
1153         // If we're compiling at `-O0` then the number doesn't really matter too
1154         // much because performance doesn't matter and inlining is ok to lose.
1155         // In debug mode we just want to try to guarantee that no cpu is stuck
1156         // doing work that could otherwise be farmed to others.
1157         //
1158         // In release mode, however (O1 and above) performance does indeed
1159         // matter! To recover the loss in performance due to inlining we'll be
1160         // enabling ThinLTO by default (the function for which is just below).
1161         // This will ensure that we recover any inlining wins we otherwise lost
1162         // through codegen unit partitioning.
1163         //
1164         // ---
1165         //
1166         // Ok that's a lot of words but the basic tl;dr; is that we want a high
1167         // number here -- but not too high. Additionally we're "safe" to have it
1168         // always at the same number at all optimization levels.
1169         //
1170         // As a result 16 was chosen here! Mostly because it was a power of 2
1171         // and most benchmarks agreed it was roughly a local optimum. Not very
1172         // scientific.
1173         16
1174     }
1175
1176     pub fn teach(&self, code: &DiagnosticId) -> bool {
1177         self.opts.unstable_opts.teach && self.diagnostic().must_teach(code)
1178     }
1179
1180     pub fn edition(&self) -> Edition {
1181         self.opts.edition
1182     }
1183
1184     pub fn link_dead_code(&self) -> bool {
1185         self.opts.cg.link_dead_code.unwrap_or(false)
1186     }
1187 }
1188
1189 // JUSTIFICATION: part of session construction
1190 #[allow(rustc::bad_opt_access)]
1191 fn default_emitter(
1192     sopts: &config::Options,
1193     registry: rustc_errors::registry::Registry,
1194     source_map: Lrc<SourceMap>,
1195     bundle: Option<Lrc<FluentBundle>>,
1196     fallback_bundle: LazyFallbackBundle,
1197     emitter_dest: Option<Box<dyn Write + Send>>,
1198 ) -> Box<dyn Emitter + sync::Send> {
1199     let macro_backtrace = sopts.unstable_opts.macro_backtrace;
1200     match (sopts.error_format, emitter_dest) {
1201         (config::ErrorOutputType::HumanReadable(kind), dst) => {
1202             let (short, color_config) = kind.unzip();
1203
1204             if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1205                 let emitter = AnnotateSnippetEmitterWriter::new(
1206                     Some(source_map),
1207                     bundle,
1208                     fallback_bundle,
1209                     short,
1210                     macro_backtrace,
1211                 );
1212                 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1213             } else {
1214                 let emitter = match dst {
1215                     None => EmitterWriter::stderr(
1216                         color_config,
1217                         Some(source_map),
1218                         bundle,
1219                         fallback_bundle,
1220                         short,
1221                         sopts.unstable_opts.teach,
1222                         sopts.diagnostic_width,
1223                         macro_backtrace,
1224                     ),
1225                     Some(dst) => EmitterWriter::new(
1226                         dst,
1227                         Some(source_map),
1228                         bundle,
1229                         fallback_bundle,
1230                         short,
1231                         false, // no teach messages when writing to a buffer
1232                         false, // no colors when writing to a buffer
1233                         None,  // no diagnostic width
1234                         macro_backtrace,
1235                     ),
1236                 };
1237                 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1238             }
1239         }
1240         (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
1241             JsonEmitter::stderr(
1242                 Some(registry),
1243                 source_map,
1244                 bundle,
1245                 fallback_bundle,
1246                 pretty,
1247                 json_rendered,
1248                 sopts.diagnostic_width,
1249                 macro_backtrace,
1250             )
1251             .ui_testing(sopts.unstable_opts.ui_testing),
1252         ),
1253         (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
1254             JsonEmitter::new(
1255                 dst,
1256                 Some(registry),
1257                 source_map,
1258                 bundle,
1259                 fallback_bundle,
1260                 pretty,
1261                 json_rendered,
1262                 sopts.diagnostic_width,
1263                 macro_backtrace,
1264             )
1265             .ui_testing(sopts.unstable_opts.ui_testing),
1266         ),
1267     }
1268 }
1269
1270 pub enum DiagnosticOutput {
1271     Default,
1272     Raw(Box<dyn Write + Send>),
1273 }
1274
1275 // JUSTIFICATION: literally session construction
1276 #[allow(rustc::bad_opt_access)]
1277 pub fn build_session(
1278     sopts: config::Options,
1279     local_crate_source_file: Option<PathBuf>,
1280     bundle: Option<Lrc<rustc_errors::FluentBundle>>,
1281     registry: rustc_errors::registry::Registry,
1282     diagnostics_output: DiagnosticOutput,
1283     driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1284     file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1285     target_override: Option<Target>,
1286 ) -> Session {
1287     // FIXME: This is not general enough to make the warning lint completely override
1288     // normal diagnostic warnings, since the warning lint can also be denied and changed
1289     // later via the source code.
1290     let warnings_allow = sopts
1291         .lint_opts
1292         .iter()
1293         .filter(|&&(ref key, _)| *key == "warnings")
1294         .map(|&(_, ref level)| *level == lint::Allow)
1295         .last()
1296         .unwrap_or(false);
1297     let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1298     let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1299
1300     let write_dest = match diagnostics_output {
1301         DiagnosticOutput::Default => None,
1302         DiagnosticOutput::Raw(write) => Some(write),
1303     };
1304
1305     let sysroot = match &sopts.maybe_sysroot {
1306         Some(sysroot) => sysroot.clone(),
1307         None => filesearch::get_or_default_sysroot(),
1308     };
1309
1310     let target_cfg = config::build_target_config(&sopts, target_override, &sysroot);
1311     let host_triple = TargetTriple::from_triple(config::host_triple());
1312     let (host, target_warnings) = Target::search(&host_triple, &sysroot).unwrap_or_else(|e| {
1313         early_error(sopts.error_format, &format!("Error loading host specification: {e}"))
1314     });
1315     for warning in target_warnings.warning_messages() {
1316         early_warn(sopts.error_format, &warning)
1317     }
1318
1319     let loader = file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
1320     let hash_kind = sopts.unstable_opts.src_hash_algorithm.unwrap_or_else(|| {
1321         if target_cfg.is_like_msvc {
1322             SourceFileHashAlgorithm::Sha1
1323         } else {
1324             SourceFileHashAlgorithm::Md5
1325         }
1326     });
1327     let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1328         loader,
1329         sopts.file_path_mapping(),
1330         hash_kind,
1331     ));
1332
1333     let fallback_bundle = fallback_fluent_bundle(
1334         rustc_errors::DEFAULT_LOCALE_RESOURCES,
1335         sopts.unstable_opts.translate_directionality_markers,
1336     );
1337     let emitter =
1338         default_emitter(&sopts, registry, source_map.clone(), bundle, fallback_bundle, write_dest);
1339
1340     let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1341         emitter,
1342         sopts.unstable_opts.diagnostic_handler_flags(can_emit_warnings),
1343     );
1344
1345     let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1346     {
1347         let directory =
1348             if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1349
1350         let profiler = SelfProfiler::new(
1351             directory,
1352             sopts.crate_name.as_deref(),
1353             sopts.unstable_opts.self_profile_events.as_ref().map(|xs| &xs[..]),
1354             &sopts.unstable_opts.self_profile_counter,
1355         );
1356         match profiler {
1357             Ok(profiler) => Some(Arc::new(profiler)),
1358             Err(e) => {
1359                 early_warn(sopts.error_format, &format!("failed to create profiler: {e}"));
1360                 None
1361             }
1362         }
1363     } else {
1364         None
1365     };
1366
1367     let mut parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
1368     parse_sess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1369
1370     let host_triple = config::host_triple();
1371     let target_triple = sopts.target_triple.triple();
1372     let host_tlib_path = Lrc::new(SearchPath::from_sysroot_and_triple(&sysroot, host_triple));
1373     let target_tlib_path = if host_triple == target_triple {
1374         // Use the same `SearchPath` if host and target triple are identical to avoid unnecessary
1375         // rescanning of the target lib path and an unnecessary allocation.
1376         host_tlib_path.clone()
1377     } else {
1378         Lrc::new(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1379     };
1380
1381     let file_path_mapping = sopts.file_path_mapping();
1382
1383     let local_crate_source_file =
1384         local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1385
1386     let optimization_fuel = Lock::new(OptimizationFuel {
1387         remaining: sopts.unstable_opts.fuel.as_ref().map_or(0, |i| i.1),
1388         out_of_fuel: false,
1389     });
1390     let print_fuel = AtomicU64::new(0);
1391
1392     let cgu_reuse_tracker = if sopts.unstable_opts.query_dep_graph {
1393         CguReuseTracker::new()
1394     } else {
1395         CguReuseTracker::new_disabled()
1396     };
1397
1398     let prof =
1399         SelfProfilerRef::new(self_profiler, sopts.time_passes(), sopts.unstable_opts.time_passes);
1400
1401     let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1402         Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1403         Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1404         _ => CtfeBacktrace::Disabled,
1405     });
1406
1407     let asm_arch =
1408         if target_cfg.allow_asm { InlineAsmArch::from_str(&target_cfg.arch).ok() } else { None };
1409
1410     let sess = Session {
1411         target: target_cfg,
1412         host,
1413         opts: sopts,
1414         host_tlib_path,
1415         target_tlib_path,
1416         parse_sess,
1417         sysroot,
1418         local_crate_source_file,
1419         crate_types: OnceCell::new(),
1420         stable_crate_id: OnceCell::new(),
1421         features: OnceCell::new(),
1422         incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1423         cgu_reuse_tracker,
1424         prof,
1425         perf_stats: PerfStats {
1426             symbol_hash_time: Lock::new(Duration::from_secs(0)),
1427             queries_canonicalized: AtomicUsize::new(0),
1428             normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1429             normalize_projection_ty: AtomicUsize::new(0),
1430         },
1431         code_stats: Default::default(),
1432         optimization_fuel,
1433         print_fuel,
1434         jobserver: jobserver::client(),
1435         driver_lint_caps,
1436         ctfe_backtrace,
1437         miri_unleashed_features: Lock::new(Default::default()),
1438         asm_arch,
1439         target_features: FxHashSet::default(),
1440         unstable_target_features: FxHashSet::default(),
1441     };
1442
1443     validate_commandline_args_with_session_available(&sess);
1444
1445     sess
1446 }
1447
1448 /// Validate command line arguments with a `Session`.
1449 ///
1450 /// If it is useful to have a Session available already for validating a commandline argument, you
1451 /// can do so here.
1452 // JUSTIFICATION: needs to access args to validate them
1453 #[allow(rustc::bad_opt_access)]
1454 fn validate_commandline_args_with_session_available(sess: &Session) {
1455     // Since we don't know if code in an rlib will be linked to statically or
1456     // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1457     // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1458     // these manually generated symbols confuse LLD when it tries to merge
1459     // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1460     // when compiling for LLD ThinLTO. This way we can validly just not generate
1461     // the `dllimport` attributes and `__imp_` symbols in that case.
1462     if sess.opts.cg.linker_plugin_lto.enabled()
1463         && sess.opts.cg.prefer_dynamic
1464         && sess.target.is_like_windows
1465     {
1466         sess.err(
1467             "Linker plugin based LTO is not supported together with \
1468                   `-C prefer-dynamic` when targeting Windows-like targets",
1469         );
1470     }
1471
1472     // Make sure that any given profiling data actually exists so LLVM can't
1473     // decide to silently skip PGO.
1474     if let Some(ref path) = sess.opts.cg.profile_use {
1475         if !path.exists() {
1476             sess.err(&format!(
1477                 "File `{}` passed to `-C profile-use` does not exist.",
1478                 path.display()
1479             ));
1480         }
1481     }
1482
1483     // Do the same for sample profile data.
1484     if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1485         if !path.exists() {
1486             sess.err(&format!(
1487                 "File `{}` passed to `-C profile-sample-use` does not exist.",
1488                 path.display()
1489             ));
1490         }
1491     }
1492
1493     // Unwind tables cannot be disabled if the target requires them.
1494     if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1495         if sess.target.requires_uwtable && !include_uwtables {
1496             sess.err(
1497                 "target requires unwind tables, they cannot be disabled with \
1498                      `-C force-unwind-tables=no`.",
1499             );
1500         }
1501     }
1502
1503     // Sanitizers can only be used on platforms that we know have working sanitizer codegen.
1504     let supported_sanitizers = sess.target.options.supported_sanitizers;
1505     let unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1506     match unsupported_sanitizers.into_iter().count() {
1507         0 => {}
1508         1 => {
1509             sess.err(&format!(
1510                 "{} sanitizer is not supported for this target",
1511                 unsupported_sanitizers
1512             ));
1513         }
1514         _ => {
1515             sess.err(&format!(
1516                 "{} sanitizers are not supported for this target",
1517                 unsupported_sanitizers
1518             ));
1519         }
1520     }
1521     // Cannot mix and match sanitizers.
1522     let mut sanitizer_iter = sess.opts.unstable_opts.sanitizer.into_iter();
1523     if let (Some(first), Some(second)) = (sanitizer_iter.next(), sanitizer_iter.next()) {
1524         sess.err(&format!("`-Zsanitizer={first}` is incompatible with `-Zsanitizer={second}`"));
1525     }
1526
1527     // Cannot enable crt-static with sanitizers on Linux
1528     if sess.crt_static(None) && !sess.opts.unstable_opts.sanitizer.is_empty() {
1529         sess.err(
1530             "sanitizer is incompatible with statically linked libc, \
1531                                 disable it using `-C target-feature=-crt-static`",
1532         );
1533     }
1534
1535     // LLVM CFI and VFE both require LTO.
1536     if sess.lto() != config::Lto::Fat {
1537         if sess.is_sanitizer_cfi_enabled() {
1538             sess.err("`-Zsanitizer=cfi` requires `-Clto`");
1539         }
1540         if sess.opts.unstable_opts.virtual_function_elimination {
1541             sess.err("`-Zvirtual-function-elimination` requires `-Clto`");
1542         }
1543     }
1544
1545     if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1546         if !sess.target.options.supports_stack_protector {
1547             sess.warn(&format!(
1548                 "`-Z stack-protector={}` is not supported for target {} and will be ignored",
1549                 sess.opts.unstable_opts.stack_protector, sess.opts.target_triple
1550             ))
1551         }
1552     }
1553
1554     if let Some(dwarf_version) = sess.opts.unstable_opts.dwarf_version {
1555         if dwarf_version > 5 {
1556             sess.err(&format!("requested DWARF version {} is greater than 5", dwarf_version));
1557         }
1558     }
1559
1560     if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1561         && !sess.opts.unstable_opts.unstable_options
1562     {
1563         sess.err(&format!(
1564             "`-Csplit-debuginfo={}` is unstable on this platform",
1565             sess.split_debuginfo()
1566         ));
1567     }
1568 }
1569
1570 /// Holds data on the current incremental compilation session, if there is one.
1571 #[derive(Debug)]
1572 pub enum IncrCompSession {
1573     /// This is the state the session will be in until the incr. comp. dir is
1574     /// needed.
1575     NotInitialized,
1576     /// This is the state during which the session directory is private and can
1577     /// be modified.
1578     Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1579     /// This is the state after the session directory has been finalized. In this
1580     /// state, the contents of the directory must not be modified any more.
1581     Finalized { session_directory: PathBuf },
1582     /// This is an error state that is reached when some compilation error has
1583     /// occurred. It indicates that the contents of the session directory must
1584     /// not be used, since they might be invalid.
1585     InvalidBecauseOfErrors { session_directory: PathBuf },
1586 }
1587
1588 fn early_error_handler(output: config::ErrorOutputType) -> rustc_errors::Handler {
1589     let fallback_bundle = fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
1590     let emitter: Box<dyn Emitter + sync::Send> = match output {
1591         config::ErrorOutputType::HumanReadable(kind) => {
1592             let (short, color_config) = kind.unzip();
1593             Box::new(EmitterWriter::stderr(
1594                 color_config,
1595                 None,
1596                 None,
1597                 fallback_bundle,
1598                 short,
1599                 false,
1600                 None,
1601                 false,
1602             ))
1603         }
1604         config::ErrorOutputType::Json { pretty, json_rendered } => {
1605             Box::new(JsonEmitter::basic(pretty, json_rendered, None, fallback_bundle, None, false))
1606         }
1607     };
1608     rustc_errors::Handler::with_emitter(true, None, emitter)
1609 }
1610
1611 pub fn early_error_no_abort(output: config::ErrorOutputType, msg: &str) -> ErrorGuaranteed {
1612     early_error_handler(output).struct_err(msg).emit()
1613 }
1614
1615 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1616     early_error_handler(output).struct_fatal(msg).emit()
1617 }
1618
1619 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1620     early_error_handler(output).struct_warn(msg).emit()
1621 }