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 coverage_inject_unused_local_file(&self) -> bool {
376 self.opts.unstable_opts.coverage_options.inject_unused_local_file
377 }
378
379 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
380 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::CFI)
381 }
382
383 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
384 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
385 }
386
387 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
388 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
389 }
390
391 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
392 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
393 }
394
395 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
396 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
397 }
398
399 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
400 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
401 }
402
403 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
404 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::KCFI)
405 }
406
407 pub fn is_split_lto_unit_enabled(&self) -> bool {
408 self.opts.unstable_opts.split_lto_unit == Some(true)
409 }
410
411 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
413 if !self.target.crt_static_respected {
414 return self.target.crt_static_default;
416 }
417
418 let requested_features = self.opts.cg.target_feature.split(',');
419 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
420 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
421
422 #[allow(rustc::bad_opt_access)]
424 if found_positive || found_negative {
425 found_positive
426 } else if crate_type == Some(CrateType::ProcMacro)
427 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
428 {
429 false
433 } else {
434 self.target.crt_static_default
435 }
436 }
437
438 pub fn is_wasi_reactor(&self) -> bool {
439 self.target.options.os == "wasi"
440 && matches!(
441 self.opts.unstable_opts.wasi_exec_model,
442 Some(config::WasiExecModel::Reactor)
443 )
444 }
445
446 pub fn target_can_use_split_dwarf(&self) -> bool {
448 self.target.debuginfo_kind == DebuginfoKind::Dwarf
449 }
450
451 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
452 format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.as_u64())
453 }
454
455 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
456 &self.target_filesearch
457 }
458 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
459 &self.host_filesearch
460 }
461
462 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
466 let bin_path = filesearch::make_target_bin_path(&self.sysroot, config::host_tuple());
467 let fallback_sysroot_paths = filesearch::sysroot_candidates()
468 .into_iter()
469 .filter(|sysroot| *sysroot != self.sysroot)
471 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
472 let search_paths = std::iter::once(bin_path).chain(fallback_sysroot_paths);
473
474 if self_contained {
475 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
479 } else {
480 search_paths.collect()
481 }
482 }
483
484 pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
485 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
486
487 if let IncrCompSession::NotInitialized = *incr_comp_session {
488 } else {
489 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
490 }
491
492 *incr_comp_session =
493 IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
494 }
495
496 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
497 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
498
499 if let IncrCompSession::Active { .. } = *incr_comp_session {
500 } else {
501 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
502 }
503
504 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
506 }
507
508 pub fn mark_incr_comp_session_as_invalid(&self) {
509 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
510
511 let session_directory = match *incr_comp_session {
512 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
513 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
514 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
515 };
516
517 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
519 }
520
521 pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
522 let incr_comp_session = self.incr_comp_session.borrow();
523 ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
524 IncrCompSession::NotInitialized => panic!(
525 "trying to get session directory from `IncrCompSession`: {:?}",
526 *incr_comp_session,
527 ),
528 IncrCompSession::Active { ref session_directory, .. }
529 | IncrCompSession::Finalized { ref session_directory }
530 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
531 session_directory
532 }
533 })
534 }
535
536 pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
537 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
538 }
539
540 pub fn is_rust_2015(&self) -> bool {
542 self.edition().is_rust_2015()
543 }
544
545 pub fn at_least_rust_2018(&self) -> bool {
547 self.edition().at_least_rust_2018()
548 }
549
550 pub fn at_least_rust_2021(&self) -> bool {
552 self.edition().at_least_rust_2021()
553 }
554
555 pub fn at_least_rust_2024(&self) -> bool {
557 self.edition().at_least_rust_2024()
558 }
559
560 pub fn needs_plt(&self) -> bool {
562 let want_plt = self.target.plt_by_default;
565
566 let dbg_opts = &self.opts.unstable_opts;
567
568 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
569
570 let full_relro = RelroLevel::Full == relro_level;
574
575 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
578 }
579
580 pub fn emit_lifetime_markers(&self) -> bool {
582 self.opts.optimize != config::OptLevel::No
583 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
587 }
588
589 pub fn diagnostic_width(&self) -> usize {
590 let default_column_width = 140;
591 if let Some(width) = self.opts.diagnostic_width {
592 width
593 } else if self.opts.unstable_opts.ui_testing {
594 default_column_width
595 } else {
596 termize::dimensions().map_or(default_column_width, |(w, _)| w)
597 }
598 }
599
600 pub fn default_visibility(&self) -> SymbolVisibility {
602 self.opts
603 .unstable_opts
604 .default_visibility
605 .or(self.target.options.default_visibility)
606 .unwrap_or(SymbolVisibility::Interposable)
607 }
608
609 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
610 if verbatim {
611 ("", "")
612 } else {
613 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
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
809 || self.opts.cg.force_unwind_tables.unwrap_or(
810 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
811 )
812 }
813
814 #[inline]
817 pub fn threads(&self) -> usize {
818 self.opts.unstable_opts.threads
819 }
820
821 pub fn codegen_units(&self) -> CodegenUnits {
824 if let Some(n) = self.opts.cli_forced_codegen_units {
825 return CodegenUnits::User(n);
826 }
827 if let Some(n) = self.target.default_codegen_units {
828 return CodegenUnits::Default(n as usize);
829 }
830
831 if self.opts.incremental.is_some() {
835 return CodegenUnits::Default(256);
836 }
837
838 CodegenUnits::Default(16)
889 }
890
891 pub fn teach(&self, code: ErrCode) -> bool {
892 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
893 }
894
895 pub fn edition(&self) -> Edition {
896 self.opts.edition
897 }
898
899 pub fn link_dead_code(&self) -> bool {
900 self.opts.cg.link_dead_code.unwrap_or(false)
901 }
902
903 pub fn filename_display_preference(
904 &self,
905 scope: RemapPathScopeComponents,
906 ) -> FileNameDisplayPreference {
907 assert!(
908 scope.bits().count_ones() == 1,
909 "one and only one scope should be passed to `Session::filename_display_preference`"
910 );
911 if self.opts.unstable_opts.remap_path_scope.contains(scope) {
912 FileNameDisplayPreference::Remapped
913 } else {
914 FileNameDisplayPreference::Local
915 }
916 }
917
918 pub fn apple_deployment_target(&self) -> apple::OSVersion {
923 let min = apple::OSVersion::minimum_deployment_target(&self.target);
924 let env_var = apple::deployment_target_env_var(&self.target.os);
925
926 if let Ok(deployment_target) = env::var(env_var) {
928 match apple::OSVersion::from_str(&deployment_target) {
929 Ok(version) => {
930 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
931 if version < os_min {
936 self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {
937 env_var,
938 version: version.fmt_pretty().to_string(),
939 os_min: os_min.fmt_pretty().to_string(),
940 });
941 }
942
943 version.max(min)
945 }
946 Err(error) => {
947 self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });
948 min
949 }
950 }
951 } else {
952 min
954 }
955 }
956}
957
958#[allow(rustc::bad_opt_access)]
960fn default_emitter(
961 sopts: &config::Options,
962 source_map: Arc<SourceMap>,
963 bundle: Option<Arc<FluentBundle>>,
964 fallback_bundle: LazyFallbackBundle,
965) -> Box<DynEmitter> {
966 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
967 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
968 let terminal_url = match sopts.unstable_opts.terminal_urls {
969 TerminalUrl::Auto => {
970 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
971 (Ok("truecolor"), Ok("xterm-256color"))
972 if sopts.unstable_features.is_nightly_build() =>
973 {
974 TerminalUrl::Yes
975 }
976 _ => TerminalUrl::No,
977 }
978 }
979 t => t,
980 };
981
982 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
983
984 match sopts.error_format {
985 config::ErrorOutputType::HumanReadable { kind, color_config } => {
986 let short = kind.short();
987
988 if let HumanReadableErrorType::AnnotateSnippet = kind {
989 let emitter = AnnotateSnippetEmitter::new(
990 source_map,
991 bundle,
992 fallback_bundle,
993 short,
994 macro_backtrace,
995 );
996 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
997 } else {
998 let emitter = HumanEmitter::new(stderr_destination(color_config), fallback_bundle)
999 .fluent_bundle(bundle)
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 fallback_bundle,
1022 pretty,
1023 json_rendered,
1024 color_config,
1025 )
1026 .fluent_bundle(bundle)
1027 .ui_testing(sopts.unstable_opts.ui_testing)
1028 .ignored_directories_in_source_blocks(
1029 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1030 )
1031 .diagnostic_width(sopts.diagnostic_width)
1032 .macro_backtrace(macro_backtrace)
1033 .track_diagnostics(track_diagnostics)
1034 .terminal_url(terminal_url),
1035 ),
1036 }
1037}
1038
1039#[allow(rustc::bad_opt_access)]
1041#[allow(rustc::untranslatable_diagnostic)] pub fn build_session(
1043 sopts: config::Options,
1044 io: CompilerIO,
1045 bundle: Option<Arc<rustc_errors::FluentBundle>>,
1046 registry: rustc_errors::registry::Registry,
1047 fluent_resources: Vec<&'static str>,
1048 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1049 target: Target,
1050 sysroot: PathBuf,
1051 cfg_version: &'static str,
1052 ice_file: Option<PathBuf>,
1053 using_internal_features: &'static AtomicBool,
1054 expanded_args: Vec<String>,
1055) -> Session {
1056 let warnings_allow = sopts
1060 .lint_opts
1061 .iter()
1062 .rfind(|&(key, _)| *key == "warnings")
1063 .is_some_and(|&(_, level)| level == lint::Allow);
1064 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1065 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1066
1067 let fallback_bundle = fallback_fluent_bundle(
1068 fluent_resources,
1069 sopts.unstable_opts.translate_directionality_markers,
1070 );
1071 let source_map = rustc_span::source_map::get_source_map().unwrap();
1072 let emitter = default_emitter(&sopts, Arc::clone(&source_map), bundle, fallback_bundle);
1073
1074 let mut dcx = DiagCtxt::new(emitter)
1075 .with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings))
1076 .with_registry(registry);
1077 if let Some(ice_file) = ice_file {
1078 dcx = dcx.with_ice_file(ice_file);
1079 }
1080
1081 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1082 let (host, target_warnings) = Target::search(&host_triple, &sysroot)
1083 .unwrap_or_else(|e| dcx.handle().fatal(format!("Error loading host specification: {e}")));
1084 for warning in target_warnings.warning_messages() {
1085 dcx.handle().warn(warning)
1086 }
1087
1088 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1089 {
1090 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1091
1092 let profiler = SelfProfiler::new(
1093 directory,
1094 sopts.crate_name.as_deref(),
1095 sopts.unstable_opts.self_profile_events.as_deref(),
1096 &sopts.unstable_opts.self_profile_counter,
1097 );
1098 match profiler {
1099 Ok(profiler) => Some(Arc::new(profiler)),
1100 Err(e) => {
1101 dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1102 None
1103 }
1104 }
1105 } else {
1106 None
1107 };
1108
1109 let mut psess = ParseSess::with_dcx(dcx, source_map);
1110 psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1111
1112 let host_triple = config::host_tuple();
1113 let target_triple = sopts.target_triple.tuple();
1114 let host_tlib_path = Arc::new(SearchPath::from_sysroot_and_triple(&sysroot, host_triple));
1116 let target_tlib_path = if host_triple == target_triple {
1117 Arc::clone(&host_tlib_path)
1120 } else {
1121 Arc::new(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1122 };
1123
1124 let prof = SelfProfilerRef::new(
1125 self_profiler,
1126 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1127 );
1128
1129 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1130 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1131 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1132 _ => CtfeBacktrace::Disabled,
1133 });
1134
1135 let asm_arch = if target.allow_asm { InlineAsmArch::from_str(&target.arch).ok() } else { None };
1136 let target_filesearch =
1137 filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1138 let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1139
1140 let invocation_temp = sopts
1141 .incremental
1142 .as_ref()
1143 .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
1144
1145 let sess = Session {
1146 target,
1147 host,
1148 opts: sopts,
1149 target_tlib_path,
1150 psess,
1151 sysroot,
1152 io,
1153 incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1154 prof,
1155 code_stats: Default::default(),
1156 lint_store: None,
1157 driver_lint_caps,
1158 ctfe_backtrace,
1159 miri_unleashed_features: Lock::new(Default::default()),
1160 asm_arch,
1161 target_features: Default::default(),
1162 unstable_target_features: Default::default(),
1163 cfg_version,
1164 using_internal_features,
1165 expanded_args,
1166 target_filesearch,
1167 host_filesearch,
1168 invocation_temp,
1169 };
1170
1171 validate_commandline_args_with_session_available(&sess);
1172
1173 sess
1174}
1175
1176#[allow(rustc::bad_opt_access)]
1182fn validate_commandline_args_with_session_available(sess: &Session) {
1183 if sess.opts.cg.linker_plugin_lto.enabled()
1191 && sess.opts.cg.prefer_dynamic
1192 && sess.target.is_like_windows
1193 {
1194 sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1195 }
1196
1197 if let Some(ref path) = sess.opts.cg.profile_use {
1200 if !path.exists() {
1201 sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1202 }
1203 }
1204
1205 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1207 if !path.exists() {
1208 sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1209 }
1210 }
1211
1212 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1214 if sess.target.requires_uwtable && !include_uwtables {
1215 sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1216 }
1217 }
1218
1219 let supported_sanitizers = sess.target.options.supported_sanitizers;
1221 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1222 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == "aarch64" {
1225 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1226 }
1227 match unsupported_sanitizers.into_iter().count() {
1228 0 => {}
1229 1 => {
1230 sess.dcx()
1231 .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1232 }
1233 _ => {
1234 sess.dcx().emit_err(errors::SanitizersNotSupported {
1235 us: unsupported_sanitizers.to_string(),
1236 });
1237 }
1238 }
1239
1240 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1242 sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1243 first: first.to_string(),
1244 second: second.to_string(),
1245 });
1246 }
1247
1248 if sess.crt_static(None)
1250 && !sess.opts.unstable_opts.sanitizer.is_empty()
1251 && !sess.target.is_like_msvc
1252 {
1253 sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1254 }
1255
1256 if sess.is_sanitizer_cfi_enabled()
1258 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1259 {
1260 sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1261 }
1262
1263 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy() != PanicStrategy::Abort {
1265 sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1266 }
1267
1268 if sess.is_sanitizer_cfi_enabled()
1270 && sess.lto() == config::Lto::Fat
1271 && (sess.codegen_units().as_usize() != 1)
1272 {
1273 sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1274 }
1275
1276 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1278 if !sess.is_sanitizer_cfi_enabled() {
1279 sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1280 }
1281 }
1282
1283 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1285 sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);
1286 }
1287
1288 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1290 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1291 sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1292 }
1293 }
1294
1295 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1297 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1298 sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1299 }
1300 }
1301
1302 if sess.is_split_lto_unit_enabled()
1304 && !(sess.lto() == config::Lto::Fat
1305 || sess.lto() == config::Lto::Thin
1306 || sess.opts.cg.linker_plugin_lto.enabled())
1307 {
1308 sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1309 }
1310
1311 if sess.lto() != config::Lto::Fat {
1313 if sess.opts.unstable_opts.virtual_function_elimination {
1314 sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1315 }
1316 }
1317
1318 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1319 if !sess.target.options.supports_stack_protector {
1320 sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1321 stack_protector: sess.opts.unstable_opts.stack_protector,
1322 target_triple: &sess.opts.target_triple,
1323 });
1324 }
1325 }
1326
1327 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1328 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1329 sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1330 target_triple: &sess.opts.target_triple,
1331 })
1332 }
1333 }
1334
1335 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != "aarch64" {
1336 sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1337 }
1338
1339 if let Some(dwarf_version) =
1340 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1341 {
1342 if dwarf_version < 2 || dwarf_version > 5 {
1344 sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1345 }
1346 }
1347
1348 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1349 && !sess.opts.unstable_opts.unstable_options
1350 {
1351 sess.dcx()
1352 .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1353 }
1354
1355 if sess.opts.unstable_opts.embed_source {
1356 let dwarf_version = sess.dwarf_version();
1357
1358 if dwarf_version < 5 {
1359 sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1360 }
1361
1362 if sess.opts.debuginfo == DebugInfo::None {
1363 sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1364 }
1365 }
1366
1367 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1368 sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1369 }
1370
1371 if let Some(flavor) = sess.opts.cg.linker_flavor {
1372 if let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor) {
1373 let flavor = flavor.desc();
1374 sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1375 }
1376 }
1377
1378 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1379 if sess.target.arch != "x86" && sess.target.arch != "x86_64" {
1380 sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1381 }
1382 }
1383
1384 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1385 if regparm > 3 {
1386 sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1387 }
1388 if sess.target.arch != "x86" {
1389 sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1390 }
1391 }
1392 if sess.opts.unstable_opts.reg_struct_return {
1393 if sess.target.arch != "x86" {
1394 sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1395 }
1396 }
1397
1398 match sess.opts.unstable_opts.function_return {
1402 FunctionReturn::Keep => (),
1403 FunctionReturn::ThunkExtern => {
1404 if let Some(code_model) = sess.code_model()
1407 && code_model == CodeModel::Large
1408 {
1409 sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1410 }
1411 }
1412 }
1413
1414 if sess.opts.cg.soft_float {
1415 if sess.target.arch == "arm" {
1416 sess.dcx().emit_warn(errors::SoftFloatDeprecated);
1417 } else {
1418 sess.dcx().emit_warn(errors::SoftFloatIgnored);
1421 }
1422 }
1423}
1424
1425#[derive(Debug)]
1427enum IncrCompSession {
1428 NotInitialized,
1431 Active { session_directory: PathBuf, _lock_file: flock::Lock },
1436 Finalized { session_directory: PathBuf },
1439 InvalidBecauseOfErrors { session_directory: PathBuf },
1443}
1444
1445pub struct EarlyDiagCtxt {
1447 dcx: DiagCtxt,
1448}
1449
1450impl EarlyDiagCtxt {
1451 pub fn new(output: ErrorOutputType) -> Self {
1452 let emitter = mk_emitter(output);
1453 Self { dcx: DiagCtxt::new(emitter) }
1454 }
1455
1456 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1459 assert!(self.dcx.handle().has_errors().is_none());
1460
1461 let emitter = mk_emitter(output);
1462 self.dcx = DiagCtxt::new(emitter);
1463 }
1464
1465 #[allow(rustc::untranslatable_diagnostic)]
1466 #[allow(rustc::diagnostic_outside_of_impl)]
1467 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1468 self.dcx.handle().note(msg)
1469 }
1470
1471 #[allow(rustc::untranslatable_diagnostic)]
1472 #[allow(rustc::diagnostic_outside_of_impl)]
1473 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1474 self.dcx.handle().struct_help(msg).emit()
1475 }
1476
1477 #[allow(rustc::untranslatable_diagnostic)]
1478 #[allow(rustc::diagnostic_outside_of_impl)]
1479 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1480 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1481 self.dcx.handle().err(msg)
1482 }
1483
1484 #[allow(rustc::untranslatable_diagnostic)]
1485 #[allow(rustc::diagnostic_outside_of_impl)]
1486 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1487 self.dcx.handle().fatal(msg)
1488 }
1489
1490 #[allow(rustc::untranslatable_diagnostic)]
1491 #[allow(rustc::diagnostic_outside_of_impl)]
1492 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1493 self.dcx.handle().struct_fatal(msg)
1494 }
1495
1496 #[allow(rustc::untranslatable_diagnostic)]
1497 #[allow(rustc::diagnostic_outside_of_impl)]
1498 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1499 self.dcx.handle().warn(msg)
1500 }
1501
1502 #[allow(rustc::untranslatable_diagnostic)]
1503 #[allow(rustc::diagnostic_outside_of_impl)]
1504 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1505 self.dcx.handle().struct_warn(msg)
1506 }
1507}
1508
1509fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1510 let fallback_bundle =
1513 fallback_fluent_bundle(vec![rustc_errors::DEFAULT_LOCALE_RESOURCE], false);
1514 let emitter: Box<DynEmitter> = match output {
1515 config::ErrorOutputType::HumanReadable { kind, color_config } => {
1516 let short = kind.short();
1517 Box::new(
1518 HumanEmitter::new(stderr_destination(color_config), fallback_bundle)
1519 .theme(if let HumanReadableErrorType::Unicode = kind {
1520 OutputTheme::Unicode
1521 } else {
1522 OutputTheme::Ascii
1523 })
1524 .short_message(short),
1525 )
1526 }
1527 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1528 Box::new(JsonEmitter::new(
1529 Box::new(io::BufWriter::new(io::stderr())),
1530 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1531 fallback_bundle,
1532 pretty,
1533 json_rendered,
1534 color_config,
1535 ))
1536 }
1537 };
1538 emitter
1539}
1540
1541pub trait RemapFileNameExt {
1542 type Output<'a>
1543 where
1544 Self: 'a;
1545
1546 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_>;
1550}
1551
1552impl RemapFileNameExt for rustc_span::FileName {
1553 type Output<'a> = rustc_span::FileNameDisplay<'a>;
1554
1555 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1556 assert!(
1557 scope.bits().count_ones() == 1,
1558 "one and only one scope should be passed to for_scope"
1559 );
1560 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1561 self.prefer_remapped_unconditionaly()
1562 } else {
1563 self.prefer_local()
1564 }
1565 }
1566}
1567
1568impl RemapFileNameExt for rustc_span::RealFileName {
1569 type Output<'a> = &'a Path;
1570
1571 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1572 assert!(
1573 scope.bits().count_ones() == 1,
1574 "one and only one scope should be passed to for_scope"
1575 );
1576 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1577 self.remapped_path_if_available()
1578 } else {
1579 self.local_path_if_available()
1580 }
1581 }
1582}