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