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::parse::{ParseSess, add_feature_diagnostics};
48use crate::search_paths::SearchPath;
49use crate::{errors, filesearch, lint};
50
51#[derive(Clone, Copy)]
53pub enum CtfeBacktrace {
54 Disabled,
56 Capture,
59 Immediate,
61}
62
63#[derive(Clone, Copy, Debug, HashStable_Generic)]
66pub struct Limit(pub usize);
67
68impl Limit {
69 pub fn new(value: usize) -> Self {
71 Limit(value)
72 }
73
74 pub fn unlimited() -> Self {
76 Limit(usize::MAX)
77 }
78
79 #[inline]
82 pub fn value_within_limit(&self, value: usize) -> bool {
83 value <= self.0
84 }
85}
86
87impl From<usize> for Limit {
88 fn from(value: usize) -> Self {
89 Self::new(value)
90 }
91}
92
93impl fmt::Display for Limit {
94 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95 self.0.fmt(f)
96 }
97}
98
99impl Div<usize> for Limit {
100 type Output = Limit;
101
102 fn div(self, rhs: usize) -> Self::Output {
103 Limit::new(self.0 / rhs)
104 }
105}
106
107impl Mul<usize> for Limit {
108 type Output = Limit;
109
110 fn mul(self, rhs: usize) -> Self::Output {
111 Limit::new(self.0 * rhs)
112 }
113}
114
115impl rustc_errors::IntoDiagArg for Limit {
116 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
117 self.to_string().into_diag_arg(&mut None)
118 }
119}
120
121#[derive(Clone, Copy, Debug, HashStable_Generic)]
122pub struct Limits {
123 pub recursion_limit: Limit,
126 pub move_size_limit: Limit,
129 pub type_length_limit: Limit,
131 pub pattern_complexity_limit: Limit,
133}
134
135pub struct CompilerIO {
136 pub input: Input,
137 pub output_dir: Option<PathBuf>,
138 pub output_file: Option<OutFileName>,
139 pub temps_dir: Option<PathBuf>,
140}
141
142pub trait LintStoreMarker: Any + DynSync + DynSend {}
143
144pub struct Session {
147 pub target: Target,
148 pub host: Target,
149 pub opts: config::Options,
150 pub target_tlib_path: Arc<SearchPath>,
151 pub psess: ParseSess,
152 pub io: CompilerIO,
154
155 incr_comp_session: RwLock<IncrCompSession>,
156
157 pub prof: SelfProfilerRef,
159
160 pub timings: TimingSectionHandler,
162
163 pub code_stats: CodeStats,
165
166 pub lint_store: Option<Arc<dyn LintStoreMarker>>,
168
169 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
171
172 pub ctfe_backtrace: Lock<CtfeBacktrace>,
179
180 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
185
186 pub asm_arch: Option<InlineAsmArch>,
188
189 pub target_features: FxIndexSet<Symbol>,
191
192 pub unstable_target_features: FxIndexSet<Symbol>,
194
195 pub cfg_version: &'static str,
197
198 pub using_internal_features: &'static AtomicBool,
203
204 pub expanded_args: Vec<String>,
209
210 target_filesearch: FileSearch,
211 host_filesearch: FileSearch,
212
213 pub invocation_temp: Option<String>,
220}
221
222#[derive(Clone, Copy)]
223pub enum CodegenUnits {
224 User(usize),
227
228 Default(usize),
232}
233
234impl CodegenUnits {
235 pub fn as_usize(self) -> usize {
236 match self {
237 CodegenUnits::User(n) => n,
238 CodegenUnits::Default(n) => n,
239 }
240 }
241}
242
243impl Session {
244 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
245 self.miri_unleashed_features.lock().push((span, feature_gate));
246 }
247
248 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
249 Some(self.source_map().path_mapping().to_real_filename(self.io.input.opt_path()?))
250 }
251
252 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
253 let mut guar = None;
254 let unleashed_features = self.miri_unleashed_features.lock();
255 if !unleashed_features.is_empty() {
256 let mut must_err = false;
257 self.dcx().emit_warn(errors::SkippingConstChecks {
259 unleashed_features: unleashed_features
260 .iter()
261 .map(|(span, gate)| {
262 gate.map(|gate| {
263 must_err = true;
264 errors::UnleashedFeatureHelp::Named { span: *span, gate }
265 })
266 .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })
267 })
268 .collect(),
269 });
270
271 if must_err && self.dcx().has_errors().is_none() {
273 guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));
275 }
276 }
277 guar
278 }
279
280 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
282 let mut guar = None;
283 guar = guar.or(self.check_miri_unleashed_features());
284 guar = guar.or(self.dcx().emit_stashed_diagnostics());
285 self.dcx().print_error_count();
286 if self.opts.json_future_incompat {
287 self.dcx().emit_future_breakage_report();
288 }
289 guar
290 }
291
292 pub fn is_test_crate(&self) -> bool {
294 self.opts.test
295 }
296
297 #[track_caller]
299 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
300 let mut err = self.dcx().create_err(err);
301 if err.code.is_none() {
302 #[allow(rustc::diagnostic_outside_of_impl)]
303 err.code(E0658);
304 }
305 add_feature_diagnostics(&mut err, self, feature);
306 err
307 }
308
309 pub fn record_trimmed_def_paths(&self) {
312 if self.opts.unstable_opts.print_type_sizes
313 || self.opts.unstable_opts.query_dep_graph
314 || self.opts.unstable_opts.dump_mir.is_some()
315 || self.opts.unstable_opts.unpretty.is_some()
316 || self.prof.is_args_recording_enabled()
317 || self.opts.output_types.contains_key(&OutputType::Mir)
318 || std::env::var_os("RUSTC_LOG").is_some()
319 {
320 return;
321 }
322
323 self.dcx().set_must_produce_diag()
324 }
325
326 #[inline]
327 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
328 self.psess.dcx()
329 }
330
331 #[inline]
332 pub fn source_map(&self) -> &SourceMap {
333 self.psess.source_map()
334 }
335
336 pub fn enable_internal_lints(&self) -> bool {
340 self.unstable_options() && !self.opts.actually_rustdoc
341 }
342
343 pub fn instrument_coverage(&self) -> bool {
344 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
345 }
346
347 pub fn instrument_coverage_branch(&self) -> bool {
348 self.instrument_coverage()
349 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
350 }
351
352 pub fn instrument_coverage_condition(&self) -> bool {
353 self.instrument_coverage()
354 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
355 }
356
357 pub fn coverage_options(&self) -> &CoverageOptions {
361 &self.opts.unstable_opts.coverage_options
362 }
363
364 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
365 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::CFI)
366 }
367
368 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
369 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
370 }
371
372 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
373 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
374 }
375
376 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
377 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
378 }
379
380 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
381 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
382 }
383
384 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
385 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
386 }
387
388 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
389 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::KCFI)
390 }
391
392 pub fn is_split_lto_unit_enabled(&self) -> bool {
393 self.opts.unstable_opts.split_lto_unit == Some(true)
394 }
395
396 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
398 if !self.target.crt_static_respected {
399 return self.target.crt_static_default;
401 }
402
403 let requested_features = self.opts.cg.target_feature.split(',');
404 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
405 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
406
407 #[allow(rustc::bad_opt_access)]
409 if found_positive || found_negative {
410 found_positive
411 } else if crate_type == Some(CrateType::ProcMacro)
412 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
413 {
414 false
418 } else {
419 self.target.crt_static_default
420 }
421 }
422
423 pub fn is_wasi_reactor(&self) -> bool {
424 self.target.options.os == "wasi"
425 && matches!(
426 self.opts.unstable_opts.wasi_exec_model,
427 Some(config::WasiExecModel::Reactor)
428 )
429 }
430
431 pub fn target_can_use_split_dwarf(&self) -> bool {
433 self.target.debuginfo_kind == DebuginfoKind::Dwarf
434 }
435
436 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
437 format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.as_u64())
438 }
439
440 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
441 &self.target_filesearch
442 }
443 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
444 &self.host_filesearch
445 }
446
447 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
451 let search_paths = self
452 .opts
453 .sysroot
454 .all_paths()
455 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
456
457 if self_contained {
458 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
462 } else {
463 search_paths.collect()
464 }
465 }
466
467 pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
468 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
469
470 if let IncrCompSession::NotInitialized = *incr_comp_session {
471 } else {
472 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
473 }
474
475 *incr_comp_session =
476 IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
477 }
478
479 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
480 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
481
482 if let IncrCompSession::Active { .. } = *incr_comp_session {
483 } else {
484 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
485 }
486
487 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
489 }
490
491 pub fn mark_incr_comp_session_as_invalid(&self) {
492 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
493
494 let session_directory = match *incr_comp_session {
495 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
496 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
497 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
498 };
499
500 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
502 }
503
504 pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
505 let incr_comp_session = self.incr_comp_session.borrow();
506 ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
507 IncrCompSession::NotInitialized => panic!(
508 "trying to get session directory from `IncrCompSession`: {:?}",
509 *incr_comp_session,
510 ),
511 IncrCompSession::Active { ref session_directory, .. }
512 | IncrCompSession::Finalized { ref session_directory }
513 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
514 session_directory
515 }
516 })
517 }
518
519 pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
520 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
521 }
522
523 pub fn is_rust_2015(&self) -> bool {
525 self.edition().is_rust_2015()
526 }
527
528 pub fn at_least_rust_2018(&self) -> bool {
530 self.edition().at_least_rust_2018()
531 }
532
533 pub fn at_least_rust_2021(&self) -> bool {
535 self.edition().at_least_rust_2021()
536 }
537
538 pub fn at_least_rust_2024(&self) -> bool {
540 self.edition().at_least_rust_2024()
541 }
542
543 pub fn needs_plt(&self) -> bool {
545 let want_plt = self.target.plt_by_default;
548
549 let dbg_opts = &self.opts.unstable_opts;
550
551 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
552
553 let full_relro = RelroLevel::Full == relro_level;
557
558 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
561 }
562
563 pub fn emit_lifetime_markers(&self) -> bool {
565 self.opts.optimize != config::OptLevel::No
566 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
570 }
571
572 pub fn diagnostic_width(&self) -> usize {
573 let default_column_width = 140;
574 if let Some(width) = self.opts.diagnostic_width {
575 width
576 } else if self.opts.unstable_opts.ui_testing {
577 default_column_width
578 } else {
579 termize::dimensions().map_or(default_column_width, |(w, _)| w)
580 }
581 }
582
583 pub fn default_visibility(&self) -> SymbolVisibility {
585 self.opts
586 .unstable_opts
587 .default_visibility
588 .or(self.target.options.default_visibility)
589 .unwrap_or(SymbolVisibility::Interposable)
590 }
591
592 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
593 if verbatim {
594 ("", "")
595 } else {
596 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
597 }
598 }
599}
600
601#[allow(rustc::bad_opt_access)]
603impl Session {
604 pub fn verbose_internals(&self) -> bool {
605 self.opts.unstable_opts.verbose_internals
606 }
607
608 pub fn print_llvm_stats(&self) -> bool {
609 self.opts.unstable_opts.print_codegen_stats
610 }
611
612 pub fn verify_llvm_ir(&self) -> bool {
613 self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
614 }
615
616 pub fn binary_dep_depinfo(&self) -> bool {
617 self.opts.unstable_opts.binary_dep_depinfo
618 }
619
620 pub fn mir_opt_level(&self) -> usize {
621 self.opts
622 .unstable_opts
623 .mir_opt_level
624 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
625 }
626
627 pub fn lto(&self) -> config::Lto {
629 if self.target.requires_lto {
631 return config::Lto::Fat;
632 }
633
634 match self.opts.cg.lto {
638 config::LtoCli::Unspecified => {
639 }
642 config::LtoCli::No => {
643 return config::Lto::No;
645 }
646 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
647 return config::Lto::Fat;
649 }
650 config::LtoCli::Thin => {
651 return config::Lto::Thin;
653 }
654 }
655
656 if self.opts.cli_forced_local_thinlto_off {
665 return config::Lto::No;
666 }
667
668 if let Some(enabled) = self.opts.unstable_opts.thinlto {
671 if enabled {
672 return config::Lto::ThinLocal;
673 } else {
674 return config::Lto::No;
675 }
676 }
677
678 if self.codegen_units().as_usize() == 1 {
681 return config::Lto::No;
682 }
683
684 match self.opts.optimize {
687 config::OptLevel::No => config::Lto::No,
688 _ => config::Lto::ThinLocal,
689 }
690 }
691
692 pub fn panic_strategy(&self) -> PanicStrategy {
695 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
696 }
697
698 pub fn fewer_names(&self) -> bool {
699 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
700 fewer_names
701 } else {
702 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
703 || self.opts.output_types.contains_key(&OutputType::Bitcode)
704 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
706 !more_names
707 }
708 }
709
710 pub fn unstable_options(&self) -> bool {
711 self.opts.unstable_opts.unstable_options
712 }
713
714 pub fn is_nightly_build(&self) -> bool {
715 self.opts.unstable_features.is_nightly_build()
716 }
717
718 pub fn overflow_checks(&self) -> bool {
719 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
720 }
721
722 pub fn ub_checks(&self) -> bool {
723 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
724 }
725
726 pub fn contract_checks(&self) -> bool {
727 self.opts.unstable_opts.contract_checks.unwrap_or(false)
728 }
729
730 pub fn relocation_model(&self) -> RelocModel {
731 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
732 }
733
734 pub fn code_model(&self) -> Option<CodeModel> {
735 self.opts.cg.code_model.or(self.target.code_model)
736 }
737
738 pub fn tls_model(&self) -> TlsModel {
739 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
740 }
741
742 pub fn direct_access_external_data(&self) -> Option<bool> {
743 self.opts
744 .unstable_opts
745 .direct_access_external_data
746 .or(self.target.direct_access_external_data)
747 }
748
749 pub fn split_debuginfo(&self) -> SplitDebuginfo {
750 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
751 }
752
753 pub fn dwarf_version(&self) -> u32 {
755 self.opts
756 .cg
757 .dwarf_version
758 .or(self.opts.unstable_opts.dwarf_version)
759 .unwrap_or(self.target.default_dwarf_version)
760 }
761
762 pub fn stack_protector(&self) -> StackProtector {
763 if self.target.options.supports_stack_protector {
764 self.opts.unstable_opts.stack_protector
765 } else {
766 StackProtector::None
767 }
768 }
769
770 pub fn must_emit_unwind_tables(&self) -> bool {
771 self.target.requires_uwtable
799 || self.opts.cg.force_unwind_tables.unwrap_or(
800 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
801 )
802 }
803
804 #[inline]
807 pub fn threads(&self) -> usize {
808 self.opts.unstable_opts.threads
809 }
810
811 pub fn codegen_units(&self) -> CodegenUnits {
814 if let Some(n) = self.opts.cli_forced_codegen_units {
815 return CodegenUnits::User(n);
816 }
817 if let Some(n) = self.target.default_codegen_units {
818 return CodegenUnits::Default(n as usize);
819 }
820
821 if self.opts.incremental.is_some() {
825 return CodegenUnits::Default(256);
826 }
827
828 CodegenUnits::Default(16)
879 }
880
881 pub fn teach(&self, code: ErrCode) -> bool {
882 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
883 }
884
885 pub fn edition(&self) -> Edition {
886 self.opts.edition
887 }
888
889 pub fn link_dead_code(&self) -> bool {
890 self.opts.cg.link_dead_code.unwrap_or(false)
891 }
892
893 pub fn filename_display_preference(
894 &self,
895 scope: RemapPathScopeComponents,
896 ) -> FileNameDisplayPreference {
897 assert!(
898 scope.bits().count_ones() == 1,
899 "one and only one scope should be passed to `Session::filename_display_preference`"
900 );
901 if self.opts.unstable_opts.remap_path_scope.contains(scope) {
902 FileNameDisplayPreference::Remapped
903 } else {
904 FileNameDisplayPreference::Local
905 }
906 }
907
908 pub fn apple_deployment_target(&self) -> apple::OSVersion {
913 let min = apple::OSVersion::minimum_deployment_target(&self.target);
914 let env_var = apple::deployment_target_env_var(&self.target.os);
915
916 if let Ok(deployment_target) = env::var(env_var) {
918 match apple::OSVersion::from_str(&deployment_target) {
919 Ok(version) => {
920 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
921 if version < os_min {
926 self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {
927 env_var,
928 version: version.fmt_pretty().to_string(),
929 os_min: os_min.fmt_pretty().to_string(),
930 });
931 }
932
933 version.max(min)
935 }
936 Err(error) => {
937 self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });
938 min
939 }
940 }
941 } else {
942 min
944 }
945 }
946}
947
948#[allow(rustc::bad_opt_access)]
950fn default_emitter(
951 sopts: &config::Options,
952 source_map: Arc<SourceMap>,
953 translator: Translator,
954) -> Box<DynEmitter> {
955 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
956 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
957 let terminal_url = match sopts.unstable_opts.terminal_urls {
958 TerminalUrl::Auto => {
959 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
960 (Ok("truecolor"), Ok("xterm-256color"))
961 if sopts.unstable_features.is_nightly_build() =>
962 {
963 TerminalUrl::Yes
964 }
965 _ => TerminalUrl::No,
966 }
967 }
968 t => t,
969 };
970
971 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
972
973 match sopts.error_format {
974 config::ErrorOutputType::HumanReadable { kind, color_config } => {
975 let short = kind.short();
976
977 if let HumanReadableErrorType::AnnotateSnippet = kind {
978 let emitter =
979 AnnotateSnippetEmitter::new(source_map, translator, short, macro_backtrace);
980 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
981 } else {
982 let emitter = HumanEmitter::new(stderr_destination(color_config), translator)
983 .sm(source_map)
984 .short_message(short)
985 .diagnostic_width(sopts.diagnostic_width)
986 .macro_backtrace(macro_backtrace)
987 .track_diagnostics(track_diagnostics)
988 .terminal_url(terminal_url)
989 .theme(if let HumanReadableErrorType::Unicode = kind {
990 OutputTheme::Unicode
991 } else {
992 OutputTheme::Ascii
993 })
994 .ignored_directories_in_source_blocks(
995 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
996 );
997 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
998 }
999 }
1000 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
1001 JsonEmitter::new(
1002 Box::new(io::BufWriter::new(io::stderr())),
1003 source_map,
1004 translator,
1005 pretty,
1006 json_rendered,
1007 color_config,
1008 )
1009 .ui_testing(sopts.unstable_opts.ui_testing)
1010 .ignored_directories_in_source_blocks(
1011 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1012 )
1013 .diagnostic_width(sopts.diagnostic_width)
1014 .macro_backtrace(macro_backtrace)
1015 .track_diagnostics(track_diagnostics)
1016 .terminal_url(terminal_url),
1017 ),
1018 }
1019}
1020
1021#[allow(rustc::bad_opt_access)]
1023#[allow(rustc::untranslatable_diagnostic)] pub fn build_session(
1025 sopts: config::Options,
1026 io: CompilerIO,
1027 fluent_bundle: Option<Arc<rustc_errors::FluentBundle>>,
1028 registry: rustc_errors::registry::Registry,
1029 fluent_resources: Vec<&'static str>,
1030 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1031 target: Target,
1032 cfg_version: &'static str,
1033 ice_file: Option<PathBuf>,
1034 using_internal_features: &'static AtomicBool,
1035 expanded_args: Vec<String>,
1036) -> Session {
1037 let warnings_allow = sopts
1041 .lint_opts
1042 .iter()
1043 .rfind(|&(key, _)| *key == "warnings")
1044 .is_some_and(|&(_, level)| level == lint::Allow);
1045 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1046 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1047
1048 let translator = Translator {
1049 fluent_bundle,
1050 fallback_fluent_bundle: fallback_fluent_bundle(
1051 fluent_resources,
1052 sopts.unstable_opts.translate_directionality_markers,
1053 ),
1054 };
1055 let source_map = rustc_span::source_map::get_source_map().unwrap();
1056 let emitter = default_emitter(&sopts, Arc::clone(&source_map), translator);
1057
1058 let mut dcx = DiagCtxt::new(emitter)
1059 .with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings))
1060 .with_registry(registry);
1061 if let Some(ice_file) = ice_file {
1062 dcx = dcx.with_ice_file(ice_file);
1063 }
1064
1065 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1066 let (host, target_warnings) = Target::search(&host_triple, sopts.sysroot.path())
1067 .unwrap_or_else(|e| dcx.handle().fatal(format!("Error loading host specification: {e}")));
1068 for warning in target_warnings.warning_messages() {
1069 dcx.handle().warn(warning)
1070 }
1071
1072 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1073 {
1074 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1075
1076 let profiler = SelfProfiler::new(
1077 directory,
1078 sopts.crate_name.as_deref(),
1079 sopts.unstable_opts.self_profile_events.as_deref(),
1080 &sopts.unstable_opts.self_profile_counter,
1081 );
1082 match profiler {
1083 Ok(profiler) => Some(Arc::new(profiler)),
1084 Err(e) => {
1085 dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1086 None
1087 }
1088 }
1089 } else {
1090 None
1091 };
1092
1093 let mut psess = ParseSess::with_dcx(dcx, source_map);
1094 psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1095
1096 let host_triple = config::host_tuple();
1097 let target_triple = sopts.target_triple.tuple();
1098 let host_tlib_path =
1100 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1101 let target_tlib_path = if host_triple == target_triple {
1102 Arc::clone(&host_tlib_path)
1105 } else {
1106 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1107 };
1108
1109 let prof = SelfProfilerRef::new(
1110 self_profiler,
1111 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1112 );
1113
1114 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1115 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1116 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1117 _ => CtfeBacktrace::Disabled,
1118 });
1119
1120 let asm_arch = if target.allow_asm { InlineAsmArch::from_str(&target.arch).ok() } else { None };
1121 let target_filesearch =
1122 filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1123 let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1124
1125 let invocation_temp = sopts
1126 .incremental
1127 .as_ref()
1128 .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
1129
1130 let timings = TimingSectionHandler::new(sopts.json_timings);
1131
1132 let sess = Session {
1133 target,
1134 host,
1135 opts: sopts,
1136 target_tlib_path,
1137 psess,
1138 io,
1139 incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1140 prof,
1141 timings,
1142 code_stats: Default::default(),
1143 lint_store: None,
1144 driver_lint_caps,
1145 ctfe_backtrace,
1146 miri_unleashed_features: Lock::new(Default::default()),
1147 asm_arch,
1148 target_features: Default::default(),
1149 unstable_target_features: Default::default(),
1150 cfg_version,
1151 using_internal_features,
1152 expanded_args,
1153 target_filesearch,
1154 host_filesearch,
1155 invocation_temp,
1156 };
1157
1158 validate_commandline_args_with_session_available(&sess);
1159
1160 sess
1161}
1162
1163#[allow(rustc::bad_opt_access)]
1169fn validate_commandline_args_with_session_available(sess: &Session) {
1170 if sess.opts.cg.linker_plugin_lto.enabled()
1178 && sess.opts.cg.prefer_dynamic
1179 && sess.target.is_like_windows
1180 {
1181 sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1182 }
1183
1184 if let Some(ref path) = sess.opts.cg.profile_use {
1187 if !path.exists() {
1188 sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1189 }
1190 }
1191
1192 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1194 if !path.exists() {
1195 sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1196 }
1197 }
1198
1199 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1201 if sess.target.requires_uwtable && !include_uwtables {
1202 sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1203 }
1204 }
1205
1206 let supported_sanitizers = sess.target.options.supported_sanitizers;
1208 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1209 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == "aarch64" {
1212 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1213 }
1214 match unsupported_sanitizers.into_iter().count() {
1215 0 => {}
1216 1 => {
1217 sess.dcx()
1218 .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1219 }
1220 _ => {
1221 sess.dcx().emit_err(errors::SanitizersNotSupported {
1222 us: unsupported_sanitizers.to_string(),
1223 });
1224 }
1225 }
1226
1227 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1229 sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1230 first: first.to_string(),
1231 second: second.to_string(),
1232 });
1233 }
1234
1235 if sess.crt_static(None)
1237 && !sess.opts.unstable_opts.sanitizer.is_empty()
1238 && !sess.target.is_like_msvc
1239 {
1240 sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1241 }
1242
1243 if sess.is_sanitizer_cfi_enabled()
1245 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1246 {
1247 sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1248 }
1249
1250 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy() != PanicStrategy::Abort {
1252 sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1253 }
1254
1255 if sess.is_sanitizer_cfi_enabled()
1257 && sess.lto() == config::Lto::Fat
1258 && (sess.codegen_units().as_usize() != 1)
1259 {
1260 sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1261 }
1262
1263 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1265 if !sess.is_sanitizer_cfi_enabled() {
1266 sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1267 }
1268 }
1269
1270 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1272 sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);
1273 }
1274
1275 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1277 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1278 sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1279 }
1280 }
1281
1282 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1284 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1285 sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1286 }
1287 }
1288
1289 if sess.is_split_lto_unit_enabled()
1291 && !(sess.lto() == config::Lto::Fat
1292 || sess.lto() == config::Lto::Thin
1293 || sess.opts.cg.linker_plugin_lto.enabled())
1294 {
1295 sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1296 }
1297
1298 if sess.lto() != config::Lto::Fat {
1300 if sess.opts.unstable_opts.virtual_function_elimination {
1301 sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1302 }
1303 }
1304
1305 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1306 if !sess.target.options.supports_stack_protector {
1307 sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1308 stack_protector: sess.opts.unstable_opts.stack_protector,
1309 target_triple: &sess.opts.target_triple,
1310 });
1311 }
1312 }
1313
1314 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1315 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1316 sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1317 target_triple: &sess.opts.target_triple,
1318 })
1319 }
1320 }
1321
1322 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != "aarch64" {
1323 sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1324 }
1325
1326 if let Some(dwarf_version) =
1327 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1328 {
1329 if dwarf_version < 2 || dwarf_version > 5 {
1331 sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1332 }
1333 }
1334
1335 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1336 && !sess.opts.unstable_opts.unstable_options
1337 {
1338 sess.dcx()
1339 .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1340 }
1341
1342 if sess.opts.unstable_opts.embed_source {
1343 let dwarf_version = sess.dwarf_version();
1344
1345 if dwarf_version < 5 {
1346 sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1347 }
1348
1349 if sess.opts.debuginfo == DebugInfo::None {
1350 sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1351 }
1352 }
1353
1354 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1355 sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1356 }
1357
1358 if let Some(flavor) = sess.opts.cg.linker_flavor
1359 && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1360 {
1361 let flavor = flavor.desc();
1362 sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1363 }
1364
1365 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1366 if sess.target.arch != "x86" && sess.target.arch != "x86_64" {
1367 sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1368 }
1369 }
1370
1371 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1372 if regparm > 3 {
1373 sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1374 }
1375 if sess.target.arch != "x86" {
1376 sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1377 }
1378 }
1379 if sess.opts.unstable_opts.reg_struct_return {
1380 if sess.target.arch != "x86" {
1381 sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1382 }
1383 }
1384
1385 match sess.opts.unstable_opts.function_return {
1389 FunctionReturn::Keep => (),
1390 FunctionReturn::ThunkExtern => {
1391 if let Some(code_model) = sess.code_model()
1394 && code_model == CodeModel::Large
1395 {
1396 sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1397 }
1398 }
1399 }
1400
1401 if sess.opts.cg.soft_float {
1402 if sess.target.arch == "arm" {
1403 sess.dcx().emit_warn(errors::SoftFloatDeprecated);
1404 } else {
1405 sess.dcx().emit_warn(errors::SoftFloatIgnored);
1408 }
1409 }
1410}
1411
1412#[derive(Debug)]
1414enum IncrCompSession {
1415 NotInitialized,
1418 Active { session_directory: PathBuf, _lock_file: flock::Lock },
1423 Finalized { session_directory: PathBuf },
1426 InvalidBecauseOfErrors { session_directory: PathBuf },
1430}
1431
1432pub struct EarlyDiagCtxt {
1434 dcx: DiagCtxt,
1435}
1436
1437impl EarlyDiagCtxt {
1438 pub fn new(output: ErrorOutputType) -> Self {
1439 let emitter = mk_emitter(output);
1440 Self { dcx: DiagCtxt::new(emitter) }
1441 }
1442
1443 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1446 assert!(self.dcx.handle().has_errors().is_none());
1447
1448 let emitter = mk_emitter(output);
1449 self.dcx = DiagCtxt::new(emitter);
1450 }
1451
1452 #[allow(rustc::untranslatable_diagnostic)]
1453 #[allow(rustc::diagnostic_outside_of_impl)]
1454 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1455 self.dcx.handle().note(msg)
1456 }
1457
1458 #[allow(rustc::untranslatable_diagnostic)]
1459 #[allow(rustc::diagnostic_outside_of_impl)]
1460 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1461 self.dcx.handle().struct_help(msg).emit()
1462 }
1463
1464 #[allow(rustc::untranslatable_diagnostic)]
1465 #[allow(rustc::diagnostic_outside_of_impl)]
1466 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1467 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1468 self.dcx.handle().err(msg)
1469 }
1470
1471 #[allow(rustc::untranslatable_diagnostic)]
1472 #[allow(rustc::diagnostic_outside_of_impl)]
1473 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1474 self.dcx.handle().fatal(msg)
1475 }
1476
1477 #[allow(rustc::untranslatable_diagnostic)]
1478 #[allow(rustc::diagnostic_outside_of_impl)]
1479 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1480 self.dcx.handle().struct_fatal(msg)
1481 }
1482
1483 #[allow(rustc::untranslatable_diagnostic)]
1484 #[allow(rustc::diagnostic_outside_of_impl)]
1485 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1486 self.dcx.handle().warn(msg)
1487 }
1488
1489 #[allow(rustc::untranslatable_diagnostic)]
1490 #[allow(rustc::diagnostic_outside_of_impl)]
1491 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1492 self.dcx.handle().struct_warn(msg)
1493 }
1494}
1495
1496fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1497 let translator =
1500 Translator::with_fallback_bundle(vec![rustc_errors::DEFAULT_LOCALE_RESOURCE], false);
1501 let emitter: Box<DynEmitter> = match output {
1502 config::ErrorOutputType::HumanReadable { kind, color_config } => {
1503 let short = kind.short();
1504 Box::new(
1505 HumanEmitter::new(stderr_destination(color_config), translator)
1506 .theme(if let HumanReadableErrorType::Unicode = kind {
1507 OutputTheme::Unicode
1508 } else {
1509 OutputTheme::Ascii
1510 })
1511 .short_message(short),
1512 )
1513 }
1514 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1515 Box::new(JsonEmitter::new(
1516 Box::new(io::BufWriter::new(io::stderr())),
1517 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1518 translator,
1519 pretty,
1520 json_rendered,
1521 color_config,
1522 ))
1523 }
1524 };
1525 emitter
1526}
1527
1528pub trait RemapFileNameExt {
1529 type Output<'a>
1530 where
1531 Self: 'a;
1532
1533 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_>;
1537}
1538
1539impl RemapFileNameExt for rustc_span::FileName {
1540 type Output<'a> = rustc_span::FileNameDisplay<'a>;
1541
1542 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1543 assert!(
1544 scope.bits().count_ones() == 1,
1545 "one and only one scope should be passed to for_scope"
1546 );
1547 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1548 self.prefer_remapped_unconditionally()
1549 } else {
1550 self.prefer_local()
1551 }
1552 }
1553}
1554
1555impl RemapFileNameExt for rustc_span::RealFileName {
1556 type Output<'a> = &'a Path;
1557
1558 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1559 assert!(
1560 scope.bits().count_ones() == 1,
1561 "one and only one scope should be passed to for_scope"
1562 );
1563 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1564 self.remapped_path_if_available()
1565 } else {
1566 self.local_path_if_available()
1567 }
1568 }
1569}