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