1use std::any::Any;
2use std::path::{Path, PathBuf};
3use std::str::FromStr;
4use std::sync::Arc;
5use std::sync::atomic::AtomicBool;
6use std::{env, io};
7
8use rand::{RngCore, rng};
9use rustc_ast::NodeId;
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 LintEmitter, TerminalUrl, fallback_fluent_bundle,
26};
27use rustc_hir::limit::Limit;
28use rustc_macros::HashStable_Generic;
29pub use rustc_span::def_id::StableCrateId;
30use rustc_span::edition::Edition;
31use rustc_span::source_map::{FilePathMapping, SourceMap};
32use rustc_span::{FileNameDisplayPreference, RealFileName, Span, Symbol};
33use rustc_target::asm::InlineAsmArch;
34use rustc_target::spec::{
35 CodeModel, DebuginfoKind, PanicStrategy, RelocModel, RelroLevel, SanitizerSet,
36 SmallDataThresholdSupport, SplitDebuginfo, StackProtector, SymbolVisibility, Target,
37 TargetTuple, TlsModel, apple,
38};
39
40use crate::code_stats::CodeStats;
41pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
42use crate::config::{
43 self, CoverageLevel, CoverageOptions, CrateType, DebugInfo, ErrorOutputType, FunctionReturn,
44 Input, InstrumentCoverage, OptLevel, OutFileName, OutputType, RemapPathScopeComponents,
45 SwitchWithOptPath,
46};
47use crate::filesearch::FileSearch;
48use crate::lint::LintId;
49use crate::parse::{ParseSess, add_feature_diagnostics};
50use crate::search_paths::SearchPath;
51use crate::{errors, filesearch, lint};
52
53#[derive(Clone, Copy)]
55pub enum CtfeBacktrace {
56 Disabled,
58 Capture,
61 Immediate,
63}
64
65#[derive(Clone, Copy, Debug, HashStable_Generic)]
66pub struct Limits {
67 pub recursion_limit: Limit,
70 pub move_size_limit: Limit,
73 pub type_length_limit: Limit,
75 pub pattern_complexity_limit: Limit,
77}
78
79pub struct CompilerIO {
80 pub input: Input,
81 pub output_dir: Option<PathBuf>,
82 pub output_file: Option<OutFileName>,
83 pub temps_dir: Option<PathBuf>,
84}
85
86pub trait DynLintStore: Any + DynSync + DynSend {
87 fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;
89}
90
91pub struct Session {
94 pub target: Target,
95 pub host: Target,
96 pub opts: config::Options,
97 pub target_tlib_path: Arc<SearchPath>,
98 pub psess: ParseSess,
99 pub io: CompilerIO,
101
102 incr_comp_session: RwLock<IncrCompSession>,
103
104 pub prof: SelfProfilerRef,
106
107 pub timings: TimingSectionHandler,
109
110 pub code_stats: CodeStats,
112
113 pub lint_store: Option<Arc<dyn DynLintStore>>,
115
116 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
118
119 pub ctfe_backtrace: Lock<CtfeBacktrace>,
126
127 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
132
133 pub asm_arch: Option<InlineAsmArch>,
135
136 pub target_features: FxIndexSet<Symbol>,
138
139 pub unstable_target_features: FxIndexSet<Symbol>,
141
142 pub cfg_version: &'static str,
144
145 pub using_internal_features: &'static AtomicBool,
150
151 pub expanded_args: Vec<String>,
156
157 target_filesearch: FileSearch,
158 host_filesearch: FileSearch,
159
160 pub invocation_temp: Option<String>,
167}
168
169impl LintEmitter for &'_ Session {
170 type Id = NodeId;
171
172 fn emit_node_span_lint(
173 self,
174 lint: &'static rustc_lint_defs::Lint,
175 node_id: Self::Id,
176 span: impl Into<rustc_errors::MultiSpan>,
177 decorator: impl for<'a> rustc_errors::LintDiagnostic<'a, ()> + DynSend + 'static,
178 ) {
179 self.psess.buffer_lint(lint, span, node_id, decorator);
180 }
181}
182
183#[derive(Clone, Copy)]
184pub enum CodegenUnits {
185 User(usize),
188
189 Default(usize),
193}
194
195impl CodegenUnits {
196 pub fn as_usize(self) -> usize {
197 match self {
198 CodegenUnits::User(n) => n,
199 CodegenUnits::Default(n) => n,
200 }
201 }
202}
203
204pub struct LintGroup {
205 pub name: &'static str,
206 pub lints: Vec<LintId>,
207 pub is_externally_loaded: bool,
208}
209
210impl Session {
211 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
212 self.miri_unleashed_features.lock().push((span, feature_gate));
213 }
214
215 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
216 Some(self.source_map().path_mapping().to_real_filename(self.io.input.opt_path()?))
217 }
218
219 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
220 let mut guar = None;
221 let unleashed_features = self.miri_unleashed_features.lock();
222 if !unleashed_features.is_empty() {
223 let mut must_err = false;
224 self.dcx().emit_warn(errors::SkippingConstChecks {
226 unleashed_features: unleashed_features
227 .iter()
228 .map(|(span, gate)| {
229 gate.map(|gate| {
230 must_err = true;
231 errors::UnleashedFeatureHelp::Named { span: *span, gate }
232 })
233 .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })
234 })
235 .collect(),
236 });
237
238 if must_err && self.dcx().has_errors().is_none() {
240 guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));
242 }
243 }
244 guar
245 }
246
247 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
249 let mut guar = None;
250 guar = guar.or(self.check_miri_unleashed_features());
251 guar = guar.or(self.dcx().emit_stashed_diagnostics());
252 self.dcx().print_error_count();
253 if self.opts.json_future_incompat {
254 self.dcx().emit_future_breakage_report();
255 }
256 guar
257 }
258
259 pub fn is_test_crate(&self) -> bool {
261 self.opts.test
262 }
263
264 #[track_caller]
266 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
267 let mut err = self.dcx().create_err(err);
268 if err.code.is_none() {
269 #[allow(rustc::diagnostic_outside_of_impl)]
270 err.code(E0658);
271 }
272 add_feature_diagnostics(&mut err, self, feature);
273 err
274 }
275
276 pub fn record_trimmed_def_paths(&self) {
279 if self.opts.unstable_opts.print_type_sizes
280 || self.opts.unstable_opts.query_dep_graph
281 || self.opts.unstable_opts.dump_mir.is_some()
282 || self.opts.unstable_opts.unpretty.is_some()
283 || self.prof.is_args_recording_enabled()
284 || self.opts.output_types.contains_key(&OutputType::Mir)
285 || std::env::var_os("RUSTC_LOG").is_some()
286 {
287 return;
288 }
289
290 self.dcx().set_must_produce_diag()
291 }
292
293 #[inline]
294 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
295 self.psess.dcx()
296 }
297
298 #[inline]
299 pub fn source_map(&self) -> &SourceMap {
300 self.psess.source_map()
301 }
302
303 pub fn enable_internal_lints(&self) -> bool {
307 self.unstable_options() && !self.opts.actually_rustdoc
308 }
309
310 pub fn instrument_coverage(&self) -> bool {
311 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
312 }
313
314 pub fn instrument_coverage_branch(&self) -> bool {
315 self.instrument_coverage()
316 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
317 }
318
319 pub fn instrument_coverage_condition(&self) -> bool {
320 self.instrument_coverage()
321 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
322 }
323
324 pub fn coverage_options(&self) -> &CoverageOptions {
328 &self.opts.unstable_opts.coverage_options
329 }
330
331 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
332 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::CFI)
333 }
334
335 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
336 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
337 }
338
339 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
340 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
341 }
342
343 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
344 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
345 }
346
347 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
348 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
349 }
350
351 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
352 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
353 }
354
355 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
356 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::KCFI)
357 }
358
359 pub fn is_split_lto_unit_enabled(&self) -> bool {
360 self.opts.unstable_opts.split_lto_unit == Some(true)
361 }
362
363 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
365 if !self.target.crt_static_respected {
366 return self.target.crt_static_default;
368 }
369
370 let requested_features = self.opts.cg.target_feature.split(',');
371 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
372 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
373
374 #[allow(rustc::bad_opt_access)]
376 if found_positive || found_negative {
377 found_positive
378 } else if crate_type == Some(CrateType::ProcMacro)
379 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
380 {
381 false
385 } else {
386 self.target.crt_static_default
387 }
388 }
389
390 pub fn is_wasi_reactor(&self) -> bool {
391 self.target.options.os == "wasi"
392 && matches!(
393 self.opts.unstable_opts.wasi_exec_model,
394 Some(config::WasiExecModel::Reactor)
395 )
396 }
397
398 pub fn target_can_use_split_dwarf(&self) -> bool {
400 self.target.debuginfo_kind == DebuginfoKind::Dwarf
401 }
402
403 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
404 format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.as_u64())
405 }
406
407 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
408 &self.target_filesearch
409 }
410 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
411 &self.host_filesearch
412 }
413
414 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
418 let search_paths = self
419 .opts
420 .sysroot
421 .all_paths()
422 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
423
424 if self_contained {
425 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
429 } else {
430 search_paths.collect()
431 }
432 }
433
434 pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
435 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
436
437 if let IncrCompSession::NotInitialized = *incr_comp_session {
438 } else {
439 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
440 }
441
442 *incr_comp_session =
443 IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
444 }
445
446 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
447 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
448
449 if let IncrCompSession::Active { .. } = *incr_comp_session {
450 } else {
451 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
452 }
453
454 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
456 }
457
458 pub fn mark_incr_comp_session_as_invalid(&self) {
459 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
460
461 let session_directory = match *incr_comp_session {
462 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
463 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
464 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
465 };
466
467 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
469 }
470
471 pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
472 let incr_comp_session = self.incr_comp_session.borrow();
473 ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
474 IncrCompSession::NotInitialized => panic!(
475 "trying to get session directory from `IncrCompSession`: {:?}",
476 *incr_comp_session,
477 ),
478 IncrCompSession::Active { ref session_directory, .. }
479 | IncrCompSession::Finalized { ref session_directory }
480 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
481 session_directory
482 }
483 })
484 }
485
486 pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
487 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
488 }
489
490 pub fn is_rust_2015(&self) -> bool {
492 self.edition().is_rust_2015()
493 }
494
495 pub fn at_least_rust_2018(&self) -> bool {
497 self.edition().at_least_rust_2018()
498 }
499
500 pub fn at_least_rust_2021(&self) -> bool {
502 self.edition().at_least_rust_2021()
503 }
504
505 pub fn at_least_rust_2024(&self) -> bool {
507 self.edition().at_least_rust_2024()
508 }
509
510 pub fn needs_plt(&self) -> bool {
512 let want_plt = self.target.plt_by_default;
515
516 let dbg_opts = &self.opts.unstable_opts;
517
518 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
519
520 let full_relro = RelroLevel::Full == relro_level;
524
525 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
528 }
529
530 pub fn emit_lifetime_markers(&self) -> bool {
532 self.opts.optimize != config::OptLevel::No
533 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
537 }
538
539 pub fn diagnostic_width(&self) -> usize {
540 let default_column_width = 140;
541 if let Some(width) = self.opts.diagnostic_width {
542 width
543 } else if self.opts.unstable_opts.ui_testing {
544 default_column_width
545 } else {
546 termize::dimensions().map_or(default_column_width, |(w, _)| w)
547 }
548 }
549
550 pub fn default_visibility(&self) -> SymbolVisibility {
552 self.opts
553 .unstable_opts
554 .default_visibility
555 .or(self.target.options.default_visibility)
556 .unwrap_or(SymbolVisibility::Interposable)
557 }
558
559 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
560 if verbatim {
561 ("", "")
562 } else {
563 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
564 }
565 }
566
567 pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
568 match self.lint_store {
569 Some(ref lint_store) => lint_store.lint_groups_iter(),
570 None => Box::new(std::iter::empty()),
571 }
572 }
573}
574
575#[allow(rustc::bad_opt_access)]
577impl Session {
578 pub fn verbose_internals(&self) -> bool {
579 self.opts.unstable_opts.verbose_internals
580 }
581
582 pub fn print_llvm_stats(&self) -> bool {
583 self.opts.unstable_opts.print_codegen_stats
584 }
585
586 pub fn verify_llvm_ir(&self) -> bool {
587 self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
588 }
589
590 pub fn binary_dep_depinfo(&self) -> bool {
591 self.opts.unstable_opts.binary_dep_depinfo
592 }
593
594 pub fn mir_opt_level(&self) -> usize {
595 self.opts
596 .unstable_opts
597 .mir_opt_level
598 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
599 }
600
601 pub fn lto(&self) -> config::Lto {
603 if self.target.requires_lto {
605 return config::Lto::Fat;
606 }
607
608 match self.opts.cg.lto {
612 config::LtoCli::Unspecified => {
613 }
616 config::LtoCli::No => {
617 return config::Lto::No;
619 }
620 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
621 return config::Lto::Fat;
623 }
624 config::LtoCli::Thin => {
625 return config::Lto::Thin;
627 }
628 }
629
630 if self.opts.cli_forced_local_thinlto_off {
639 return config::Lto::No;
640 }
641
642 if let Some(enabled) = self.opts.unstable_opts.thinlto {
645 if enabled {
646 return config::Lto::ThinLocal;
647 } else {
648 return config::Lto::No;
649 }
650 }
651
652 if self.codegen_units().as_usize() == 1 {
655 return config::Lto::No;
656 }
657
658 match self.opts.optimize {
661 config::OptLevel::No => config::Lto::No,
662 _ => config::Lto::ThinLocal,
663 }
664 }
665
666 pub fn panic_strategy(&self) -> PanicStrategy {
669 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
670 }
671
672 pub fn fewer_names(&self) -> bool {
673 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
674 fewer_names
675 } else {
676 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
677 || self.opts.output_types.contains_key(&OutputType::Bitcode)
678 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
680 !more_names
681 }
682 }
683
684 pub fn unstable_options(&self) -> bool {
685 self.opts.unstable_opts.unstable_options
686 }
687
688 pub fn is_nightly_build(&self) -> bool {
689 self.opts.unstable_features.is_nightly_build()
690 }
691
692 pub fn overflow_checks(&self) -> bool {
693 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
694 }
695
696 pub fn ub_checks(&self) -> bool {
697 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
698 }
699
700 pub fn contract_checks(&self) -> bool {
701 self.opts.unstable_opts.contract_checks.unwrap_or(false)
702 }
703
704 pub fn relocation_model(&self) -> RelocModel {
705 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
706 }
707
708 pub fn code_model(&self) -> Option<CodeModel> {
709 self.opts.cg.code_model.or(self.target.code_model)
710 }
711
712 pub fn tls_model(&self) -> TlsModel {
713 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
714 }
715
716 pub fn direct_access_external_data(&self) -> Option<bool> {
717 self.opts
718 .unstable_opts
719 .direct_access_external_data
720 .or(self.target.direct_access_external_data)
721 }
722
723 pub fn split_debuginfo(&self) -> SplitDebuginfo {
724 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
725 }
726
727 pub fn dwarf_version(&self) -> u32 {
729 self.opts
730 .cg
731 .dwarf_version
732 .or(self.opts.unstable_opts.dwarf_version)
733 .unwrap_or(self.target.default_dwarf_version)
734 }
735
736 pub fn stack_protector(&self) -> StackProtector {
737 if self.target.options.supports_stack_protector {
738 self.opts.unstable_opts.stack_protector
739 } else {
740 StackProtector::None
741 }
742 }
743
744 pub fn must_emit_unwind_tables(&self) -> bool {
745 self.target.requires_uwtable
773 || self.opts.cg.force_unwind_tables.unwrap_or(
774 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
775 )
776 }
777
778 #[inline]
781 pub fn threads(&self) -> usize {
782 self.opts.unstable_opts.threads
783 }
784
785 pub fn codegen_units(&self) -> CodegenUnits {
788 if let Some(n) = self.opts.cli_forced_codegen_units {
789 return CodegenUnits::User(n);
790 }
791 if let Some(n) = self.target.default_codegen_units {
792 return CodegenUnits::Default(n as usize);
793 }
794
795 if self.opts.incremental.is_some() {
799 return CodegenUnits::Default(256);
800 }
801
802 CodegenUnits::Default(16)
853 }
854
855 pub fn teach(&self, code: ErrCode) -> bool {
856 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
857 }
858
859 pub fn edition(&self) -> Edition {
860 self.opts.edition
861 }
862
863 pub fn link_dead_code(&self) -> bool {
864 self.opts.cg.link_dead_code.unwrap_or(false)
865 }
866
867 pub fn filename_display_preference(
868 &self,
869 scope: RemapPathScopeComponents,
870 ) -> FileNameDisplayPreference {
871 assert!(
872 scope.bits().count_ones() == 1,
873 "one and only one scope should be passed to `Session::filename_display_preference`"
874 );
875 if self.opts.unstable_opts.remap_path_scope.contains(scope) {
876 FileNameDisplayPreference::Remapped
877 } else {
878 FileNameDisplayPreference::Local
879 }
880 }
881
882 pub fn apple_deployment_target(&self) -> apple::OSVersion {
887 let min = apple::OSVersion::minimum_deployment_target(&self.target);
888 let env_var = apple::deployment_target_env_var(&self.target.os);
889
890 if let Ok(deployment_target) = env::var(env_var) {
892 match apple::OSVersion::from_str(&deployment_target) {
893 Ok(version) => {
894 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
895 if version < os_min {
900 self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {
901 env_var,
902 version: version.fmt_pretty().to_string(),
903 os_min: os_min.fmt_pretty().to_string(),
904 });
905 }
906
907 version.max(min)
909 }
910 Err(error) => {
911 self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });
912 min
913 }
914 }
915 } else {
916 min
918 }
919 }
920}
921
922#[allow(rustc::bad_opt_access)]
924fn default_emitter(
925 sopts: &config::Options,
926 source_map: Arc<SourceMap>,
927 translator: Translator,
928) -> Box<DynEmitter> {
929 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
930 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
931 let terminal_url = match sopts.unstable_opts.terminal_urls {
932 TerminalUrl::Auto => {
933 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
934 (Ok("truecolor"), Ok("xterm-256color"))
935 if sopts.unstable_features.is_nightly_build() =>
936 {
937 TerminalUrl::Yes
938 }
939 _ => TerminalUrl::No,
940 }
941 }
942 t => t,
943 };
944
945 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
946
947 match sopts.error_format {
948 config::ErrorOutputType::HumanReadable { kind, color_config } => {
949 let short = kind.short();
950
951 if let HumanReadableErrorType::AnnotateSnippet = kind {
952 let emitter =
953 AnnotateSnippetEmitter::new(source_map, translator, short, macro_backtrace);
954 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
955 } else {
956 let emitter = HumanEmitter::new(stderr_destination(color_config), translator)
957 .sm(source_map)
958 .short_message(short)
959 .diagnostic_width(sopts.diagnostic_width)
960 .macro_backtrace(macro_backtrace)
961 .track_diagnostics(track_diagnostics)
962 .terminal_url(terminal_url)
963 .theme(if let HumanReadableErrorType::Unicode = kind {
964 OutputTheme::Unicode
965 } else {
966 OutputTheme::Ascii
967 })
968 .ignored_directories_in_source_blocks(
969 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
970 );
971 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
972 }
973 }
974 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
975 JsonEmitter::new(
976 Box::new(io::BufWriter::new(io::stderr())),
977 source_map,
978 translator,
979 pretty,
980 json_rendered,
981 color_config,
982 )
983 .ui_testing(sopts.unstable_opts.ui_testing)
984 .ignored_directories_in_source_blocks(
985 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
986 )
987 .diagnostic_width(sopts.diagnostic_width)
988 .macro_backtrace(macro_backtrace)
989 .track_diagnostics(track_diagnostics)
990 .terminal_url(terminal_url),
991 ),
992 }
993}
994
995#[allow(rustc::bad_opt_access)]
997#[allow(rustc::untranslatable_diagnostic)] pub fn build_session(
999 sopts: config::Options,
1000 io: CompilerIO,
1001 fluent_bundle: Option<Arc<rustc_errors::FluentBundle>>,
1002 registry: rustc_errors::registry::Registry,
1003 fluent_resources: Vec<&'static str>,
1004 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1005 target: Target,
1006 cfg_version: &'static str,
1007 ice_file: Option<PathBuf>,
1008 using_internal_features: &'static AtomicBool,
1009 expanded_args: Vec<String>,
1010) -> Session {
1011 let warnings_allow = sopts
1015 .lint_opts
1016 .iter()
1017 .rfind(|&(key, _)| *key == "warnings")
1018 .is_some_and(|&(_, level)| level == lint::Allow);
1019 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1020 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1021
1022 let translator = Translator {
1023 fluent_bundle,
1024 fallback_fluent_bundle: fallback_fluent_bundle(
1025 fluent_resources,
1026 sopts.unstable_opts.translate_directionality_markers,
1027 ),
1028 };
1029 let source_map = rustc_span::source_map::get_source_map().unwrap();
1030 let emitter = default_emitter(&sopts, Arc::clone(&source_map), translator);
1031
1032 let mut dcx = DiagCtxt::new(emitter)
1033 .with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings))
1034 .with_registry(registry);
1035 if let Some(ice_file) = ice_file {
1036 dcx = dcx.with_ice_file(ice_file);
1037 }
1038
1039 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1040 let (host, target_warnings) = Target::search(&host_triple, sopts.sysroot.path())
1041 .unwrap_or_else(|e| dcx.handle().fatal(format!("Error loading host specification: {e}")));
1042 for warning in target_warnings.warning_messages() {
1043 dcx.handle().warn(warning)
1044 }
1045
1046 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1047 {
1048 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1049
1050 let profiler = SelfProfiler::new(
1051 directory,
1052 sopts.crate_name.as_deref(),
1053 sopts.unstable_opts.self_profile_events.as_deref(),
1054 &sopts.unstable_opts.self_profile_counter,
1055 );
1056 match profiler {
1057 Ok(profiler) => Some(Arc::new(profiler)),
1058 Err(e) => {
1059 dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1060 None
1061 }
1062 }
1063 } else {
1064 None
1065 };
1066
1067 let mut psess = ParseSess::with_dcx(dcx, source_map);
1068 psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1069
1070 let host_triple = config::host_tuple();
1071 let target_triple = sopts.target_triple.tuple();
1072 let host_tlib_path =
1074 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1075 let target_tlib_path = if host_triple == target_triple {
1076 Arc::clone(&host_tlib_path)
1079 } else {
1080 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1081 };
1082
1083 let prof = SelfProfilerRef::new(
1084 self_profiler,
1085 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1086 );
1087
1088 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1089 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1090 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1091 _ => CtfeBacktrace::Disabled,
1092 });
1093
1094 let asm_arch = if target.allow_asm { InlineAsmArch::from_str(&target.arch).ok() } else { None };
1095 let target_filesearch =
1096 filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1097 let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1098
1099 let invocation_temp = sopts
1100 .incremental
1101 .as_ref()
1102 .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
1103
1104 let timings = TimingSectionHandler::new(sopts.json_timings);
1105
1106 let sess = Session {
1107 target,
1108 host,
1109 opts: sopts,
1110 target_tlib_path,
1111 psess,
1112 io,
1113 incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1114 prof,
1115 timings,
1116 code_stats: Default::default(),
1117 lint_store: None,
1118 driver_lint_caps,
1119 ctfe_backtrace,
1120 miri_unleashed_features: Lock::new(Default::default()),
1121 asm_arch,
1122 target_features: Default::default(),
1123 unstable_target_features: Default::default(),
1124 cfg_version,
1125 using_internal_features,
1126 expanded_args,
1127 target_filesearch,
1128 host_filesearch,
1129 invocation_temp,
1130 };
1131
1132 validate_commandline_args_with_session_available(&sess);
1133
1134 sess
1135}
1136
1137#[allow(rustc::bad_opt_access)]
1143fn validate_commandline_args_with_session_available(sess: &Session) {
1144 if sess.opts.cg.linker_plugin_lto.enabled()
1152 && sess.opts.cg.prefer_dynamic
1153 && sess.target.is_like_windows
1154 {
1155 sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1156 }
1157
1158 if let Some(ref path) = sess.opts.cg.profile_use {
1161 if !path.exists() {
1162 sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1163 }
1164 }
1165
1166 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1168 if !path.exists() {
1169 sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1170 }
1171 }
1172
1173 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1175 if sess.target.requires_uwtable && !include_uwtables {
1176 sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1177 }
1178 }
1179
1180 let supported_sanitizers = sess.target.options.supported_sanitizers;
1182 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1183 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == "aarch64" {
1186 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1187 }
1188 match unsupported_sanitizers.into_iter().count() {
1189 0 => {}
1190 1 => {
1191 sess.dcx()
1192 .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1193 }
1194 _ => {
1195 sess.dcx().emit_err(errors::SanitizersNotSupported {
1196 us: unsupported_sanitizers.to_string(),
1197 });
1198 }
1199 }
1200
1201 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1203 sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1204 first: first.to_string(),
1205 second: second.to_string(),
1206 });
1207 }
1208
1209 if sess.crt_static(None)
1211 && !sess.opts.unstable_opts.sanitizer.is_empty()
1212 && !sess.target.is_like_msvc
1213 {
1214 sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1215 }
1216
1217 if sess.is_sanitizer_cfi_enabled()
1219 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1220 {
1221 sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1222 }
1223
1224 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy() != PanicStrategy::Abort {
1226 sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1227 }
1228
1229 if sess.is_sanitizer_cfi_enabled()
1231 && sess.lto() == config::Lto::Fat
1232 && (sess.codegen_units().as_usize() != 1)
1233 {
1234 sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1235 }
1236
1237 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1239 if !sess.is_sanitizer_cfi_enabled() {
1240 sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1241 }
1242 }
1243
1244 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1246 sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);
1247 }
1248
1249 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1251 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1252 sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1253 }
1254 }
1255
1256 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1258 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1259 sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1260 }
1261 }
1262
1263 if sess.is_split_lto_unit_enabled()
1265 && !(sess.lto() == config::Lto::Fat
1266 || sess.lto() == config::Lto::Thin
1267 || sess.opts.cg.linker_plugin_lto.enabled())
1268 {
1269 sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1270 }
1271
1272 if sess.lto() != config::Lto::Fat {
1274 if sess.opts.unstable_opts.virtual_function_elimination {
1275 sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1276 }
1277 }
1278
1279 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1280 if !sess.target.options.supports_stack_protector {
1281 sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1282 stack_protector: sess.opts.unstable_opts.stack_protector,
1283 target_triple: &sess.opts.target_triple,
1284 });
1285 }
1286 }
1287
1288 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1289 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1290 sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1291 target_triple: &sess.opts.target_triple,
1292 })
1293 }
1294 }
1295
1296 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != "aarch64" {
1297 sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1298 }
1299
1300 if let Some(dwarf_version) =
1301 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1302 {
1303 if dwarf_version < 2 || dwarf_version > 5 {
1305 sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1306 }
1307 }
1308
1309 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1310 && !sess.opts.unstable_opts.unstable_options
1311 {
1312 sess.dcx()
1313 .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1314 }
1315
1316 if sess.opts.unstable_opts.embed_source {
1317 let dwarf_version = sess.dwarf_version();
1318
1319 if dwarf_version < 5 {
1320 sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1321 }
1322
1323 if sess.opts.debuginfo == DebugInfo::None {
1324 sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1325 }
1326 }
1327
1328 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1329 sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1330 }
1331
1332 if let Some(flavor) = sess.opts.cg.linker_flavor
1333 && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1334 {
1335 let flavor = flavor.desc();
1336 sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1337 }
1338
1339 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1340 if sess.target.arch != "x86" && sess.target.arch != "x86_64" {
1341 sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1342 }
1343 }
1344
1345 if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1346 if sess.target.arch != "x86" && sess.target.arch != "x86_64" {
1347 sess.dcx().emit_err(errors::IndirectBranchCsPrefixRequiresX86OrX8664);
1348 }
1349 }
1350
1351 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1352 if regparm > 3 {
1353 sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1354 }
1355 if sess.target.arch != "x86" {
1356 sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1357 }
1358 }
1359 if sess.opts.unstable_opts.reg_struct_return {
1360 if sess.target.arch != "x86" {
1361 sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1362 }
1363 }
1364
1365 match sess.opts.unstable_opts.function_return {
1369 FunctionReturn::Keep => (),
1370 FunctionReturn::ThunkExtern => {
1371 if let Some(code_model) = sess.code_model()
1374 && code_model == CodeModel::Large
1375 {
1376 sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1377 }
1378 }
1379 }
1380
1381 if sess.opts.cg.soft_float {
1382 if sess.target.arch == "arm" {
1383 sess.dcx().emit_warn(errors::SoftFloatDeprecated);
1384 } else {
1385 sess.dcx().emit_warn(errors::SoftFloatIgnored);
1388 }
1389 }
1390}
1391
1392#[derive(Debug)]
1394enum IncrCompSession {
1395 NotInitialized,
1398 Active { session_directory: PathBuf, _lock_file: flock::Lock },
1403 Finalized { session_directory: PathBuf },
1406 InvalidBecauseOfErrors { session_directory: PathBuf },
1410}
1411
1412pub struct EarlyDiagCtxt {
1414 dcx: DiagCtxt,
1415}
1416
1417impl EarlyDiagCtxt {
1418 pub fn new(output: ErrorOutputType) -> Self {
1419 let emitter = mk_emitter(output);
1420 Self { dcx: DiagCtxt::new(emitter) }
1421 }
1422
1423 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1426 assert!(self.dcx.handle().has_errors().is_none());
1427
1428 let emitter = mk_emitter(output);
1429 self.dcx = DiagCtxt::new(emitter);
1430 }
1431
1432 #[allow(rustc::untranslatable_diagnostic)]
1433 #[allow(rustc::diagnostic_outside_of_impl)]
1434 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1435 self.dcx.handle().note(msg)
1436 }
1437
1438 #[allow(rustc::untranslatable_diagnostic)]
1439 #[allow(rustc::diagnostic_outside_of_impl)]
1440 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1441 self.dcx.handle().struct_help(msg).emit()
1442 }
1443
1444 #[allow(rustc::untranslatable_diagnostic)]
1445 #[allow(rustc::diagnostic_outside_of_impl)]
1446 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1447 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1448 self.dcx.handle().err(msg)
1449 }
1450
1451 #[allow(rustc::untranslatable_diagnostic)]
1452 #[allow(rustc::diagnostic_outside_of_impl)]
1453 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1454 self.dcx.handle().fatal(msg)
1455 }
1456
1457 #[allow(rustc::untranslatable_diagnostic)]
1458 #[allow(rustc::diagnostic_outside_of_impl)]
1459 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1460 self.dcx.handle().struct_fatal(msg)
1461 }
1462
1463 #[allow(rustc::untranslatable_diagnostic)]
1464 #[allow(rustc::diagnostic_outside_of_impl)]
1465 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1466 self.dcx.handle().warn(msg)
1467 }
1468
1469 #[allow(rustc::untranslatable_diagnostic)]
1470 #[allow(rustc::diagnostic_outside_of_impl)]
1471 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1472 self.dcx.handle().struct_warn(msg)
1473 }
1474}
1475
1476fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1477 let translator =
1480 Translator::with_fallback_bundle(vec![rustc_errors::DEFAULT_LOCALE_RESOURCE], false);
1481 let emitter: Box<DynEmitter> = match output {
1482 config::ErrorOutputType::HumanReadable { kind, color_config } => {
1483 let short = kind.short();
1484 Box::new(
1485 HumanEmitter::new(stderr_destination(color_config), translator)
1486 .theme(if let HumanReadableErrorType::Unicode = kind {
1487 OutputTheme::Unicode
1488 } else {
1489 OutputTheme::Ascii
1490 })
1491 .short_message(short),
1492 )
1493 }
1494 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1495 Box::new(JsonEmitter::new(
1496 Box::new(io::BufWriter::new(io::stderr())),
1497 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1498 translator,
1499 pretty,
1500 json_rendered,
1501 color_config,
1502 ))
1503 }
1504 };
1505 emitter
1506}
1507
1508pub trait RemapFileNameExt {
1509 type Output<'a>
1510 where
1511 Self: 'a;
1512
1513 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_>;
1517}
1518
1519impl RemapFileNameExt for rustc_span::FileName {
1520 type Output<'a> = rustc_span::FileNameDisplay<'a>;
1521
1522 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1523 assert!(
1524 scope.bits().count_ones() == 1,
1525 "one and only one scope should be passed to for_scope"
1526 );
1527 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1528 self.prefer_remapped_unconditionally()
1529 } else {
1530 self.prefer_local()
1531 }
1532 }
1533}
1534
1535impl RemapFileNameExt for rustc_span::RealFileName {
1536 type Output<'a> = &'a Path;
1537
1538 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1539 assert!(
1540 scope.bits().count_ones() == 1,
1541 "one and only one scope should be passed to for_scope"
1542 );
1543 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1544 self.remapped_path_if_available()
1545 } else {
1546 self.local_path_if_available()
1547 }
1548 }
1549}