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