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