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