1use std::any::Any;
2use std::ops::{Div, Mul};
3use std::path::{Path, PathBuf};
4use std::str::FromStr;
5use std::sync::Arc;
6use std::sync::atomic::AtomicBool;
7use std::{env, fmt, io};
8
9use rand::{RngCore, rng};
10use rustc_ast::NodeId;
11use rustc_data_structures::base_n::{CASE_INSENSITIVE, ToBaseN};
12use rustc_data_structures::flock;
13use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
14use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
15use rustc_data_structures::sync::{DynSend, DynSync, Lock, MappedReadGuard, ReadGuard, RwLock};
16use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;
17use rustc_errors::codes::*;
18use rustc_errors::emitter::{
19 DynEmitter, HumanEmitter, HumanReadableErrorType, OutputTheme, stderr_destination,
20};
21use rustc_errors::json::JsonEmitter;
22use rustc_errors::timings::TimingSectionHandler;
23use rustc_errors::translation::Translator;
24use rustc_errors::{
25 Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, FatalAbort,
26 LintEmitter, TerminalUrl, fallback_fluent_bundle,
27};
28use rustc_macros::HashStable_Generic;
29pub use rustc_span::def_id::StableCrateId;
30use rustc_span::edition::Edition;
31use rustc_span::source_map::{FilePathMapping, SourceMap};
32use rustc_span::{FileNameDisplayPreference, RealFileName, Span, Symbol};
33use rustc_target::asm::InlineAsmArch;
34use rustc_target::spec::{
35 CodeModel, DebuginfoKind, PanicStrategy, RelocModel, RelroLevel, SanitizerSet,
36 SmallDataThresholdSupport, SplitDebuginfo, StackProtector, SymbolVisibility, Target,
37 TargetTuple, TlsModel, apple,
38};
39
40use crate::code_stats::CodeStats;
41pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
42use crate::config::{
43 self, CoverageLevel, CoverageOptions, CrateType, DebugInfo, ErrorOutputType, FunctionReturn,
44 Input, InstrumentCoverage, OptLevel, OutFileName, OutputType, RemapPathScopeComponents,
45 SwitchWithOptPath,
46};
47use crate::filesearch::FileSearch;
48use crate::lint::LintId;
49use crate::parse::{ParseSess, add_feature_diagnostics};
50use crate::search_paths::SearchPath;
51use crate::{errors, filesearch, lint};
52
53#[derive(Clone, Copy)]
55pub enum CtfeBacktrace {
56 Disabled,
58 Capture,
61 Immediate,
63}
64
65#[derive(Clone, Copy, Debug, HashStable_Generic)]
68pub struct Limit(pub usize);
69
70impl Limit {
71 pub fn new(value: usize) -> Self {
73 Limit(value)
74 }
75
76 pub fn unlimited() -> Self {
78 Limit(usize::MAX)
79 }
80
81 #[inline]
84 pub fn value_within_limit(&self, value: usize) -> bool {
85 value <= self.0
86 }
87}
88
89impl From<usize> for Limit {
90 fn from(value: usize) -> Self {
91 Self::new(value)
92 }
93}
94
95impl fmt::Display for Limit {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 self.0.fmt(f)
98 }
99}
100
101impl Div<usize> for Limit {
102 type Output = Limit;
103
104 fn div(self, rhs: usize) -> Self::Output {
105 Limit::new(self.0 / rhs)
106 }
107}
108
109impl Mul<usize> for Limit {
110 type Output = Limit;
111
112 fn mul(self, rhs: usize) -> Self::Output {
113 Limit::new(self.0 * rhs)
114 }
115}
116
117impl rustc_errors::IntoDiagArg for Limit {
118 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
119 self.to_string().into_diag_arg(&mut None)
120 }
121}
122
123#[derive(Clone, Copy, Debug, HashStable_Generic)]
124pub struct Limits {
125 pub recursion_limit: Limit,
128 pub move_size_limit: Limit,
131 pub type_length_limit: Limit,
133 pub pattern_complexity_limit: Limit,
135}
136
137pub struct CompilerIO {
138 pub input: Input,
139 pub output_dir: Option<PathBuf>,
140 pub output_file: Option<OutFileName>,
141 pub temps_dir: Option<PathBuf>,
142}
143
144pub trait DynLintStore: Any + DynSync + DynSend {
145 fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;
147}
148
149pub struct Session {
152 pub target: Target,
153 pub host: Target,
154 pub opts: config::Options,
155 pub target_tlib_path: Arc<SearchPath>,
156 pub psess: ParseSess,
157 pub io: CompilerIO,
159
160 incr_comp_session: RwLock<IncrCompSession>,
161
162 pub prof: SelfProfilerRef,
164
165 pub timings: TimingSectionHandler,
167
168 pub code_stats: CodeStats,
170
171 pub lint_store: Option<Arc<dyn DynLintStore>>,
173
174 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
176
177 pub ctfe_backtrace: Lock<CtfeBacktrace>,
184
185 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
190
191 pub asm_arch: Option<InlineAsmArch>,
193
194 pub target_features: FxIndexSet<Symbol>,
196
197 pub unstable_target_features: FxIndexSet<Symbol>,
199
200 pub cfg_version: &'static str,
202
203 pub using_internal_features: &'static AtomicBool,
208
209 pub expanded_args: Vec<String>,
214
215 target_filesearch: FileSearch,
216 host_filesearch: FileSearch,
217
218 pub invocation_temp: Option<String>,
225}
226
227impl LintEmitter for &'_ Session {
228 type Id = NodeId;
229
230 fn emit_node_span_lint(
231 self,
232 lint: &'static rustc_lint_defs::Lint,
233 node_id: Self::Id,
234 span: impl Into<rustc_errors::MultiSpan>,
235 decorator: impl for<'a> rustc_errors::LintDiagnostic<'a, ()> + DynSend + 'static,
236 ) {
237 self.psess.buffer_lint(lint, span, node_id, decorator);
238 }
239}
240
241#[derive(Clone, Copy)]
242pub enum CodegenUnits {
243 User(usize),
246
247 Default(usize),
251}
252
253impl CodegenUnits {
254 pub fn as_usize(self) -> usize {
255 match self {
256 CodegenUnits::User(n) => n,
257 CodegenUnits::Default(n) => n,
258 }
259 }
260}
261
262pub struct LintGroup {
263 pub name: &'static str,
264 pub lints: Vec<LintId>,
265 pub is_externally_loaded: bool,
266}
267
268impl Session {
269 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
270 self.miri_unleashed_features.lock().push((span, feature_gate));
271 }
272
273 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
274 Some(self.source_map().path_mapping().to_real_filename(self.io.input.opt_path()?))
275 }
276
277 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
278 let mut guar = None;
279 let unleashed_features = self.miri_unleashed_features.lock();
280 if !unleashed_features.is_empty() {
281 let mut must_err = false;
282 self.dcx().emit_warn(errors::SkippingConstChecks {
284 unleashed_features: unleashed_features
285 .iter()
286 .map(|(span, gate)| {
287 gate.map(|gate| {
288 must_err = true;
289 errors::UnleashedFeatureHelp::Named { span: *span, gate }
290 })
291 .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })
292 })
293 .collect(),
294 });
295
296 if must_err && self.dcx().has_errors().is_none() {
298 guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));
300 }
301 }
302 guar
303 }
304
305 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
307 let mut guar = None;
308 guar = guar.or(self.check_miri_unleashed_features());
309 guar = guar.or(self.dcx().emit_stashed_diagnostics());
310 self.dcx().print_error_count();
311 if self.opts.json_future_incompat {
312 self.dcx().emit_future_breakage_report();
313 }
314 guar
315 }
316
317 pub fn is_test_crate(&self) -> bool {
319 self.opts.test
320 }
321
322 #[track_caller]
324 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
325 let mut err = self.dcx().create_err(err);
326 if err.code.is_none() {
327 #[allow(rustc::diagnostic_outside_of_impl)]
328 err.code(E0658);
329 }
330 add_feature_diagnostics(&mut err, self, feature);
331 err
332 }
333
334 pub fn record_trimmed_def_paths(&self) {
337 if self.opts.unstable_opts.print_type_sizes
338 || self.opts.unstable_opts.query_dep_graph
339 || self.opts.unstable_opts.dump_mir.is_some()
340 || self.opts.unstable_opts.unpretty.is_some()
341 || self.prof.is_args_recording_enabled()
342 || self.opts.output_types.contains_key(&OutputType::Mir)
343 || std::env::var_os("RUSTC_LOG").is_some()
344 {
345 return;
346 }
347
348 self.dcx().set_must_produce_diag()
349 }
350
351 #[inline]
352 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
353 self.psess.dcx()
354 }
355
356 #[inline]
357 pub fn source_map(&self) -> &SourceMap {
358 self.psess.source_map()
359 }
360
361 pub fn enable_internal_lints(&self) -> bool {
365 self.unstable_options() && !self.opts.actually_rustdoc
366 }
367
368 pub fn instrument_coverage(&self) -> bool {
369 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
370 }
371
372 pub fn instrument_coverage_branch(&self) -> bool {
373 self.instrument_coverage()
374 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
375 }
376
377 pub fn instrument_coverage_condition(&self) -> bool {
378 self.instrument_coverage()
379 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
380 }
381
382 pub fn coverage_options(&self) -> &CoverageOptions {
386 &self.opts.unstable_opts.coverage_options
387 }
388
389 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
390 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::CFI)
391 }
392
393 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
394 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
395 }
396
397 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
398 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
399 }
400
401 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
402 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
403 }
404
405 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
406 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
407 }
408
409 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
410 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
411 }
412
413 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
414 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::KCFI)
415 }
416
417 pub fn is_split_lto_unit_enabled(&self) -> bool {
418 self.opts.unstable_opts.split_lto_unit == Some(true)
419 }
420
421 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
423 if !self.target.crt_static_respected {
424 return self.target.crt_static_default;
426 }
427
428 let requested_features = self.opts.cg.target_feature.split(',');
429 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
430 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
431
432 #[allow(rustc::bad_opt_access)]
434 if found_positive || found_negative {
435 found_positive
436 } else if crate_type == Some(CrateType::ProcMacro)
437 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
438 {
439 false
443 } else {
444 self.target.crt_static_default
445 }
446 }
447
448 pub fn is_wasi_reactor(&self) -> bool {
449 self.target.options.os == "wasi"
450 && matches!(
451 self.opts.unstable_opts.wasi_exec_model,
452 Some(config::WasiExecModel::Reactor)
453 )
454 }
455
456 pub fn target_can_use_split_dwarf(&self) -> bool {
458 self.target.debuginfo_kind == DebuginfoKind::Dwarf
459 }
460
461 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
462 format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.as_u64())
463 }
464
465 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
466 &self.target_filesearch
467 }
468 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
469 &self.host_filesearch
470 }
471
472 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
476 let search_paths = self
477 .opts
478 .sysroot
479 .all_paths()
480 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
481
482 if self_contained {
483 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
487 } else {
488 search_paths.collect()
489 }
490 }
491
492 pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
493 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
494
495 if let IncrCompSession::NotInitialized = *incr_comp_session {
496 } else {
497 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
498 }
499
500 *incr_comp_session =
501 IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
502 }
503
504 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
505 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
506
507 if let IncrCompSession::Active { .. } = *incr_comp_session {
508 } else {
509 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
510 }
511
512 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
514 }
515
516 pub fn mark_incr_comp_session_as_invalid(&self) {
517 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
518
519 let session_directory = match *incr_comp_session {
520 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
521 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
522 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
523 };
524
525 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
527 }
528
529 pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
530 let incr_comp_session = self.incr_comp_session.borrow();
531 ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
532 IncrCompSession::NotInitialized => panic!(
533 "trying to get session directory from `IncrCompSession`: {:?}",
534 *incr_comp_session,
535 ),
536 IncrCompSession::Active { ref session_directory, .. }
537 | IncrCompSession::Finalized { ref session_directory }
538 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
539 session_directory
540 }
541 })
542 }
543
544 pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
545 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
546 }
547
548 pub fn is_rust_2015(&self) -> bool {
550 self.edition().is_rust_2015()
551 }
552
553 pub fn at_least_rust_2018(&self) -> bool {
555 self.edition().at_least_rust_2018()
556 }
557
558 pub fn at_least_rust_2021(&self) -> bool {
560 self.edition().at_least_rust_2021()
561 }
562
563 pub fn at_least_rust_2024(&self) -> bool {
565 self.edition().at_least_rust_2024()
566 }
567
568 pub fn needs_plt(&self) -> bool {
570 let want_plt = self.target.plt_by_default;
573
574 let dbg_opts = &self.opts.unstable_opts;
575
576 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
577
578 let full_relro = RelroLevel::Full == relro_level;
582
583 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
586 }
587
588 pub fn emit_lifetime_markers(&self) -> bool {
590 self.opts.optimize != config::OptLevel::No
591 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
595 }
596
597 pub fn diagnostic_width(&self) -> usize {
598 let default_column_width = 140;
599 if let Some(width) = self.opts.diagnostic_width {
600 width
601 } else if self.opts.unstable_opts.ui_testing {
602 default_column_width
603 } else {
604 termize::dimensions().map_or(default_column_width, |(w, _)| w)
605 }
606 }
607
608 pub fn default_visibility(&self) -> SymbolVisibility {
610 self.opts
611 .unstable_opts
612 .default_visibility
613 .or(self.target.options.default_visibility)
614 .unwrap_or(SymbolVisibility::Interposable)
615 }
616
617 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
618 if verbatim {
619 ("", "")
620 } else {
621 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
622 }
623 }
624
625 pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
626 match self.lint_store {
627 Some(ref lint_store) => lint_store.lint_groups_iter(),
628 None => Box::new(std::iter::empty()),
629 }
630 }
631}
632
633#[allow(rustc::bad_opt_access)]
635impl Session {
636 pub fn verbose_internals(&self) -> bool {
637 self.opts.unstable_opts.verbose_internals
638 }
639
640 pub fn print_llvm_stats(&self) -> bool {
641 self.opts.unstable_opts.print_codegen_stats
642 }
643
644 pub fn verify_llvm_ir(&self) -> bool {
645 self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
646 }
647
648 pub fn binary_dep_depinfo(&self) -> bool {
649 self.opts.unstable_opts.binary_dep_depinfo
650 }
651
652 pub fn mir_opt_level(&self) -> usize {
653 self.opts
654 .unstable_opts
655 .mir_opt_level
656 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
657 }
658
659 pub fn lto(&self) -> config::Lto {
661 if self.target.requires_lto {
663 return config::Lto::Fat;
664 }
665
666 match self.opts.cg.lto {
670 config::LtoCli::Unspecified => {
671 }
674 config::LtoCli::No => {
675 return config::Lto::No;
677 }
678 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
679 return config::Lto::Fat;
681 }
682 config::LtoCli::Thin => {
683 return config::Lto::Thin;
685 }
686 }
687
688 if self.opts.cli_forced_local_thinlto_off {
697 return config::Lto::No;
698 }
699
700 if let Some(enabled) = self.opts.unstable_opts.thinlto {
703 if enabled {
704 return config::Lto::ThinLocal;
705 } else {
706 return config::Lto::No;
707 }
708 }
709
710 if self.codegen_units().as_usize() == 1 {
713 return config::Lto::No;
714 }
715
716 match self.opts.optimize {
719 config::OptLevel::No => config::Lto::No,
720 _ => config::Lto::ThinLocal,
721 }
722 }
723
724 pub fn panic_strategy(&self) -> PanicStrategy {
727 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
728 }
729
730 pub fn fewer_names(&self) -> bool {
731 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
732 fewer_names
733 } else {
734 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
735 || self.opts.output_types.contains_key(&OutputType::Bitcode)
736 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
738 !more_names
739 }
740 }
741
742 pub fn unstable_options(&self) -> bool {
743 self.opts.unstable_opts.unstable_options
744 }
745
746 pub fn is_nightly_build(&self) -> bool {
747 self.opts.unstable_features.is_nightly_build()
748 }
749
750 pub fn overflow_checks(&self) -> bool {
751 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
752 }
753
754 pub fn ub_checks(&self) -> bool {
755 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
756 }
757
758 pub fn contract_checks(&self) -> bool {
759 self.opts.unstable_opts.contract_checks.unwrap_or(false)
760 }
761
762 pub fn relocation_model(&self) -> RelocModel {
763 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
764 }
765
766 pub fn code_model(&self) -> Option<CodeModel> {
767 self.opts.cg.code_model.or(self.target.code_model)
768 }
769
770 pub fn tls_model(&self) -> TlsModel {
771 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
772 }
773
774 pub fn direct_access_external_data(&self) -> Option<bool> {
775 self.opts
776 .unstable_opts
777 .direct_access_external_data
778 .or(self.target.direct_access_external_data)
779 }
780
781 pub fn split_debuginfo(&self) -> SplitDebuginfo {
782 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
783 }
784
785 pub fn dwarf_version(&self) -> u32 {
787 self.opts
788 .cg
789 .dwarf_version
790 .or(self.opts.unstable_opts.dwarf_version)
791 .unwrap_or(self.target.default_dwarf_version)
792 }
793
794 pub fn stack_protector(&self) -> StackProtector {
795 if self.target.options.supports_stack_protector {
796 self.opts.unstable_opts.stack_protector
797 } else {
798 StackProtector::None
799 }
800 }
801
802 pub fn must_emit_unwind_tables(&self) -> bool {
803 self.target.requires_uwtable
831 || self.opts.cg.force_unwind_tables.unwrap_or(
832 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
833 )
834 }
835
836 #[inline]
839 pub fn threads(&self) -> usize {
840 self.opts.unstable_opts.threads
841 }
842
843 pub fn codegen_units(&self) -> CodegenUnits {
846 if let Some(n) = self.opts.cli_forced_codegen_units {
847 return CodegenUnits::User(n);
848 }
849 if let Some(n) = self.target.default_codegen_units {
850 return CodegenUnits::Default(n as usize);
851 }
852
853 if self.opts.incremental.is_some() {
857 return CodegenUnits::Default(256);
858 }
859
860 CodegenUnits::Default(16)
911 }
912
913 pub fn teach(&self, code: ErrCode) -> bool {
914 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
915 }
916
917 pub fn edition(&self) -> Edition {
918 self.opts.edition
919 }
920
921 pub fn link_dead_code(&self) -> bool {
922 self.opts.cg.link_dead_code.unwrap_or(false)
923 }
924
925 pub fn filename_display_preference(
926 &self,
927 scope: RemapPathScopeComponents,
928 ) -> FileNameDisplayPreference {
929 assert!(
930 scope.bits().count_ones() == 1,
931 "one and only one scope should be passed to `Session::filename_display_preference`"
932 );
933 if self.opts.unstable_opts.remap_path_scope.contains(scope) {
934 FileNameDisplayPreference::Remapped
935 } else {
936 FileNameDisplayPreference::Local
937 }
938 }
939
940 pub fn apple_deployment_target(&self) -> apple::OSVersion {
945 let min = apple::OSVersion::minimum_deployment_target(&self.target);
946 let env_var = apple::deployment_target_env_var(&self.target.os);
947
948 if let Ok(deployment_target) = env::var(env_var) {
950 match apple::OSVersion::from_str(&deployment_target) {
951 Ok(version) => {
952 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
953 if version < os_min {
958 self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {
959 env_var,
960 version: version.fmt_pretty().to_string(),
961 os_min: os_min.fmt_pretty().to_string(),
962 });
963 }
964
965 version.max(min)
967 }
968 Err(error) => {
969 self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });
970 min
971 }
972 }
973 } else {
974 min
976 }
977 }
978}
979
980#[allow(rustc::bad_opt_access)]
982fn default_emitter(
983 sopts: &config::Options,
984 source_map: Arc<SourceMap>,
985 translator: Translator,
986) -> Box<DynEmitter> {
987 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
988 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
989 let terminal_url = match sopts.unstable_opts.terminal_urls {
990 TerminalUrl::Auto => {
991 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
992 (Ok("truecolor"), Ok("xterm-256color"))
993 if sopts.unstable_features.is_nightly_build() =>
994 {
995 TerminalUrl::Yes
996 }
997 _ => TerminalUrl::No,
998 }
999 }
1000 t => t,
1001 };
1002
1003 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
1004
1005 match sopts.error_format {
1006 config::ErrorOutputType::HumanReadable { kind, color_config } => {
1007 let short = kind.short();
1008
1009 if let HumanReadableErrorType::AnnotateSnippet = kind {
1010 let emitter =
1011 AnnotateSnippetEmitter::new(source_map, translator, short, macro_backtrace);
1012 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1013 } else {
1014 let emitter = HumanEmitter::new(stderr_destination(color_config), translator)
1015 .sm(source_map)
1016 .short_message(short)
1017 .diagnostic_width(sopts.diagnostic_width)
1018 .macro_backtrace(macro_backtrace)
1019 .track_diagnostics(track_diagnostics)
1020 .terminal_url(terminal_url)
1021 .theme(if let HumanReadableErrorType::Unicode = kind {
1022 OutputTheme::Unicode
1023 } else {
1024 OutputTheme::Ascii
1025 })
1026 .ignored_directories_in_source_blocks(
1027 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1028 );
1029 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1030 }
1031 }
1032 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
1033 JsonEmitter::new(
1034 Box::new(io::BufWriter::new(io::stderr())),
1035 source_map,
1036 translator,
1037 pretty,
1038 json_rendered,
1039 color_config,
1040 )
1041 .ui_testing(sopts.unstable_opts.ui_testing)
1042 .ignored_directories_in_source_blocks(
1043 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1044 )
1045 .diagnostic_width(sopts.diagnostic_width)
1046 .macro_backtrace(macro_backtrace)
1047 .track_diagnostics(track_diagnostics)
1048 .terminal_url(terminal_url),
1049 ),
1050 }
1051}
1052
1053#[allow(rustc::bad_opt_access)]
1055#[allow(rustc::untranslatable_diagnostic)] pub fn build_session(
1057 sopts: config::Options,
1058 io: CompilerIO,
1059 fluent_bundle: Option<Arc<rustc_errors::FluentBundle>>,
1060 registry: rustc_errors::registry::Registry,
1061 fluent_resources: Vec<&'static str>,
1062 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1063 target: Target,
1064 cfg_version: &'static str,
1065 ice_file: Option<PathBuf>,
1066 using_internal_features: &'static AtomicBool,
1067 expanded_args: Vec<String>,
1068) -> Session {
1069 let warnings_allow = sopts
1073 .lint_opts
1074 .iter()
1075 .rfind(|&(key, _)| *key == "warnings")
1076 .is_some_and(|&(_, level)| level == lint::Allow);
1077 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1078 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1079
1080 let translator = Translator {
1081 fluent_bundle,
1082 fallback_fluent_bundle: fallback_fluent_bundle(
1083 fluent_resources,
1084 sopts.unstable_opts.translate_directionality_markers,
1085 ),
1086 };
1087 let source_map = rustc_span::source_map::get_source_map().unwrap();
1088 let emitter = default_emitter(&sopts, Arc::clone(&source_map), translator);
1089
1090 let mut dcx = DiagCtxt::new(emitter)
1091 .with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings))
1092 .with_registry(registry);
1093 if let Some(ice_file) = ice_file {
1094 dcx = dcx.with_ice_file(ice_file);
1095 }
1096
1097 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1098 let (host, target_warnings) = Target::search(&host_triple, sopts.sysroot.path())
1099 .unwrap_or_else(|e| dcx.handle().fatal(format!("Error loading host specification: {e}")));
1100 for warning in target_warnings.warning_messages() {
1101 dcx.handle().warn(warning)
1102 }
1103
1104 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1105 {
1106 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1107
1108 let profiler = SelfProfiler::new(
1109 directory,
1110 sopts.crate_name.as_deref(),
1111 sopts.unstable_opts.self_profile_events.as_deref(),
1112 &sopts.unstable_opts.self_profile_counter,
1113 );
1114 match profiler {
1115 Ok(profiler) => Some(Arc::new(profiler)),
1116 Err(e) => {
1117 dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1118 None
1119 }
1120 }
1121 } else {
1122 None
1123 };
1124
1125 let mut psess = ParseSess::with_dcx(dcx, source_map);
1126 psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1127
1128 let host_triple = config::host_tuple();
1129 let target_triple = sopts.target_triple.tuple();
1130 let host_tlib_path =
1132 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1133 let target_tlib_path = if host_triple == target_triple {
1134 Arc::clone(&host_tlib_path)
1137 } else {
1138 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1139 };
1140
1141 let prof = SelfProfilerRef::new(
1142 self_profiler,
1143 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1144 );
1145
1146 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1147 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1148 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1149 _ => CtfeBacktrace::Disabled,
1150 });
1151
1152 let asm_arch = if target.allow_asm { InlineAsmArch::from_str(&target.arch).ok() } else { None };
1153 let target_filesearch =
1154 filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1155 let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1156
1157 let invocation_temp = sopts
1158 .incremental
1159 .as_ref()
1160 .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
1161
1162 let timings = TimingSectionHandler::new(sopts.json_timings);
1163
1164 let sess = Session {
1165 target,
1166 host,
1167 opts: sopts,
1168 target_tlib_path,
1169 psess,
1170 io,
1171 incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1172 prof,
1173 timings,
1174 code_stats: Default::default(),
1175 lint_store: None,
1176 driver_lint_caps,
1177 ctfe_backtrace,
1178 miri_unleashed_features: Lock::new(Default::default()),
1179 asm_arch,
1180 target_features: Default::default(),
1181 unstable_target_features: Default::default(),
1182 cfg_version,
1183 using_internal_features,
1184 expanded_args,
1185 target_filesearch,
1186 host_filesearch,
1187 invocation_temp,
1188 };
1189
1190 validate_commandline_args_with_session_available(&sess);
1191
1192 sess
1193}
1194
1195#[allow(rustc::bad_opt_access)]
1201fn validate_commandline_args_with_session_available(sess: &Session) {
1202 if sess.opts.cg.linker_plugin_lto.enabled()
1210 && sess.opts.cg.prefer_dynamic
1211 && sess.target.is_like_windows
1212 {
1213 sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1214 }
1215
1216 if let Some(ref path) = sess.opts.cg.profile_use {
1219 if !path.exists() {
1220 sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1221 }
1222 }
1223
1224 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1226 if !path.exists() {
1227 sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1228 }
1229 }
1230
1231 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1233 if sess.target.requires_uwtable && !include_uwtables {
1234 sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1235 }
1236 }
1237
1238 let supported_sanitizers = sess.target.options.supported_sanitizers;
1240 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1241 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == "aarch64" {
1244 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1245 }
1246 match unsupported_sanitizers.into_iter().count() {
1247 0 => {}
1248 1 => {
1249 sess.dcx()
1250 .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1251 }
1252 _ => {
1253 sess.dcx().emit_err(errors::SanitizersNotSupported {
1254 us: unsupported_sanitizers.to_string(),
1255 });
1256 }
1257 }
1258
1259 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1261 sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1262 first: first.to_string(),
1263 second: second.to_string(),
1264 });
1265 }
1266
1267 if sess.crt_static(None)
1269 && !sess.opts.unstable_opts.sanitizer.is_empty()
1270 && !sess.target.is_like_msvc
1271 {
1272 sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1273 }
1274
1275 if sess.is_sanitizer_cfi_enabled()
1277 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1278 {
1279 sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1280 }
1281
1282 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy() != PanicStrategy::Abort {
1284 sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1285 }
1286
1287 if sess.is_sanitizer_cfi_enabled()
1289 && sess.lto() == config::Lto::Fat
1290 && (sess.codegen_units().as_usize() != 1)
1291 {
1292 sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1293 }
1294
1295 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1297 if !sess.is_sanitizer_cfi_enabled() {
1298 sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1299 }
1300 }
1301
1302 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1304 sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);
1305 }
1306
1307 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1309 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1310 sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1311 }
1312 }
1313
1314 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1316 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1317 sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1318 }
1319 }
1320
1321 if sess.is_split_lto_unit_enabled()
1323 && !(sess.lto() == config::Lto::Fat
1324 || sess.lto() == config::Lto::Thin
1325 || sess.opts.cg.linker_plugin_lto.enabled())
1326 {
1327 sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1328 }
1329
1330 if sess.lto() != config::Lto::Fat {
1332 if sess.opts.unstable_opts.virtual_function_elimination {
1333 sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1334 }
1335 }
1336
1337 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1338 if !sess.target.options.supports_stack_protector {
1339 sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1340 stack_protector: sess.opts.unstable_opts.stack_protector,
1341 target_triple: &sess.opts.target_triple,
1342 });
1343 }
1344 }
1345
1346 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1347 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1348 sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1349 target_triple: &sess.opts.target_triple,
1350 })
1351 }
1352 }
1353
1354 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != "aarch64" {
1355 sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1356 }
1357
1358 if let Some(dwarf_version) =
1359 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1360 {
1361 if dwarf_version < 2 || dwarf_version > 5 {
1363 sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1364 }
1365 }
1366
1367 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1368 && !sess.opts.unstable_opts.unstable_options
1369 {
1370 sess.dcx()
1371 .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1372 }
1373
1374 if sess.opts.unstable_opts.embed_source {
1375 let dwarf_version = sess.dwarf_version();
1376
1377 if dwarf_version < 5 {
1378 sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1379 }
1380
1381 if sess.opts.debuginfo == DebugInfo::None {
1382 sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1383 }
1384 }
1385
1386 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1387 sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1388 }
1389
1390 if let Some(flavor) = sess.opts.cg.linker_flavor
1391 && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1392 {
1393 let flavor = flavor.desc();
1394 sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1395 }
1396
1397 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1398 if sess.target.arch != "x86" && sess.target.arch != "x86_64" {
1399 sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1400 }
1401 }
1402
1403 if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1404 if sess.target.arch != "x86" && sess.target.arch != "x86_64" {
1405 sess.dcx().emit_err(errors::IndirectBranchCsPrefixRequiresX86OrX8664);
1406 }
1407 }
1408
1409 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1410 if regparm > 3 {
1411 sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1412 }
1413 if sess.target.arch != "x86" {
1414 sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1415 }
1416 }
1417 if sess.opts.unstable_opts.reg_struct_return {
1418 if sess.target.arch != "x86" {
1419 sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1420 }
1421 }
1422
1423 match sess.opts.unstable_opts.function_return {
1427 FunctionReturn::Keep => (),
1428 FunctionReturn::ThunkExtern => {
1429 if let Some(code_model) = sess.code_model()
1432 && code_model == CodeModel::Large
1433 {
1434 sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1435 }
1436 }
1437 }
1438
1439 if sess.opts.cg.soft_float {
1440 if sess.target.arch == "arm" {
1441 sess.dcx().emit_warn(errors::SoftFloatDeprecated);
1442 } else {
1443 sess.dcx().emit_warn(errors::SoftFloatIgnored);
1446 }
1447 }
1448}
1449
1450#[derive(Debug)]
1452enum IncrCompSession {
1453 NotInitialized,
1456 Active { session_directory: PathBuf, _lock_file: flock::Lock },
1461 Finalized { session_directory: PathBuf },
1464 InvalidBecauseOfErrors { session_directory: PathBuf },
1468}
1469
1470pub struct EarlyDiagCtxt {
1472 dcx: DiagCtxt,
1473}
1474
1475impl EarlyDiagCtxt {
1476 pub fn new(output: ErrorOutputType) -> Self {
1477 let emitter = mk_emitter(output);
1478 Self { dcx: DiagCtxt::new(emitter) }
1479 }
1480
1481 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1484 assert!(self.dcx.handle().has_errors().is_none());
1485
1486 let emitter = mk_emitter(output);
1487 self.dcx = DiagCtxt::new(emitter);
1488 }
1489
1490 #[allow(rustc::untranslatable_diagnostic)]
1491 #[allow(rustc::diagnostic_outside_of_impl)]
1492 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1493 self.dcx.handle().note(msg)
1494 }
1495
1496 #[allow(rustc::untranslatable_diagnostic)]
1497 #[allow(rustc::diagnostic_outside_of_impl)]
1498 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1499 self.dcx.handle().struct_help(msg).emit()
1500 }
1501
1502 #[allow(rustc::untranslatable_diagnostic)]
1503 #[allow(rustc::diagnostic_outside_of_impl)]
1504 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1505 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1506 self.dcx.handle().err(msg)
1507 }
1508
1509 #[allow(rustc::untranslatable_diagnostic)]
1510 #[allow(rustc::diagnostic_outside_of_impl)]
1511 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1512 self.dcx.handle().fatal(msg)
1513 }
1514
1515 #[allow(rustc::untranslatable_diagnostic)]
1516 #[allow(rustc::diagnostic_outside_of_impl)]
1517 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1518 self.dcx.handle().struct_fatal(msg)
1519 }
1520
1521 #[allow(rustc::untranslatable_diagnostic)]
1522 #[allow(rustc::diagnostic_outside_of_impl)]
1523 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1524 self.dcx.handle().warn(msg)
1525 }
1526
1527 #[allow(rustc::untranslatable_diagnostic)]
1528 #[allow(rustc::diagnostic_outside_of_impl)]
1529 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1530 self.dcx.handle().struct_warn(msg)
1531 }
1532}
1533
1534fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1535 let translator =
1538 Translator::with_fallback_bundle(vec![rustc_errors::DEFAULT_LOCALE_RESOURCE], false);
1539 let emitter: Box<DynEmitter> = match output {
1540 config::ErrorOutputType::HumanReadable { kind, color_config } => {
1541 let short = kind.short();
1542 Box::new(
1543 HumanEmitter::new(stderr_destination(color_config), translator)
1544 .theme(if let HumanReadableErrorType::Unicode = kind {
1545 OutputTheme::Unicode
1546 } else {
1547 OutputTheme::Ascii
1548 })
1549 .short_message(short),
1550 )
1551 }
1552 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1553 Box::new(JsonEmitter::new(
1554 Box::new(io::BufWriter::new(io::stderr())),
1555 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1556 translator,
1557 pretty,
1558 json_rendered,
1559 color_config,
1560 ))
1561 }
1562 };
1563 emitter
1564}
1565
1566pub trait RemapFileNameExt {
1567 type Output<'a>
1568 where
1569 Self: 'a;
1570
1571 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_>;
1575}
1576
1577impl RemapFileNameExt for rustc_span::FileName {
1578 type Output<'a> = rustc_span::FileNameDisplay<'a>;
1579
1580 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1581 assert!(
1582 scope.bits().count_ones() == 1,
1583 "one and only one scope should be passed to for_scope"
1584 );
1585 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1586 self.prefer_remapped_unconditionally()
1587 } else {
1588 self.prefer_local()
1589 }
1590 }
1591}
1592
1593impl RemapFileNameExt for rustc_span::RealFileName {
1594 type Output<'a> = &'a Path;
1595
1596 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1597 assert!(
1598 scope.bits().count_ones() == 1,
1599 "one and only one scope should be passed to for_scope"
1600 );
1601 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1602 self.remapped_path_if_available()
1603 } else {
1604 self.local_path_if_available()
1605 }
1606 }
1607}