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::{
22 Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, FatalAbort,
23 FluentBundle, LazyFallbackBundle, TerminalUrl, fallback_fluent_bundle,
24};
25use rustc_macros::HashStable_Generic;
26pub use rustc_span::def_id::StableCrateId;
27use rustc_span::edition::Edition;
28use rustc_span::source_map::{FilePathMapping, SourceMap};
29use rustc_span::{FileNameDisplayPreference, RealFileName, Span, Symbol};
30use rustc_target::asm::InlineAsmArch;
31use rustc_target::spec::{
32 CodeModel, DebuginfoKind, PanicStrategy, RelocModel, RelroLevel, SanitizerSet,
33 SmallDataThresholdSupport, SplitDebuginfo, StackProtector, SymbolVisibility, Target,
34 TargetTuple, TlsModel, apple,
35};
36
37use crate::code_stats::CodeStats;
38pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
39use crate::config::{
40 self, CoverageLevel, CrateType, DebugInfo, ErrorOutputType, FunctionReturn, Input,
41 InstrumentCoverage, OptLevel, OutFileName, OutputType, RemapPathScopeComponents,
42 SwitchWithOptPath,
43};
44use crate::filesearch::FileSearch;
45use crate::parse::{ParseSess, add_feature_diagnostics};
46use crate::search_paths::SearchPath;
47use crate::{errors, filesearch, lint};
48
49#[derive(Clone, Copy)]
51pub enum CtfeBacktrace {
52 Disabled,
54 Capture,
57 Immediate,
59}
60
61#[derive(Clone, Copy, Debug, HashStable_Generic)]
64pub struct Limit(pub usize);
65
66impl Limit {
67 pub fn new(value: usize) -> Self {
69 Limit(value)
70 }
71
72 pub fn unlimited() -> Self {
74 Limit(usize::MAX)
75 }
76
77 #[inline]
80 pub fn value_within_limit(&self, value: usize) -> bool {
81 value <= self.0
82 }
83}
84
85impl From<usize> for Limit {
86 fn from(value: usize) -> Self {
87 Self::new(value)
88 }
89}
90
91impl fmt::Display for Limit {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 self.0.fmt(f)
94 }
95}
96
97impl Div<usize> for Limit {
98 type Output = Limit;
99
100 fn div(self, rhs: usize) -> Self::Output {
101 Limit::new(self.0 / rhs)
102 }
103}
104
105impl Mul<usize> for Limit {
106 type Output = Limit;
107
108 fn mul(self, rhs: usize) -> Self::Output {
109 Limit::new(self.0 * rhs)
110 }
111}
112
113impl rustc_errors::IntoDiagArg for Limit {
114 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
115 self.to_string().into_diag_arg(&mut None)
116 }
117}
118
119#[derive(Clone, Copy, Debug, HashStable_Generic)]
120pub struct Limits {
121 pub recursion_limit: Limit,
124 pub move_size_limit: Limit,
127 pub type_length_limit: Limit,
129 pub pattern_complexity_limit: Limit,
131}
132
133pub struct CompilerIO {
134 pub input: Input,
135 pub output_dir: Option<PathBuf>,
136 pub output_file: Option<OutFileName>,
137 pub temps_dir: Option<PathBuf>,
138}
139
140pub trait LintStoreMarker: Any + DynSync + DynSend {}
141
142pub struct Session {
145 pub target: Target,
146 pub host: Target,
147 pub opts: config::Options,
148 pub target_tlib_path: Arc<SearchPath>,
149 pub psess: ParseSess,
150 pub sysroot: PathBuf,
151 pub io: CompilerIO,
153
154 incr_comp_session: RwLock<IncrCompSession>,
155
156 pub prof: SelfProfilerRef,
158
159 pub code_stats: CodeStats,
161
162 pub lint_store: Option<Arc<dyn LintStoreMarker>>,
164
165 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
167
168 pub ctfe_backtrace: Lock<CtfeBacktrace>,
175
176 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
181
182 pub asm_arch: Option<InlineAsmArch>,
184
185 pub target_features: FxIndexSet<Symbol>,
187
188 pub unstable_target_features: FxIndexSet<Symbol>,
190
191 pub cfg_version: &'static str,
193
194 pub using_internal_features: &'static AtomicBool,
199
200 pub expanded_args: Vec<String>,
205
206 target_filesearch: FileSearch,
207 host_filesearch: FileSearch,
208
209 pub invocation_temp: Option<String>,
216}
217
218#[derive(PartialEq, Eq, PartialOrd, Ord)]
219pub enum MetadataKind {
220 None,
221 Uncompressed,
222 Compressed,
223}
224
225#[derive(Clone, Copy)]
226pub enum CodegenUnits {
227 User(usize),
230
231 Default(usize),
235}
236
237impl CodegenUnits {
238 pub fn as_usize(self) -> usize {
239 match self {
240 CodegenUnits::User(n) => n,
241 CodegenUnits::Default(n) => n,
242 }
243 }
244}
245
246impl Session {
247 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
248 self.miri_unleashed_features.lock().push((span, feature_gate));
249 }
250
251 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
252 Some(self.source_map().path_mapping().to_real_filename(self.io.input.opt_path()?))
253 }
254
255 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
256 let mut guar = None;
257 let unleashed_features = self.miri_unleashed_features.lock();
258 if !unleashed_features.is_empty() {
259 let mut must_err = false;
260 self.dcx().emit_warn(errors::SkippingConstChecks {
262 unleashed_features: unleashed_features
263 .iter()
264 .map(|(span, gate)| {
265 gate.map(|gate| {
266 must_err = true;
267 errors::UnleashedFeatureHelp::Named { span: *span, gate }
268 })
269 .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })
270 })
271 .collect(),
272 });
273
274 if must_err && self.dcx().has_errors().is_none() {
276 guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));
278 }
279 }
280 guar
281 }
282
283 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
285 let mut guar = None;
286 guar = guar.or(self.check_miri_unleashed_features());
287 guar = guar.or(self.dcx().emit_stashed_diagnostics());
288 self.dcx().print_error_count();
289 if self.opts.json_future_incompat {
290 self.dcx().emit_future_breakage_report();
291 }
292 guar
293 }
294
295 pub fn is_test_crate(&self) -> bool {
297 self.opts.test
298 }
299
300 #[track_caller]
302 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
303 let mut err = self.dcx().create_err(err);
304 if err.code.is_none() {
305 #[allow(rustc::diagnostic_outside_of_impl)]
306 err.code(E0658);
307 }
308 add_feature_diagnostics(&mut err, self, feature);
309 err
310 }
311
312 pub fn record_trimmed_def_paths(&self) {
315 if self.opts.unstable_opts.print_type_sizes
316 || self.opts.unstable_opts.query_dep_graph
317 || self.opts.unstable_opts.dump_mir.is_some()
318 || self.opts.unstable_opts.unpretty.is_some()
319 || self.opts.output_types.contains_key(&OutputType::Mir)
320 || std::env::var_os("RUSTC_LOG").is_some()
321 {
322 return;
323 }
324
325 self.dcx().set_must_produce_diag()
326 }
327
328 #[inline]
329 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
330 self.psess.dcx()
331 }
332
333 #[inline]
334 pub fn source_map(&self) -> &SourceMap {
335 self.psess.source_map()
336 }
337
338 pub fn enable_internal_lints(&self) -> bool {
342 self.unstable_options() && !self.opts.actually_rustdoc
343 }
344
345 pub fn instrument_coverage(&self) -> bool {
346 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
347 }
348
349 pub fn instrument_coverage_branch(&self) -> bool {
350 self.instrument_coverage()
351 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
352 }
353
354 pub fn instrument_coverage_condition(&self) -> bool {
355 self.instrument_coverage()
356 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
357 }
358
359 pub fn instrument_coverage_mcdc(&self) -> bool {
360 self.instrument_coverage()
361 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Mcdc
362 }
363
364 pub fn coverage_no_mir_spans(&self) -> bool {
366 self.opts.unstable_opts.coverage_options.no_mir_spans
367 }
368
369 pub fn coverage_discard_all_spans_in_codegen(&self) -> bool {
371 self.opts.unstable_opts.coverage_options.discard_all_spans_in_codegen
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 bin_path = filesearch::make_target_bin_path(&self.sysroot, config::host_tuple());
462 let fallback_sysroot_paths = filesearch::sysroot_candidates()
463 .into_iter()
464 .filter(|sysroot| *sysroot != self.sysroot)
466 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
467 let search_paths = std::iter::once(bin_path).chain(fallback_sysroot_paths);
468
469 if self_contained {
470 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
474 } else {
475 search_paths.collect()
476 }
477 }
478
479 pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
480 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
481
482 if let IncrCompSession::NotInitialized = *incr_comp_session {
483 } else {
484 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
485 }
486
487 *incr_comp_session =
488 IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
489 }
490
491 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
492 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
493
494 if let IncrCompSession::Active { .. } = *incr_comp_session {
495 } else {
496 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
497 }
498
499 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
501 }
502
503 pub fn mark_incr_comp_session_as_invalid(&self) {
504 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
505
506 let session_directory = match *incr_comp_session {
507 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
508 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
509 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
510 };
511
512 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
514 }
515
516 pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
517 let incr_comp_session = self.incr_comp_session.borrow();
518 ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
519 IncrCompSession::NotInitialized => panic!(
520 "trying to get session directory from `IncrCompSession`: {:?}",
521 *incr_comp_session,
522 ),
523 IncrCompSession::Active { ref session_directory, .. }
524 | IncrCompSession::Finalized { ref session_directory }
525 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
526 session_directory
527 }
528 })
529 }
530
531 pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
532 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
533 }
534
535 pub fn is_rust_2015(&self) -> bool {
537 self.edition().is_rust_2015()
538 }
539
540 pub fn at_least_rust_2018(&self) -> bool {
542 self.edition().at_least_rust_2018()
543 }
544
545 pub fn at_least_rust_2021(&self) -> bool {
547 self.edition().at_least_rust_2021()
548 }
549
550 pub fn at_least_rust_2024(&self) -> bool {
552 self.edition().at_least_rust_2024()
553 }
554
555 pub fn needs_plt(&self) -> bool {
557 let want_plt = self.target.plt_by_default;
560
561 let dbg_opts = &self.opts.unstable_opts;
562
563 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
564
565 let full_relro = RelroLevel::Full == relro_level;
569
570 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
573 }
574
575 pub fn emit_lifetime_markers(&self) -> bool {
577 self.opts.optimize != config::OptLevel::No
578 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
582 }
583
584 pub fn diagnostic_width(&self) -> usize {
585 let default_column_width = 140;
586 if let Some(width) = self.opts.diagnostic_width {
587 width
588 } else if self.opts.unstable_opts.ui_testing {
589 default_column_width
590 } else {
591 termize::dimensions().map_or(default_column_width, |(w, _)| w)
592 }
593 }
594
595 pub fn default_visibility(&self) -> SymbolVisibility {
597 self.opts
598 .unstable_opts
599 .default_visibility
600 .or(self.target.options.default_visibility)
601 .unwrap_or(SymbolVisibility::Interposable)
602 }
603
604 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
605 if verbatim {
606 ("", "")
607 } else {
608 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
609 }
610 }
611}
612
613#[allow(rustc::bad_opt_access)]
615impl Session {
616 pub fn verbose_internals(&self) -> bool {
617 self.opts.unstable_opts.verbose_internals
618 }
619
620 pub fn print_llvm_stats(&self) -> bool {
621 self.opts.unstable_opts.print_codegen_stats
622 }
623
624 pub fn verify_llvm_ir(&self) -> bool {
625 self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
626 }
627
628 pub fn binary_dep_depinfo(&self) -> bool {
629 self.opts.unstable_opts.binary_dep_depinfo
630 }
631
632 pub fn mir_opt_level(&self) -> usize {
633 self.opts
634 .unstable_opts
635 .mir_opt_level
636 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
637 }
638
639 pub fn lto(&self) -> config::Lto {
641 if self.target.requires_lto {
643 return config::Lto::Fat;
644 }
645
646 match self.opts.cg.lto {
650 config::LtoCli::Unspecified => {
651 }
654 config::LtoCli::No => {
655 return config::Lto::No;
657 }
658 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
659 return config::Lto::Fat;
661 }
662 config::LtoCli::Thin => {
663 return config::Lto::Thin;
665 }
666 }
667
668 if self.opts.cli_forced_local_thinlto_off {
677 return config::Lto::No;
678 }
679
680 if let Some(enabled) = self.opts.unstable_opts.thinlto {
683 if enabled {
684 return config::Lto::ThinLocal;
685 } else {
686 return config::Lto::No;
687 }
688 }
689
690 if self.codegen_units().as_usize() == 1 {
693 return config::Lto::No;
694 }
695
696 match self.opts.optimize {
699 config::OptLevel::No => config::Lto::No,
700 _ => config::Lto::ThinLocal,
701 }
702 }
703
704 pub fn panic_strategy(&self) -> PanicStrategy {
707 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
708 }
709
710 pub fn fewer_names(&self) -> bool {
711 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
712 fewer_names
713 } else {
714 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
715 || self.opts.output_types.contains_key(&OutputType::Bitcode)
716 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
718 !more_names
719 }
720 }
721
722 pub fn unstable_options(&self) -> bool {
723 self.opts.unstable_opts.unstable_options
724 }
725
726 pub fn is_nightly_build(&self) -> bool {
727 self.opts.unstable_features.is_nightly_build()
728 }
729
730 pub fn overflow_checks(&self) -> bool {
731 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
732 }
733
734 pub fn ub_checks(&self) -> bool {
735 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
736 }
737
738 pub fn contract_checks(&self) -> bool {
739 self.opts.unstable_opts.contract_checks.unwrap_or(false)
740 }
741
742 pub fn relocation_model(&self) -> RelocModel {
743 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
744 }
745
746 pub fn code_model(&self) -> Option<CodeModel> {
747 self.opts.cg.code_model.or(self.target.code_model)
748 }
749
750 pub fn tls_model(&self) -> TlsModel {
751 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
752 }
753
754 pub fn direct_access_external_data(&self) -> Option<bool> {
755 self.opts
756 .unstable_opts
757 .direct_access_external_data
758 .or(self.target.direct_access_external_data)
759 }
760
761 pub fn split_debuginfo(&self) -> SplitDebuginfo {
762 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
763 }
764
765 pub fn dwarf_version(&self) -> u32 {
767 self.opts
768 .cg
769 .dwarf_version
770 .or(self.opts.unstable_opts.dwarf_version)
771 .unwrap_or(self.target.default_dwarf_version)
772 }
773
774 pub fn stack_protector(&self) -> StackProtector {
775 if self.target.options.supports_stack_protector {
776 self.opts.unstable_opts.stack_protector
777 } else {
778 StackProtector::None
779 }
780 }
781
782 pub fn must_emit_unwind_tables(&self) -> bool {
783 self.target.requires_uwtable
804 || self.opts.cg.force_unwind_tables.unwrap_or(
805 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
806 )
807 }
808
809 #[inline]
812 pub fn threads(&self) -> usize {
813 self.opts.unstable_opts.threads
814 }
815
816 pub fn codegen_units(&self) -> CodegenUnits {
819 if let Some(n) = self.opts.cli_forced_codegen_units {
820 return CodegenUnits::User(n);
821 }
822 if let Some(n) = self.target.default_codegen_units {
823 return CodegenUnits::Default(n as usize);
824 }
825
826 if self.opts.incremental.is_some() {
830 return CodegenUnits::Default(256);
831 }
832
833 CodegenUnits::Default(16)
884 }
885
886 pub fn teach(&self, code: ErrCode) -> bool {
887 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
888 }
889
890 pub fn edition(&self) -> Edition {
891 self.opts.edition
892 }
893
894 pub fn link_dead_code(&self) -> bool {
895 self.opts.cg.link_dead_code.unwrap_or(false)
896 }
897
898 pub fn filename_display_preference(
899 &self,
900 scope: RemapPathScopeComponents,
901 ) -> FileNameDisplayPreference {
902 assert!(
903 scope.bits().count_ones() == 1,
904 "one and only one scope should be passed to `Session::filename_display_preference`"
905 );
906 if self.opts.unstable_opts.remap_path_scope.contains(scope) {
907 FileNameDisplayPreference::Remapped
908 } else {
909 FileNameDisplayPreference::Local
910 }
911 }
912
913 pub fn apple_deployment_target(&self) -> apple::OSVersion {
918 let min = apple::OSVersion::minimum_deployment_target(&self.target);
919 let env_var = apple::deployment_target_env_var(&self.target.os);
920
921 if let Ok(deployment_target) = env::var(env_var) {
923 match apple::OSVersion::from_str(&deployment_target) {
924 Ok(version) => {
925 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
926 if version < os_min {
931 self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {
932 env_var,
933 version: version.fmt_pretty().to_string(),
934 os_min: os_min.fmt_pretty().to_string(),
935 });
936 }
937
938 version.max(min)
940 }
941 Err(error) => {
942 self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });
943 min
944 }
945 }
946 } else {
947 min
949 }
950 }
951}
952
953#[allow(rustc::bad_opt_access)]
955fn default_emitter(
956 sopts: &config::Options,
957 source_map: Arc<SourceMap>,
958 bundle: Option<Arc<FluentBundle>>,
959 fallback_bundle: LazyFallbackBundle,
960) -> Box<DynEmitter> {
961 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
962 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
963 let terminal_url = match sopts.unstable_opts.terminal_urls {
964 TerminalUrl::Auto => {
965 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
966 (Ok("truecolor"), Ok("xterm-256color"))
967 if sopts.unstable_features.is_nightly_build() =>
968 {
969 TerminalUrl::Yes
970 }
971 _ => TerminalUrl::No,
972 }
973 }
974 t => t,
975 };
976
977 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
978
979 match sopts.error_format {
980 config::ErrorOutputType::HumanReadable { kind, color_config } => {
981 let short = kind.short();
982
983 if let HumanReadableErrorType::AnnotateSnippet = kind {
984 let emitter = AnnotateSnippetEmitter::new(
985 source_map,
986 bundle,
987 fallback_bundle,
988 short,
989 macro_backtrace,
990 );
991 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
992 } else {
993 let emitter = HumanEmitter::new(stderr_destination(color_config), fallback_bundle)
994 .fluent_bundle(bundle)
995 .sm(source_map)
996 .short_message(short)
997 .diagnostic_width(sopts.diagnostic_width)
998 .macro_backtrace(macro_backtrace)
999 .track_diagnostics(track_diagnostics)
1000 .terminal_url(terminal_url)
1001 .theme(if let HumanReadableErrorType::Unicode = kind {
1002 OutputTheme::Unicode
1003 } else {
1004 OutputTheme::Ascii
1005 })
1006 .ignored_directories_in_source_blocks(
1007 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1008 );
1009 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1010 }
1011 }
1012 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
1013 JsonEmitter::new(
1014 Box::new(io::BufWriter::new(io::stderr())),
1015 source_map,
1016 fallback_bundle,
1017 pretty,
1018 json_rendered,
1019 color_config,
1020 )
1021 .fluent_bundle(bundle)
1022 .ui_testing(sopts.unstable_opts.ui_testing)
1023 .ignored_directories_in_source_blocks(
1024 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1025 )
1026 .diagnostic_width(sopts.diagnostic_width)
1027 .macro_backtrace(macro_backtrace)
1028 .track_diagnostics(track_diagnostics)
1029 .terminal_url(terminal_url),
1030 ),
1031 }
1032}
1033
1034#[allow(rustc::bad_opt_access)]
1036#[allow(rustc::untranslatable_diagnostic)] pub fn build_session(
1038 sopts: config::Options,
1039 io: CompilerIO,
1040 bundle: Option<Arc<rustc_errors::FluentBundle>>,
1041 registry: rustc_errors::registry::Registry,
1042 fluent_resources: Vec<&'static str>,
1043 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1044 target: Target,
1045 sysroot: PathBuf,
1046 cfg_version: &'static str,
1047 ice_file: Option<PathBuf>,
1048 using_internal_features: &'static AtomicBool,
1049 expanded_args: Vec<String>,
1050) -> Session {
1051 let warnings_allow = sopts
1055 .lint_opts
1056 .iter()
1057 .rfind(|&(key, _)| *key == "warnings")
1058 .is_some_and(|&(_, level)| level == lint::Allow);
1059 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1060 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1061
1062 let fallback_bundle = fallback_fluent_bundle(
1063 fluent_resources,
1064 sopts.unstable_opts.translate_directionality_markers,
1065 );
1066 let source_map = rustc_span::source_map::get_source_map().unwrap();
1067 let emitter = default_emitter(&sopts, Arc::clone(&source_map), bundle, fallback_bundle);
1068
1069 let mut dcx = DiagCtxt::new(emitter)
1070 .with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings))
1071 .with_registry(registry);
1072 if let Some(ice_file) = ice_file {
1073 dcx = dcx.with_ice_file(ice_file);
1074 }
1075
1076 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1077 let (host, target_warnings) = Target::search(&host_triple, &sysroot)
1078 .unwrap_or_else(|e| dcx.handle().fatal(format!("Error loading host specification: {e}")));
1079 for warning in target_warnings.warning_messages() {
1080 dcx.handle().warn(warning)
1081 }
1082
1083 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1084 {
1085 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1086
1087 let profiler = SelfProfiler::new(
1088 directory,
1089 sopts.crate_name.as_deref(),
1090 sopts.unstable_opts.self_profile_events.as_deref(),
1091 &sopts.unstable_opts.self_profile_counter,
1092 );
1093 match profiler {
1094 Ok(profiler) => Some(Arc::new(profiler)),
1095 Err(e) => {
1096 dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1097 None
1098 }
1099 }
1100 } else {
1101 None
1102 };
1103
1104 let mut psess = ParseSess::with_dcx(dcx, source_map);
1105 psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1106
1107 let host_triple = config::host_tuple();
1108 let target_triple = sopts.target_triple.tuple();
1109 let host_tlib_path = Arc::new(SearchPath::from_sysroot_and_triple(&sysroot, host_triple));
1111 let target_tlib_path = if host_triple == target_triple {
1112 Arc::clone(&host_tlib_path)
1115 } else {
1116 Arc::new(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1117 };
1118
1119 let prof = SelfProfilerRef::new(
1120 self_profiler,
1121 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1122 );
1123
1124 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1125 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1126 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1127 _ => CtfeBacktrace::Disabled,
1128 });
1129
1130 let asm_arch = if target.allow_asm { InlineAsmArch::from_str(&target.arch).ok() } else { None };
1131 let target_filesearch =
1132 filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1133 let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1134
1135 let invocation_temp = sopts
1136 .incremental
1137 .as_ref()
1138 .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
1139
1140 let sess = Session {
1141 target,
1142 host,
1143 opts: sopts,
1144 target_tlib_path,
1145 psess,
1146 sysroot,
1147 io,
1148 incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1149 prof,
1150 code_stats: Default::default(),
1151 lint_store: None,
1152 driver_lint_caps,
1153 ctfe_backtrace,
1154 miri_unleashed_features: Lock::new(Default::default()),
1155 asm_arch,
1156 target_features: Default::default(),
1157 unstable_target_features: Default::default(),
1158 cfg_version,
1159 using_internal_features,
1160 expanded_args,
1161 target_filesearch,
1162 host_filesearch,
1163 invocation_temp,
1164 };
1165
1166 validate_commandline_args_with_session_available(&sess);
1167
1168 sess
1169}
1170
1171#[allow(rustc::bad_opt_access)]
1177fn validate_commandline_args_with_session_available(sess: &Session) {
1178 if sess.opts.cg.linker_plugin_lto.enabled()
1186 && sess.opts.cg.prefer_dynamic
1187 && sess.target.is_like_windows
1188 {
1189 sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1190 }
1191
1192 if let Some(ref path) = sess.opts.cg.profile_use {
1195 if !path.exists() {
1196 sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1197 }
1198 }
1199
1200 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1202 if !path.exists() {
1203 sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1204 }
1205 }
1206
1207 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1209 if sess.target.requires_uwtable && !include_uwtables {
1210 sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1211 }
1212 }
1213
1214 let supported_sanitizers = sess.target.options.supported_sanitizers;
1216 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1217 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == "aarch64" {
1220 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1221 }
1222 match unsupported_sanitizers.into_iter().count() {
1223 0 => {}
1224 1 => {
1225 sess.dcx()
1226 .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1227 }
1228 _ => {
1229 sess.dcx().emit_err(errors::SanitizersNotSupported {
1230 us: unsupported_sanitizers.to_string(),
1231 });
1232 }
1233 }
1234
1235 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1237 sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1238 first: first.to_string(),
1239 second: second.to_string(),
1240 });
1241 }
1242
1243 if sess.crt_static(None)
1245 && !sess.opts.unstable_opts.sanitizer.is_empty()
1246 && !sess.target.is_like_msvc
1247 {
1248 sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1249 }
1250
1251 if sess.is_sanitizer_cfi_enabled()
1253 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1254 {
1255 sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1256 }
1257
1258 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy() != PanicStrategy::Abort {
1260 sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1261 }
1262
1263 if sess.is_sanitizer_cfi_enabled()
1265 && sess.lto() == config::Lto::Fat
1266 && (sess.codegen_units().as_usize() != 1)
1267 {
1268 sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1269 }
1270
1271 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1273 if !sess.is_sanitizer_cfi_enabled() {
1274 sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1275 }
1276 }
1277
1278 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1280 sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);
1281 }
1282
1283 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1285 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1286 sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1287 }
1288 }
1289
1290 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1292 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1293 sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1294 }
1295 }
1296
1297 if sess.is_split_lto_unit_enabled()
1299 && !(sess.lto() == config::Lto::Fat
1300 || sess.lto() == config::Lto::Thin
1301 || sess.opts.cg.linker_plugin_lto.enabled())
1302 {
1303 sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1304 }
1305
1306 if sess.lto() != config::Lto::Fat {
1308 if sess.opts.unstable_opts.virtual_function_elimination {
1309 sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1310 }
1311 }
1312
1313 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1314 if !sess.target.options.supports_stack_protector {
1315 sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1316 stack_protector: sess.opts.unstable_opts.stack_protector,
1317 target_triple: &sess.opts.target_triple,
1318 });
1319 }
1320 }
1321
1322 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1323 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1324 sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1325 target_triple: &sess.opts.target_triple,
1326 })
1327 }
1328 }
1329
1330 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != "aarch64" {
1331 sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1332 }
1333
1334 if let Some(dwarf_version) =
1335 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1336 {
1337 if dwarf_version < 2 || dwarf_version > 5 {
1339 sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1340 }
1341 }
1342
1343 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1344 && !sess.opts.unstable_opts.unstable_options
1345 {
1346 sess.dcx()
1347 .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1348 }
1349
1350 if sess.opts.unstable_opts.embed_source {
1351 let dwarf_version = sess.dwarf_version();
1352
1353 if dwarf_version < 5 {
1354 sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1355 }
1356
1357 if sess.opts.debuginfo == DebugInfo::None {
1358 sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1359 }
1360 }
1361
1362 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1363 sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1364 }
1365
1366 if let Some(flavor) = sess.opts.cg.linker_flavor {
1367 if let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor) {
1368 let flavor = flavor.desc();
1369 sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1370 }
1371 }
1372
1373 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1374 if sess.target.arch != "x86" && sess.target.arch != "x86_64" {
1375 sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1376 }
1377 }
1378
1379 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1380 if regparm > 3 {
1381 sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1382 }
1383 if sess.target.arch != "x86" {
1384 sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1385 }
1386 }
1387 if sess.opts.unstable_opts.reg_struct_return {
1388 if sess.target.arch != "x86" {
1389 sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1390 }
1391 }
1392
1393 match sess.opts.unstable_opts.function_return {
1397 FunctionReturn::Keep => (),
1398 FunctionReturn::ThunkExtern => {
1399 if let Some(code_model) = sess.code_model()
1402 && code_model == CodeModel::Large
1403 {
1404 sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1405 }
1406 }
1407 }
1408
1409 if sess.opts.cg.soft_float {
1410 if sess.target.arch == "arm" {
1411 sess.dcx().emit_warn(errors::SoftFloatDeprecated);
1412 } else {
1413 sess.dcx().emit_warn(errors::SoftFloatIgnored);
1416 }
1417 }
1418}
1419
1420#[derive(Debug)]
1422enum IncrCompSession {
1423 NotInitialized,
1426 Active { session_directory: PathBuf, _lock_file: flock::Lock },
1431 Finalized { session_directory: PathBuf },
1434 InvalidBecauseOfErrors { session_directory: PathBuf },
1438}
1439
1440pub struct EarlyDiagCtxt {
1442 dcx: DiagCtxt,
1443}
1444
1445impl EarlyDiagCtxt {
1446 pub fn new(output: ErrorOutputType) -> Self {
1447 let emitter = mk_emitter(output);
1448 Self { dcx: DiagCtxt::new(emitter) }
1449 }
1450
1451 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1454 assert!(self.dcx.handle().has_errors().is_none());
1455
1456 let emitter = mk_emitter(output);
1457 self.dcx = DiagCtxt::new(emitter);
1458 }
1459
1460 #[allow(rustc::untranslatable_diagnostic)]
1461 #[allow(rustc::diagnostic_outside_of_impl)]
1462 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1463 self.dcx.handle().note(msg)
1464 }
1465
1466 #[allow(rustc::untranslatable_diagnostic)]
1467 #[allow(rustc::diagnostic_outside_of_impl)]
1468 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1469 self.dcx.handle().struct_help(msg).emit()
1470 }
1471
1472 #[allow(rustc::untranslatable_diagnostic)]
1473 #[allow(rustc::diagnostic_outside_of_impl)]
1474 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1475 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1476 self.dcx.handle().err(msg)
1477 }
1478
1479 #[allow(rustc::untranslatable_diagnostic)]
1480 #[allow(rustc::diagnostic_outside_of_impl)]
1481 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1482 self.dcx.handle().fatal(msg)
1483 }
1484
1485 #[allow(rustc::untranslatable_diagnostic)]
1486 #[allow(rustc::diagnostic_outside_of_impl)]
1487 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1488 self.dcx.handle().struct_fatal(msg)
1489 }
1490
1491 #[allow(rustc::untranslatable_diagnostic)]
1492 #[allow(rustc::diagnostic_outside_of_impl)]
1493 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1494 self.dcx.handle().warn(msg)
1495 }
1496
1497 #[allow(rustc::untranslatable_diagnostic)]
1498 #[allow(rustc::diagnostic_outside_of_impl)]
1499 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1500 self.dcx.handle().struct_warn(msg)
1501 }
1502}
1503
1504fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1505 let fallback_bundle =
1508 fallback_fluent_bundle(vec![rustc_errors::DEFAULT_LOCALE_RESOURCE], false);
1509 let emitter: Box<DynEmitter> = match output {
1510 config::ErrorOutputType::HumanReadable { kind, color_config } => {
1511 let short = kind.short();
1512 Box::new(
1513 HumanEmitter::new(stderr_destination(color_config), fallback_bundle)
1514 .theme(if let HumanReadableErrorType::Unicode = kind {
1515 OutputTheme::Unicode
1516 } else {
1517 OutputTheme::Ascii
1518 })
1519 .short_message(short),
1520 )
1521 }
1522 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1523 Box::new(JsonEmitter::new(
1524 Box::new(io::BufWriter::new(io::stderr())),
1525 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1526 fallback_bundle,
1527 pretty,
1528 json_rendered,
1529 color_config,
1530 ))
1531 }
1532 };
1533 emitter
1534}
1535
1536pub trait RemapFileNameExt {
1537 type Output<'a>
1538 where
1539 Self: 'a;
1540
1541 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_>;
1545}
1546
1547impl RemapFileNameExt for rustc_span::FileName {
1548 type Output<'a> = rustc_span::FileNameDisplay<'a>;
1549
1550 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1551 assert!(
1552 scope.bits().count_ones() == 1,
1553 "one and only one scope should be passed to for_scope"
1554 );
1555 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1556 self.prefer_remapped_unconditionaly()
1557 } else {
1558 self.prefer_local()
1559 }
1560 }
1561}
1562
1563impl RemapFileNameExt for rustc_span::RealFileName {
1564 type Output<'a> = &'a Path;
1565
1566 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1567 assert!(
1568 scope.bits().count_ones() == 1,
1569 "one and only one scope should be passed to for_scope"
1570 );
1571 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1572 self.remapped_path_if_available()
1573 } else {
1574 self.local_path_if_available()
1575 }
1576 }
1577}