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, CrateType, DebugInfo, ErrorOutputType, FunctionReturn, Input,
43 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.opts.output_types.contains_key(&OutputType::Mir)
317 || std::env::var_os("RUSTC_LOG").is_some()
318 {
319 return;
320 }
321
322 self.dcx().set_must_produce_diag()
323 }
324
325 #[inline]
326 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
327 self.psess.dcx()
328 }
329
330 #[inline]
331 pub fn source_map(&self) -> &SourceMap {
332 self.psess.source_map()
333 }
334
335 pub fn enable_internal_lints(&self) -> bool {
339 self.unstable_options() && !self.opts.actually_rustdoc
340 }
341
342 pub fn instrument_coverage(&self) -> bool {
343 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
344 }
345
346 pub fn instrument_coverage_branch(&self) -> bool {
347 self.instrument_coverage()
348 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
349 }
350
351 pub fn instrument_coverage_condition(&self) -> bool {
352 self.instrument_coverage()
353 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
354 }
355
356 pub fn instrument_coverage_mcdc(&self) -> bool {
357 self.instrument_coverage()
358 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Mcdc
359 }
360
361 pub fn coverage_no_mir_spans(&self) -> bool {
363 self.opts.unstable_opts.coverage_options.no_mir_spans
364 }
365
366 pub fn coverage_discard_all_spans_in_codegen(&self) -> bool {
368 self.opts.unstable_opts.coverage_options.discard_all_spans_in_codegen
369 }
370
371 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
372 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::CFI)
373 }
374
375 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
376 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
377 }
378
379 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
380 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
381 }
382
383 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
384 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
385 }
386
387 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
388 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
389 }
390
391 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
392 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
393 }
394
395 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
396 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::KCFI)
397 }
398
399 pub fn is_split_lto_unit_enabled(&self) -> bool {
400 self.opts.unstable_opts.split_lto_unit == Some(true)
401 }
402
403 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
405 if !self.target.crt_static_respected {
406 return self.target.crt_static_default;
408 }
409
410 let requested_features = self.opts.cg.target_feature.split(',');
411 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
412 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
413
414 #[allow(rustc::bad_opt_access)]
416 if found_positive || found_negative {
417 found_positive
418 } else if crate_type == Some(CrateType::ProcMacro)
419 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
420 {
421 false
425 } else {
426 self.target.crt_static_default
427 }
428 }
429
430 pub fn is_wasi_reactor(&self) -> bool {
431 self.target.options.os == "wasi"
432 && matches!(
433 self.opts.unstable_opts.wasi_exec_model,
434 Some(config::WasiExecModel::Reactor)
435 )
436 }
437
438 pub fn target_can_use_split_dwarf(&self) -> bool {
440 self.target.debuginfo_kind == DebuginfoKind::Dwarf
441 }
442
443 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
444 format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.as_u64())
445 }
446
447 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
448 &self.target_filesearch
449 }
450 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
451 &self.host_filesearch
452 }
453
454 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
458 let search_paths = self
459 .opts
460 .sysroot
461 .all_paths()
462 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
463
464 if self_contained {
465 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
469 } else {
470 search_paths.collect()
471 }
472 }
473
474 pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
475 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
476
477 if let IncrCompSession::NotInitialized = *incr_comp_session {
478 } else {
479 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
480 }
481
482 *incr_comp_session =
483 IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
484 }
485
486 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
487 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
488
489 if let IncrCompSession::Active { .. } = *incr_comp_session {
490 } else {
491 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
492 }
493
494 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
496 }
497
498 pub fn mark_incr_comp_session_as_invalid(&self) {
499 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
500
501 let session_directory = match *incr_comp_session {
502 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
503 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
504 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
505 };
506
507 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
509 }
510
511 pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
512 let incr_comp_session = self.incr_comp_session.borrow();
513 ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
514 IncrCompSession::NotInitialized => panic!(
515 "trying to get session directory from `IncrCompSession`: {:?}",
516 *incr_comp_session,
517 ),
518 IncrCompSession::Active { ref session_directory, .. }
519 | IncrCompSession::Finalized { ref session_directory }
520 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
521 session_directory
522 }
523 })
524 }
525
526 pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
527 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
528 }
529
530 pub fn is_rust_2015(&self) -> bool {
532 self.edition().is_rust_2015()
533 }
534
535 pub fn at_least_rust_2018(&self) -> bool {
537 self.edition().at_least_rust_2018()
538 }
539
540 pub fn at_least_rust_2021(&self) -> bool {
542 self.edition().at_least_rust_2021()
543 }
544
545 pub fn at_least_rust_2024(&self) -> bool {
547 self.edition().at_least_rust_2024()
548 }
549
550 pub fn needs_plt(&self) -> bool {
552 let want_plt = self.target.plt_by_default;
555
556 let dbg_opts = &self.opts.unstable_opts;
557
558 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
559
560 let full_relro = RelroLevel::Full == relro_level;
564
565 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
568 }
569
570 pub fn emit_lifetime_markers(&self) -> bool {
572 self.opts.optimize != config::OptLevel::No
573 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
577 }
578
579 pub fn diagnostic_width(&self) -> usize {
580 let default_column_width = 140;
581 if let Some(width) = self.opts.diagnostic_width {
582 width
583 } else if self.opts.unstable_opts.ui_testing {
584 default_column_width
585 } else {
586 termize::dimensions().map_or(default_column_width, |(w, _)| w)
587 }
588 }
589
590 pub fn default_visibility(&self) -> SymbolVisibility {
592 self.opts
593 .unstable_opts
594 .default_visibility
595 .or(self.target.options.default_visibility)
596 .unwrap_or(SymbolVisibility::Interposable)
597 }
598
599 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
600 if verbatim {
601 ("", "")
602 } else {
603 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
604 }
605 }
606}
607
608#[allow(rustc::bad_opt_access)]
610impl Session {
611 pub fn verbose_internals(&self) -> bool {
612 self.opts.unstable_opts.verbose_internals
613 }
614
615 pub fn print_llvm_stats(&self) -> bool {
616 self.opts.unstable_opts.print_codegen_stats
617 }
618
619 pub fn verify_llvm_ir(&self) -> bool {
620 self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
621 }
622
623 pub fn binary_dep_depinfo(&self) -> bool {
624 self.opts.unstable_opts.binary_dep_depinfo
625 }
626
627 pub fn mir_opt_level(&self) -> usize {
628 self.opts
629 .unstable_opts
630 .mir_opt_level
631 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
632 }
633
634 pub fn lto(&self) -> config::Lto {
636 if self.target.requires_lto {
638 return config::Lto::Fat;
639 }
640
641 match self.opts.cg.lto {
645 config::LtoCli::Unspecified => {
646 }
649 config::LtoCli::No => {
650 return config::Lto::No;
652 }
653 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
654 return config::Lto::Fat;
656 }
657 config::LtoCli::Thin => {
658 return config::Lto::Thin;
660 }
661 }
662
663 if self.opts.cli_forced_local_thinlto_off {
672 return config::Lto::No;
673 }
674
675 if let Some(enabled) = self.opts.unstable_opts.thinlto {
678 if enabled {
679 return config::Lto::ThinLocal;
680 } else {
681 return config::Lto::No;
682 }
683 }
684
685 if self.codegen_units().as_usize() == 1 {
688 return config::Lto::No;
689 }
690
691 match self.opts.optimize {
694 config::OptLevel::No => config::Lto::No,
695 _ => config::Lto::ThinLocal,
696 }
697 }
698
699 pub fn panic_strategy(&self) -> PanicStrategy {
702 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
703 }
704
705 pub fn fewer_names(&self) -> bool {
706 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
707 fewer_names
708 } else {
709 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
710 || self.opts.output_types.contains_key(&OutputType::Bitcode)
711 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
713 !more_names
714 }
715 }
716
717 pub fn unstable_options(&self) -> bool {
718 self.opts.unstable_opts.unstable_options
719 }
720
721 pub fn is_nightly_build(&self) -> bool {
722 self.opts.unstable_features.is_nightly_build()
723 }
724
725 pub fn overflow_checks(&self) -> bool {
726 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
727 }
728
729 pub fn ub_checks(&self) -> bool {
730 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
731 }
732
733 pub fn contract_checks(&self) -> bool {
734 self.opts.unstable_opts.contract_checks.unwrap_or(false)
735 }
736
737 pub fn relocation_model(&self) -> RelocModel {
738 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
739 }
740
741 pub fn code_model(&self) -> Option<CodeModel> {
742 self.opts.cg.code_model.or(self.target.code_model)
743 }
744
745 pub fn tls_model(&self) -> TlsModel {
746 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
747 }
748
749 pub fn direct_access_external_data(&self) -> Option<bool> {
750 self.opts
751 .unstable_opts
752 .direct_access_external_data
753 .or(self.target.direct_access_external_data)
754 }
755
756 pub fn split_debuginfo(&self) -> SplitDebuginfo {
757 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
758 }
759
760 pub fn dwarf_version(&self) -> u32 {
762 self.opts
763 .cg
764 .dwarf_version
765 .or(self.opts.unstable_opts.dwarf_version)
766 .unwrap_or(self.target.default_dwarf_version)
767 }
768
769 pub fn stack_protector(&self) -> StackProtector {
770 if self.target.options.supports_stack_protector {
771 self.opts.unstable_opts.stack_protector
772 } else {
773 StackProtector::None
774 }
775 }
776
777 pub fn must_emit_unwind_tables(&self) -> bool {
778 self.target.requires_uwtable
806 || self.opts.cg.force_unwind_tables.unwrap_or(
807 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
808 )
809 }
810
811 #[inline]
814 pub fn threads(&self) -> usize {
815 self.opts.unstable_opts.threads
816 }
817
818 pub fn codegen_units(&self) -> CodegenUnits {
821 if let Some(n) = self.opts.cli_forced_codegen_units {
822 return CodegenUnits::User(n);
823 }
824 if let Some(n) = self.target.default_codegen_units {
825 return CodegenUnits::Default(n as usize);
826 }
827
828 if self.opts.incremental.is_some() {
832 return CodegenUnits::Default(256);
833 }
834
835 CodegenUnits::Default(16)
886 }
887
888 pub fn teach(&self, code: ErrCode) -> bool {
889 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
890 }
891
892 pub fn edition(&self) -> Edition {
893 self.opts.edition
894 }
895
896 pub fn link_dead_code(&self) -> bool {
897 self.opts.cg.link_dead_code.unwrap_or(false)
898 }
899
900 pub fn filename_display_preference(
901 &self,
902 scope: RemapPathScopeComponents,
903 ) -> FileNameDisplayPreference {
904 assert!(
905 scope.bits().count_ones() == 1,
906 "one and only one scope should be passed to `Session::filename_display_preference`"
907 );
908 if self.opts.unstable_opts.remap_path_scope.contains(scope) {
909 FileNameDisplayPreference::Remapped
910 } else {
911 FileNameDisplayPreference::Local
912 }
913 }
914
915 pub fn apple_deployment_target(&self) -> apple::OSVersion {
920 let min = apple::OSVersion::minimum_deployment_target(&self.target);
921 let env_var = apple::deployment_target_env_var(&self.target.os);
922
923 if let Ok(deployment_target) = env::var(env_var) {
925 match apple::OSVersion::from_str(&deployment_target) {
926 Ok(version) => {
927 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
928 if version < os_min {
933 self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {
934 env_var,
935 version: version.fmt_pretty().to_string(),
936 os_min: os_min.fmt_pretty().to_string(),
937 });
938 }
939
940 version.max(min)
942 }
943 Err(error) => {
944 self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });
945 min
946 }
947 }
948 } else {
949 min
951 }
952 }
953}
954
955#[allow(rustc::bad_opt_access)]
957fn default_emitter(
958 sopts: &config::Options,
959 source_map: Arc<SourceMap>,
960 translator: Translator,
961) -> Box<DynEmitter> {
962 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
963 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
964 let terminal_url = match sopts.unstable_opts.terminal_urls {
965 TerminalUrl::Auto => {
966 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
967 (Ok("truecolor"), Ok("xterm-256color"))
968 if sopts.unstable_features.is_nightly_build() =>
969 {
970 TerminalUrl::Yes
971 }
972 _ => TerminalUrl::No,
973 }
974 }
975 t => t,
976 };
977
978 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
979
980 match sopts.error_format {
981 config::ErrorOutputType::HumanReadable { kind, color_config } => {
982 let short = kind.short();
983
984 if let HumanReadableErrorType::AnnotateSnippet = kind {
985 let emitter =
986 AnnotateSnippetEmitter::new(source_map, translator, short, macro_backtrace);
987 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
988 } else {
989 let emitter = HumanEmitter::new(stderr_destination(color_config), translator)
990 .sm(source_map)
991 .short_message(short)
992 .diagnostic_width(sopts.diagnostic_width)
993 .macro_backtrace(macro_backtrace)
994 .track_diagnostics(track_diagnostics)
995 .terminal_url(terminal_url)
996 .theme(if let HumanReadableErrorType::Unicode = kind {
997 OutputTheme::Unicode
998 } else {
999 OutputTheme::Ascii
1000 })
1001 .ignored_directories_in_source_blocks(
1002 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1003 );
1004 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
1005 }
1006 }
1007 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
1008 JsonEmitter::new(
1009 Box::new(io::BufWriter::new(io::stderr())),
1010 source_map,
1011 translator,
1012 pretty,
1013 json_rendered,
1014 color_config,
1015 )
1016 .ui_testing(sopts.unstable_opts.ui_testing)
1017 .ignored_directories_in_source_blocks(
1018 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1019 )
1020 .diagnostic_width(sopts.diagnostic_width)
1021 .macro_backtrace(macro_backtrace)
1022 .track_diagnostics(track_diagnostics)
1023 .terminal_url(terminal_url),
1024 ),
1025 }
1026}
1027
1028#[allow(rustc::bad_opt_access)]
1030#[allow(rustc::untranslatable_diagnostic)] pub fn build_session(
1032 sopts: config::Options,
1033 io: CompilerIO,
1034 fluent_bundle: Option<Arc<rustc_errors::FluentBundle>>,
1035 registry: rustc_errors::registry::Registry,
1036 fluent_resources: Vec<&'static str>,
1037 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1038 target: Target,
1039 cfg_version: &'static str,
1040 ice_file: Option<PathBuf>,
1041 using_internal_features: &'static AtomicBool,
1042 expanded_args: Vec<String>,
1043) -> Session {
1044 let warnings_allow = sopts
1048 .lint_opts
1049 .iter()
1050 .rfind(|&(key, _)| *key == "warnings")
1051 .is_some_and(|&(_, level)| level == lint::Allow);
1052 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1053 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1054
1055 let translator = Translator {
1056 fluent_bundle,
1057 fallback_fluent_bundle: fallback_fluent_bundle(
1058 fluent_resources,
1059 sopts.unstable_opts.translate_directionality_markers,
1060 ),
1061 };
1062 let source_map = rustc_span::source_map::get_source_map().unwrap();
1063 let emitter = default_emitter(&sopts, Arc::clone(&source_map), translator);
1064
1065 let mut dcx = DiagCtxt::new(emitter)
1066 .with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings))
1067 .with_registry(registry);
1068 if let Some(ice_file) = ice_file {
1069 dcx = dcx.with_ice_file(ice_file);
1070 }
1071
1072 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1073 let (host, target_warnings) = Target::search(&host_triple, sopts.sysroot.path())
1074 .unwrap_or_else(|e| dcx.handle().fatal(format!("Error loading host specification: {e}")));
1075 for warning in target_warnings.warning_messages() {
1076 dcx.handle().warn(warning)
1077 }
1078
1079 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1080 {
1081 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1082
1083 let profiler = SelfProfiler::new(
1084 directory,
1085 sopts.crate_name.as_deref(),
1086 sopts.unstable_opts.self_profile_events.as_deref(),
1087 &sopts.unstable_opts.self_profile_counter,
1088 );
1089 match profiler {
1090 Ok(profiler) => Some(Arc::new(profiler)),
1091 Err(e) => {
1092 dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1093 None
1094 }
1095 }
1096 } else {
1097 None
1098 };
1099
1100 let mut psess = ParseSess::with_dcx(dcx, source_map);
1101 psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1102
1103 let host_triple = config::host_tuple();
1104 let target_triple = sopts.target_triple.tuple();
1105 let host_tlib_path =
1107 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1108 let target_tlib_path = if host_triple == target_triple {
1109 Arc::clone(&host_tlib_path)
1112 } else {
1113 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1114 };
1115
1116 let prof = SelfProfilerRef::new(
1117 self_profiler,
1118 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1119 );
1120
1121 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1122 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1123 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1124 _ => CtfeBacktrace::Disabled,
1125 });
1126
1127 let asm_arch = if target.allow_asm { InlineAsmArch::from_str(&target.arch).ok() } else { None };
1128 let target_filesearch =
1129 filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1130 let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1131
1132 let invocation_temp = sopts
1133 .incremental
1134 .as_ref()
1135 .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
1136
1137 let timings = TimingSectionHandler::new(sopts.json_timings);
1138
1139 let sess = Session {
1140 target,
1141 host,
1142 opts: sopts,
1143 target_tlib_path,
1144 psess,
1145 io,
1146 incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1147 prof,
1148 timings,
1149 code_stats: Default::default(),
1150 lint_store: None,
1151 driver_lint_caps,
1152 ctfe_backtrace,
1153 miri_unleashed_features: Lock::new(Default::default()),
1154 asm_arch,
1155 target_features: Default::default(),
1156 unstable_target_features: Default::default(),
1157 cfg_version,
1158 using_internal_features,
1159 expanded_args,
1160 target_filesearch,
1161 host_filesearch,
1162 invocation_temp,
1163 };
1164
1165 validate_commandline_args_with_session_available(&sess);
1166
1167 sess
1168}
1169
1170#[allow(rustc::bad_opt_access)]
1176fn validate_commandline_args_with_session_available(sess: &Session) {
1177 if sess.opts.cg.linker_plugin_lto.enabled()
1185 && sess.opts.cg.prefer_dynamic
1186 && sess.target.is_like_windows
1187 {
1188 sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1189 }
1190
1191 if let Some(ref path) = sess.opts.cg.profile_use {
1194 if !path.exists() {
1195 sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1196 }
1197 }
1198
1199 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1201 if !path.exists() {
1202 sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1203 }
1204 }
1205
1206 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1208 if sess.target.requires_uwtable && !include_uwtables {
1209 sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1210 }
1211 }
1212
1213 let supported_sanitizers = sess.target.options.supported_sanitizers;
1215 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1216 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == "aarch64" {
1219 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1220 }
1221 match unsupported_sanitizers.into_iter().count() {
1222 0 => {}
1223 1 => {
1224 sess.dcx()
1225 .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1226 }
1227 _ => {
1228 sess.dcx().emit_err(errors::SanitizersNotSupported {
1229 us: unsupported_sanitizers.to_string(),
1230 });
1231 }
1232 }
1233
1234 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1236 sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1237 first: first.to_string(),
1238 second: second.to_string(),
1239 });
1240 }
1241
1242 if sess.crt_static(None)
1244 && !sess.opts.unstable_opts.sanitizer.is_empty()
1245 && !sess.target.is_like_msvc
1246 {
1247 sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1248 }
1249
1250 if sess.is_sanitizer_cfi_enabled()
1252 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1253 {
1254 sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1255 }
1256
1257 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy() != PanicStrategy::Abort {
1259 sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1260 }
1261
1262 if sess.is_sanitizer_cfi_enabled()
1264 && sess.lto() == config::Lto::Fat
1265 && (sess.codegen_units().as_usize() != 1)
1266 {
1267 sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1268 }
1269
1270 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1272 if !sess.is_sanitizer_cfi_enabled() {
1273 sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1274 }
1275 }
1276
1277 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1279 sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);
1280 }
1281
1282 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1284 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1285 sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1286 }
1287 }
1288
1289 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1291 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1292 sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1293 }
1294 }
1295
1296 if sess.is_split_lto_unit_enabled()
1298 && !(sess.lto() == config::Lto::Fat
1299 || sess.lto() == config::Lto::Thin
1300 || sess.opts.cg.linker_plugin_lto.enabled())
1301 {
1302 sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1303 }
1304
1305 if sess.lto() != config::Lto::Fat {
1307 if sess.opts.unstable_opts.virtual_function_elimination {
1308 sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1309 }
1310 }
1311
1312 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1313 if !sess.target.options.supports_stack_protector {
1314 sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1315 stack_protector: sess.opts.unstable_opts.stack_protector,
1316 target_triple: &sess.opts.target_triple,
1317 });
1318 }
1319 }
1320
1321 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1322 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1323 sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1324 target_triple: &sess.opts.target_triple,
1325 })
1326 }
1327 }
1328
1329 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != "aarch64" {
1330 sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1331 }
1332
1333 if let Some(dwarf_version) =
1334 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1335 {
1336 if dwarf_version < 2 || dwarf_version > 5 {
1338 sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1339 }
1340 }
1341
1342 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1343 && !sess.opts.unstable_opts.unstable_options
1344 {
1345 sess.dcx()
1346 .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1347 }
1348
1349 if sess.opts.unstable_opts.embed_source {
1350 let dwarf_version = sess.dwarf_version();
1351
1352 if dwarf_version < 5 {
1353 sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1354 }
1355
1356 if sess.opts.debuginfo == DebugInfo::None {
1357 sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1358 }
1359 }
1360
1361 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1362 sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1363 }
1364
1365 if let Some(flavor) = sess.opts.cg.linker_flavor {
1366 if let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor) {
1367 let flavor = flavor.desc();
1368 sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1369 }
1370 }
1371
1372 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1373 if sess.target.arch != "x86" && sess.target.arch != "x86_64" {
1374 sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1375 }
1376 }
1377
1378 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1379 if regparm > 3 {
1380 sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1381 }
1382 if sess.target.arch != "x86" {
1383 sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1384 }
1385 }
1386 if sess.opts.unstable_opts.reg_struct_return {
1387 if sess.target.arch != "x86" {
1388 sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1389 }
1390 }
1391
1392 match sess.opts.unstable_opts.function_return {
1396 FunctionReturn::Keep => (),
1397 FunctionReturn::ThunkExtern => {
1398 if let Some(code_model) = sess.code_model()
1401 && code_model == CodeModel::Large
1402 {
1403 sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1404 }
1405 }
1406 }
1407
1408 if sess.opts.cg.soft_float {
1409 if sess.target.arch == "arm" {
1410 sess.dcx().emit_warn(errors::SoftFloatDeprecated);
1411 } else {
1412 sess.dcx().emit_warn(errors::SoftFloatIgnored);
1415 }
1416 }
1417}
1418
1419#[derive(Debug)]
1421enum IncrCompSession {
1422 NotInitialized,
1425 Active { session_directory: PathBuf, _lock_file: flock::Lock },
1430 Finalized { session_directory: PathBuf },
1433 InvalidBecauseOfErrors { session_directory: PathBuf },
1437}
1438
1439pub struct EarlyDiagCtxt {
1441 dcx: DiagCtxt,
1442}
1443
1444impl EarlyDiagCtxt {
1445 pub fn new(output: ErrorOutputType) -> Self {
1446 let emitter = mk_emitter(output);
1447 Self { dcx: DiagCtxt::new(emitter) }
1448 }
1449
1450 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1453 assert!(self.dcx.handle().has_errors().is_none());
1454
1455 let emitter = mk_emitter(output);
1456 self.dcx = DiagCtxt::new(emitter);
1457 }
1458
1459 #[allow(rustc::untranslatable_diagnostic)]
1460 #[allow(rustc::diagnostic_outside_of_impl)]
1461 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1462 self.dcx.handle().note(msg)
1463 }
1464
1465 #[allow(rustc::untranslatable_diagnostic)]
1466 #[allow(rustc::diagnostic_outside_of_impl)]
1467 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1468 self.dcx.handle().struct_help(msg).emit()
1469 }
1470
1471 #[allow(rustc::untranslatable_diagnostic)]
1472 #[allow(rustc::diagnostic_outside_of_impl)]
1473 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1474 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1475 self.dcx.handle().err(msg)
1476 }
1477
1478 #[allow(rustc::untranslatable_diagnostic)]
1479 #[allow(rustc::diagnostic_outside_of_impl)]
1480 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1481 self.dcx.handle().fatal(msg)
1482 }
1483
1484 #[allow(rustc::untranslatable_diagnostic)]
1485 #[allow(rustc::diagnostic_outside_of_impl)]
1486 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1487 self.dcx.handle().struct_fatal(msg)
1488 }
1489
1490 #[allow(rustc::untranslatable_diagnostic)]
1491 #[allow(rustc::diagnostic_outside_of_impl)]
1492 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1493 self.dcx.handle().warn(msg)
1494 }
1495
1496 #[allow(rustc::untranslatable_diagnostic)]
1497 #[allow(rustc::diagnostic_outside_of_impl)]
1498 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1499 self.dcx.handle().struct_warn(msg)
1500 }
1501}
1502
1503fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1504 let translator =
1507 Translator::with_fallback_bundle(vec![rustc_errors::DEFAULT_LOCALE_RESOURCE], false);
1508 let emitter: Box<DynEmitter> = match output {
1509 config::ErrorOutputType::HumanReadable { kind, color_config } => {
1510 let short = kind.short();
1511 Box::new(
1512 HumanEmitter::new(stderr_destination(color_config), translator)
1513 .theme(if let HumanReadableErrorType::Unicode = kind {
1514 OutputTheme::Unicode
1515 } else {
1516 OutputTheme::Ascii
1517 })
1518 .short_message(short),
1519 )
1520 }
1521 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1522 Box::new(JsonEmitter::new(
1523 Box::new(io::BufWriter::new(io::stderr())),
1524 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1525 translator,
1526 pretty,
1527 json_rendered,
1528 color_config,
1529 ))
1530 }
1531 };
1532 emitter
1533}
1534
1535pub trait RemapFileNameExt {
1536 type Output<'a>
1537 where
1538 Self: 'a;
1539
1540 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_>;
1544}
1545
1546impl RemapFileNameExt for rustc_span::FileName {
1547 type Output<'a> = rustc_span::FileNameDisplay<'a>;
1548
1549 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1550 assert!(
1551 scope.bits().count_ones() == 1,
1552 "one and only one scope should be passed to for_scope"
1553 );
1554 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1555 self.prefer_remapped_unconditionally()
1556 } else {
1557 self.prefer_local()
1558 }
1559 }
1560}
1561
1562impl RemapFileNameExt for rustc_span::RealFileName {
1563 type Output<'a> = &'a Path;
1564
1565 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1566 assert!(
1567 scope.bits().count_ones() == 1,
1568 "one and only one scope should be passed to for_scope"
1569 );
1570 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1571 self.remapped_path_if_available()
1572 } else {
1573 self.local_path_if_available()
1574 }
1575 }
1576}