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 target_filesearch: FileSearch,
152 host_filesearch: FileSearch,
153
154 pub invocation_temp: Option<String>,
161}
162
163impl LintEmitter for &'_ Session {
164 type Id = NodeId;
165
166 fn emit_node_span_lint(
167 self,
168 lint: &'static rustc_lint_defs::Lint,
169 node_id: Self::Id,
170 span: impl Into<rustc_errors::MultiSpan>,
171 decorator: impl for<'a> rustc_errors::LintDiagnostic<'a, ()> + DynSend + 'static,
172 ) {
173 self.psess.buffer_lint(lint, span, node_id, decorator);
174 }
175}
176
177#[derive(Clone, Copy)]
178pub enum CodegenUnits {
179 User(usize),
182
183 Default(usize),
187}
188
189impl CodegenUnits {
190 pub fn as_usize(self) -> usize {
191 match self {
192 CodegenUnits::User(n) => n,
193 CodegenUnits::Default(n) => n,
194 }
195 }
196}
197
198pub struct LintGroup {
199 pub name: &'static str,
200 pub lints: Vec<LintId>,
201 pub is_externally_loaded: bool,
202}
203
204impl Session {
205 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
206 self.miri_unleashed_features.lock().push((span, feature_gate));
207 }
208
209 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
210 Some(self.source_map().path_mapping().to_real_filename(self.io.input.opt_path()?))
211 }
212
213 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
214 let mut guar = None;
215 let unleashed_features = self.miri_unleashed_features.lock();
216 if !unleashed_features.is_empty() {
217 let mut must_err = false;
218 self.dcx().emit_warn(errors::SkippingConstChecks {
220 unleashed_features: unleashed_features
221 .iter()
222 .map(|(span, gate)| {
223 gate.map(|gate| {
224 must_err = true;
225 errors::UnleashedFeatureHelp::Named { span: *span, gate }
226 })
227 .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })
228 })
229 .collect(),
230 });
231
232 if must_err && self.dcx().has_errors().is_none() {
234 guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));
236 }
237 }
238 guar
239 }
240
241 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
243 let mut guar = None;
244 guar = guar.or(self.check_miri_unleashed_features());
245 guar = guar.or(self.dcx().emit_stashed_diagnostics());
246 self.dcx().print_error_count();
247 if self.opts.json_future_incompat {
248 self.dcx().emit_future_breakage_report();
249 }
250 guar
251 }
252
253 pub fn is_test_crate(&self) -> bool {
255 self.opts.test
256 }
257
258 #[track_caller]
260 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
261 let mut err = self.dcx().create_err(err);
262 if err.code.is_none() {
263 #[allow(rustc::diagnostic_outside_of_impl)]
264 err.code(E0658);
265 }
266 add_feature_diagnostics(&mut err, self, feature);
267 err
268 }
269
270 pub fn record_trimmed_def_paths(&self) {
273 if self.opts.unstable_opts.print_type_sizes
274 || self.opts.unstable_opts.query_dep_graph
275 || self.opts.unstable_opts.dump_mir.is_some()
276 || self.opts.unstable_opts.unpretty.is_some()
277 || self.prof.is_args_recording_enabled()
278 || self.opts.output_types.contains_key(&OutputType::Mir)
279 || std::env::var_os("RUSTC_LOG").is_some()
280 {
281 return;
282 }
283
284 self.dcx().set_must_produce_diag()
285 }
286
287 #[inline]
288 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
289 self.psess.dcx()
290 }
291
292 #[inline]
293 pub fn source_map(&self) -> &SourceMap {
294 self.psess.source_map()
295 }
296
297 pub fn enable_internal_lints(&self) -> bool {
301 self.unstable_options() && !self.opts.actually_rustdoc
302 }
303
304 pub fn instrument_coverage(&self) -> bool {
305 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
306 }
307
308 pub fn instrument_coverage_branch(&self) -> bool {
309 self.instrument_coverage()
310 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
311 }
312
313 pub fn instrument_coverage_condition(&self) -> bool {
314 self.instrument_coverage()
315 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
316 }
317
318 pub fn coverage_options(&self) -> &CoverageOptions {
322 &self.opts.unstable_opts.coverage_options
323 }
324
325 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
326 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::CFI)
327 }
328
329 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
330 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
331 }
332
333 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
334 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
335 }
336
337 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
338 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
339 }
340
341 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
342 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
343 }
344
345 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
346 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
347 }
348
349 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
350 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::KCFI)
351 }
352
353 pub fn is_split_lto_unit_enabled(&self) -> bool {
354 self.opts.unstable_opts.split_lto_unit == Some(true)
355 }
356
357 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
359 if !self.target.crt_static_respected {
360 return self.target.crt_static_default;
362 }
363
364 let requested_features = self.opts.cg.target_feature.split(',');
365 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
366 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
367
368 #[allow(rustc::bad_opt_access)]
370 if found_positive || found_negative {
371 found_positive
372 } else if crate_type == Some(CrateType::ProcMacro)
373 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
374 {
375 false
379 } else {
380 self.target.crt_static_default
381 }
382 }
383
384 pub fn is_wasi_reactor(&self) -> bool {
385 self.target.options.os == "wasi"
386 && matches!(
387 self.opts.unstable_opts.wasi_exec_model,
388 Some(config::WasiExecModel::Reactor)
389 )
390 }
391
392 pub fn target_can_use_split_dwarf(&self) -> bool {
394 self.target.debuginfo_kind == DebuginfoKind::Dwarf
395 }
396
397 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
398 format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.as_u64())
399 }
400
401 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
402 &self.target_filesearch
403 }
404 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
405 &self.host_filesearch
406 }
407
408 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
412 let search_paths = self
413 .opts
414 .sysroot
415 .all_paths()
416 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
417
418 if self_contained {
419 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
423 } else {
424 search_paths.collect()
425 }
426 }
427
428 pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
429 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
430
431 if let IncrCompSession::NotInitialized = *incr_comp_session {
432 } else {
433 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
434 }
435
436 *incr_comp_session =
437 IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
438 }
439
440 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
441 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
442
443 if let IncrCompSession::Active { .. } = *incr_comp_session {
444 } else {
445 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
446 }
447
448 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
450 }
451
452 pub fn mark_incr_comp_session_as_invalid(&self) {
453 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
454
455 let session_directory = match *incr_comp_session {
456 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
457 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
458 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
459 };
460
461 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
463 }
464
465 pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
466 let incr_comp_session = self.incr_comp_session.borrow();
467 ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
468 IncrCompSession::NotInitialized => panic!(
469 "trying to get session directory from `IncrCompSession`: {:?}",
470 *incr_comp_session,
471 ),
472 IncrCompSession::Active { ref session_directory, .. }
473 | IncrCompSession::Finalized { ref session_directory }
474 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
475 session_directory
476 }
477 })
478 }
479
480 pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
481 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
482 }
483
484 pub fn is_rust_2015(&self) -> bool {
486 self.edition().is_rust_2015()
487 }
488
489 pub fn at_least_rust_2018(&self) -> bool {
491 self.edition().at_least_rust_2018()
492 }
493
494 pub fn at_least_rust_2021(&self) -> bool {
496 self.edition().at_least_rust_2021()
497 }
498
499 pub fn at_least_rust_2024(&self) -> bool {
501 self.edition().at_least_rust_2024()
502 }
503
504 pub fn needs_plt(&self) -> bool {
506 let want_plt = self.target.plt_by_default;
509
510 let dbg_opts = &self.opts.unstable_opts;
511
512 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
513
514 let full_relro = RelroLevel::Full == relro_level;
518
519 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
522 }
523
524 pub fn emit_lifetime_markers(&self) -> bool {
526 self.opts.optimize != config::OptLevel::No
527 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
531 }
532
533 pub fn diagnostic_width(&self) -> usize {
534 let default_column_width = 140;
535 if let Some(width) = self.opts.diagnostic_width {
536 width
537 } else if self.opts.unstable_opts.ui_testing {
538 default_column_width
539 } else {
540 termize::dimensions().map_or(default_column_width, |(w, _)| w)
541 }
542 }
543
544 pub fn default_visibility(&self) -> SymbolVisibility {
546 self.opts
547 .unstable_opts
548 .default_visibility
549 .or(self.target.options.default_visibility)
550 .unwrap_or(SymbolVisibility::Interposable)
551 }
552
553 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
554 if verbatim {
555 ("", "")
556 } else {
557 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
558 }
559 }
560
561 pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
562 match self.lint_store {
563 Some(ref lint_store) => lint_store.lint_groups_iter(),
564 None => Box::new(std::iter::empty()),
565 }
566 }
567}
568
569#[allow(rustc::bad_opt_access)]
571impl Session {
572 pub fn verbose_internals(&self) -> bool {
573 self.opts.unstable_opts.verbose_internals
574 }
575
576 pub fn print_llvm_stats(&self) -> bool {
577 self.opts.unstable_opts.print_codegen_stats
578 }
579
580 pub fn verify_llvm_ir(&self) -> bool {
581 self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
582 }
583
584 pub fn binary_dep_depinfo(&self) -> bool {
585 self.opts.unstable_opts.binary_dep_depinfo
586 }
587
588 pub fn mir_opt_level(&self) -> usize {
589 self.opts
590 .unstable_opts
591 .mir_opt_level
592 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
593 }
594
595 pub fn lto(&self) -> config::Lto {
597 if self.opts.autodiff_enabled() && !self.opts.crate_types.contains(&CrateType::ProcMacro) {
602 return config::Lto::Fat;
603 }
604
605 if self.target.requires_lto {
607 return config::Lto::Fat;
608 }
609
610 match self.opts.cg.lto {
614 config::LtoCli::Unspecified => {
615 }
618 config::LtoCli::No => {
619 return config::Lto::No;
621 }
622 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
623 return config::Lto::Fat;
625 }
626 config::LtoCli::Thin => {
627 return config::Lto::Thin;
629 }
630 }
631
632 if self.opts.cli_forced_local_thinlto_off {
641 return config::Lto::No;
642 }
643
644 if let Some(enabled) = self.opts.unstable_opts.thinlto {
647 if enabled {
648 return config::Lto::ThinLocal;
649 } else {
650 return config::Lto::No;
651 }
652 }
653
654 if self.codegen_units().as_usize() == 1 {
657 return config::Lto::No;
658 }
659
660 match self.opts.optimize {
663 config::OptLevel::No => config::Lto::No,
664 _ => config::Lto::ThinLocal,
665 }
666 }
667
668 pub fn panic_strategy(&self) -> PanicStrategy {
671 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
672 }
673
674 pub fn fewer_names(&self) -> bool {
675 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
676 fewer_names
677 } else {
678 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
679 || self.opts.output_types.contains_key(&OutputType::Bitcode)
680 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
682 !more_names
683 }
684 }
685
686 pub fn unstable_options(&self) -> bool {
687 self.opts.unstable_opts.unstable_options
688 }
689
690 pub fn is_nightly_build(&self) -> bool {
691 self.opts.unstable_features.is_nightly_build()
692 }
693
694 pub fn overflow_checks(&self) -> bool {
695 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
696 }
697
698 pub fn ub_checks(&self) -> bool {
699 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
700 }
701
702 pub fn contract_checks(&self) -> bool {
703 self.opts.unstable_opts.contract_checks.unwrap_or(false)
704 }
705
706 pub fn relocation_model(&self) -> RelocModel {
707 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
708 }
709
710 pub fn code_model(&self) -> Option<CodeModel> {
711 self.opts.cg.code_model.or(self.target.code_model)
712 }
713
714 pub fn tls_model(&self) -> TlsModel {
715 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
716 }
717
718 pub fn direct_access_external_data(&self) -> Option<bool> {
719 self.opts
720 .unstable_opts
721 .direct_access_external_data
722 .or(self.target.direct_access_external_data)
723 }
724
725 pub fn split_debuginfo(&self) -> SplitDebuginfo {
726 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
727 }
728
729 pub fn dwarf_version(&self) -> u32 {
731 self.opts
732 .cg
733 .dwarf_version
734 .or(self.opts.unstable_opts.dwarf_version)
735 .unwrap_or(self.target.default_dwarf_version)
736 }
737
738 pub fn stack_protector(&self) -> StackProtector {
739 if self.target.options.supports_stack_protector {
740 self.opts.unstable_opts.stack_protector
741 } else {
742 StackProtector::None
743 }
744 }
745
746 pub fn must_emit_unwind_tables(&self) -> bool {
747 self.target.requires_uwtable
776 || self
777 .opts
778 .cg
779 .force_unwind_tables
780 .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
781 }
782
783 #[inline]
786 pub fn threads(&self) -> usize {
787 self.opts.unstable_opts.threads
788 }
789
790 pub fn codegen_units(&self) -> CodegenUnits {
793 if let Some(n) = self.opts.cli_forced_codegen_units {
794 return CodegenUnits::User(n);
795 }
796 if let Some(n) = self.target.default_codegen_units {
797 return CodegenUnits::Default(n as usize);
798 }
799
800 if self.opts.incremental.is_some() {
804 return CodegenUnits::Default(256);
805 }
806
807 CodegenUnits::Default(16)
858 }
859
860 pub fn teach(&self, code: ErrCode) -> bool {
861 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
862 }
863
864 pub fn edition(&self) -> Edition {
865 self.opts.edition
866 }
867
868 pub fn link_dead_code(&self) -> bool {
869 self.opts.cg.link_dead_code.unwrap_or(false)
870 }
871
872 pub fn filename_display_preference(
873 &self,
874 scope: RemapPathScopeComponents,
875 ) -> FileNameDisplayPreference {
876 assert!(
877 scope.bits().count_ones() == 1,
878 "one and only one scope should be passed to `Session::filename_display_preference`"
879 );
880 if self.opts.unstable_opts.remap_path_scope.contains(scope) {
881 FileNameDisplayPreference::Remapped
882 } else {
883 FileNameDisplayPreference::Local
884 }
885 }
886
887 pub fn apple_deployment_target(&self) -> apple::OSVersion {
892 let min = apple::OSVersion::minimum_deployment_target(&self.target);
893 let env_var = apple::deployment_target_env_var(&self.target.os);
894
895 if let Ok(deployment_target) = env::var(env_var) {
897 match apple::OSVersion::from_str(&deployment_target) {
898 Ok(version) => {
899 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
900 if version < os_min {
905 self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {
906 env_var,
907 version: version.fmt_pretty().to_string(),
908 os_min: os_min.fmt_pretty().to_string(),
909 });
910 }
911
912 version.max(min)
914 }
915 Err(error) => {
916 self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });
917 min
918 }
919 }
920 } else {
921 min
923 }
924 }
925}
926
927#[allow(rustc::bad_opt_access)]
929fn default_emitter(
930 sopts: &config::Options,
931 source_map: Arc<SourceMap>,
932 translator: Translator,
933) -> Box<DynEmitter> {
934 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
935 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
936 let terminal_url = match sopts.unstable_opts.terminal_urls {
937 TerminalUrl::Auto => {
938 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
939 (Ok("truecolor"), Ok("xterm-256color"))
940 if sopts.unstable_features.is_nightly_build() =>
941 {
942 TerminalUrl::Yes
943 }
944 _ => TerminalUrl::No,
945 }
946 }
947 t => t,
948 };
949
950 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
951
952 match sopts.error_format {
953 config::ErrorOutputType::HumanReadable { kind, color_config } => {
954 let short = kind.short();
955
956 if let HumanReadableErrorType::AnnotateSnippet = kind {
957 let emitter =
958 AnnotateSnippetEmitter::new(source_map, translator, short, macro_backtrace);
959 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
960 } else {
961 let emitter = HumanEmitter::new(stderr_destination(color_config), translator)
962 .sm(source_map)
963 .short_message(short)
964 .diagnostic_width(sopts.diagnostic_width)
965 .macro_backtrace(macro_backtrace)
966 .track_diagnostics(track_diagnostics)
967 .terminal_url(terminal_url)
968 .theme(if let HumanReadableErrorType::Unicode = kind {
969 OutputTheme::Unicode
970 } else {
971 OutputTheme::Ascii
972 })
973 .ignored_directories_in_source_blocks(
974 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
975 );
976 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
977 }
978 }
979 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
980 JsonEmitter::new(
981 Box::new(io::BufWriter::new(io::stderr())),
982 source_map,
983 translator,
984 pretty,
985 json_rendered,
986 color_config,
987 )
988 .ui_testing(sopts.unstable_opts.ui_testing)
989 .ignored_directories_in_source_blocks(
990 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
991 )
992 .diagnostic_width(sopts.diagnostic_width)
993 .macro_backtrace(macro_backtrace)
994 .track_diagnostics(track_diagnostics)
995 .terminal_url(terminal_url),
996 ),
997 }
998}
999
1000#[allow(rustc::bad_opt_access)]
1002#[allow(rustc::untranslatable_diagnostic)] pub fn build_session(
1004 sopts: config::Options,
1005 io: CompilerIO,
1006 fluent_bundle: Option<Arc<rustc_errors::FluentBundle>>,
1007 registry: rustc_errors::registry::Registry,
1008 fluent_resources: Vec<&'static str>,
1009 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1010 target: Target,
1011 cfg_version: &'static str,
1012 ice_file: Option<PathBuf>,
1013 using_internal_features: &'static AtomicBool,
1014) -> Session {
1015 let warnings_allow = sopts
1019 .lint_opts
1020 .iter()
1021 .rfind(|&(key, _)| *key == "warnings")
1022 .is_some_and(|&(_, level)| level == lint::Allow);
1023 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1024 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1025
1026 let translator = Translator {
1027 fluent_bundle,
1028 fallback_fluent_bundle: fallback_fluent_bundle(
1029 fluent_resources,
1030 sopts.unstable_opts.translate_directionality_markers,
1031 ),
1032 };
1033 let source_map = rustc_span::source_map::get_source_map().unwrap();
1034 let emitter = default_emitter(&sopts, Arc::clone(&source_map), translator);
1035
1036 let mut dcx = DiagCtxt::new(emitter)
1037 .with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings))
1038 .with_registry(registry);
1039 if let Some(ice_file) = ice_file {
1040 dcx = dcx.with_ice_file(ice_file);
1041 }
1042
1043 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1044 let (host, target_warnings) = Target::search(&host_triple, sopts.sysroot.path())
1045 .unwrap_or_else(|e| dcx.handle().fatal(format!("Error loading host specification: {e}")));
1046 for warning in target_warnings.warning_messages() {
1047 dcx.handle().warn(warning)
1048 }
1049
1050 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1051 {
1052 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1053
1054 let profiler = SelfProfiler::new(
1055 directory,
1056 sopts.crate_name.as_deref(),
1057 sopts.unstable_opts.self_profile_events.as_deref(),
1058 &sopts.unstable_opts.self_profile_counter,
1059 );
1060 match profiler {
1061 Ok(profiler) => Some(Arc::new(profiler)),
1062 Err(e) => {
1063 dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1064 None
1065 }
1066 }
1067 } else {
1068 None
1069 };
1070
1071 let mut psess = ParseSess::with_dcx(dcx, source_map);
1072 psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1073
1074 let host_triple = config::host_tuple();
1075 let target_triple = sopts.target_triple.tuple();
1076 let host_tlib_path =
1078 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1079 let target_tlib_path = if host_triple == target_triple {
1080 Arc::clone(&host_tlib_path)
1083 } else {
1084 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1085 };
1086
1087 let prof = SelfProfilerRef::new(
1088 self_profiler,
1089 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1090 );
1091
1092 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1093 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1094 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1095 _ => CtfeBacktrace::Disabled,
1096 });
1097
1098 let asm_arch = if target.allow_asm { InlineAsmArch::from_str(&target.arch).ok() } else { None };
1099 let target_filesearch =
1100 filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1101 let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1102
1103 let invocation_temp = sopts
1104 .incremental
1105 .as_ref()
1106 .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
1107
1108 let timings = TimingSectionHandler::new(sopts.json_timings);
1109
1110 let sess = Session {
1111 target,
1112 host,
1113 opts: sopts,
1114 target_tlib_path,
1115 psess,
1116 io,
1117 incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1118 prof,
1119 timings,
1120 code_stats: Default::default(),
1121 lint_store: None,
1122 driver_lint_caps,
1123 ctfe_backtrace,
1124 miri_unleashed_features: Lock::new(Default::default()),
1125 asm_arch,
1126 target_features: Default::default(),
1127 unstable_target_features: Default::default(),
1128 cfg_version,
1129 using_internal_features,
1130 target_filesearch,
1131 host_filesearch,
1132 invocation_temp,
1133 };
1134
1135 validate_commandline_args_with_session_available(&sess);
1136
1137 sess
1138}
1139
1140#[allow(rustc::bad_opt_access)]
1146fn validate_commandline_args_with_session_available(sess: &Session) {
1147 if sess.opts.cg.linker_plugin_lto.enabled()
1155 && sess.opts.cg.prefer_dynamic
1156 && sess.target.is_like_windows
1157 {
1158 sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1159 }
1160
1161 if let Some(ref path) = sess.opts.cg.profile_use {
1164 if !path.exists() {
1165 sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1166 }
1167 }
1168
1169 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1171 if !path.exists() {
1172 sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1173 }
1174 }
1175
1176 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1178 if sess.target.requires_uwtable && !include_uwtables {
1179 sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1180 }
1181 }
1182
1183 let supported_sanitizers = sess.target.options.supported_sanitizers;
1185 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1186 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == "aarch64" {
1189 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1190 }
1191 match unsupported_sanitizers.into_iter().count() {
1192 0 => {}
1193 1 => {
1194 sess.dcx()
1195 .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1196 }
1197 _ => {
1198 sess.dcx().emit_err(errors::SanitizersNotSupported {
1199 us: unsupported_sanitizers.to_string(),
1200 });
1201 }
1202 }
1203
1204 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1206 sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1207 first: first.to_string(),
1208 second: second.to_string(),
1209 });
1210 }
1211
1212 if sess.crt_static(None)
1214 && !sess.opts.unstable_opts.sanitizer.is_empty()
1215 && !sess.target.is_like_msvc
1216 {
1217 sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1218 }
1219
1220 if sess.is_sanitizer_cfi_enabled()
1222 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1223 {
1224 sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1225 }
1226
1227 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1229 sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1230 }
1231
1232 if sess.is_sanitizer_cfi_enabled()
1234 && sess.lto() == config::Lto::Fat
1235 && (sess.codegen_units().as_usize() != 1)
1236 {
1237 sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1238 }
1239
1240 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1242 if !sess.is_sanitizer_cfi_enabled() {
1243 sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1244 }
1245 }
1246
1247 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1249 sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);
1250 }
1251
1252 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1254 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1255 sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1256 }
1257 }
1258
1259 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1261 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1262 sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1263 }
1264 }
1265
1266 if sess.is_split_lto_unit_enabled()
1268 && !(sess.lto() == config::Lto::Fat
1269 || sess.lto() == config::Lto::Thin
1270 || sess.opts.cg.linker_plugin_lto.enabled())
1271 {
1272 sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1273 }
1274
1275 if sess.lto() != config::Lto::Fat {
1277 if sess.opts.unstable_opts.virtual_function_elimination {
1278 sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1279 }
1280 }
1281
1282 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1283 if !sess.target.options.supports_stack_protector {
1284 sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1285 stack_protector: sess.opts.unstable_opts.stack_protector,
1286 target_triple: &sess.opts.target_triple,
1287 });
1288 }
1289 }
1290
1291 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1292 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1293 sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1294 target_triple: &sess.opts.target_triple,
1295 })
1296 }
1297 }
1298
1299 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != "aarch64" {
1300 sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1301 }
1302
1303 if let Some(dwarf_version) =
1304 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1305 {
1306 if dwarf_version < 2 || dwarf_version > 5 {
1308 sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1309 }
1310 }
1311
1312 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1313 && !sess.opts.unstable_opts.unstable_options
1314 {
1315 sess.dcx()
1316 .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1317 }
1318
1319 if sess.opts.unstable_opts.embed_source {
1320 let dwarf_version = sess.dwarf_version();
1321
1322 if dwarf_version < 5 {
1323 sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1324 }
1325
1326 if sess.opts.debuginfo == DebugInfo::None {
1327 sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1328 }
1329 }
1330
1331 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1332 sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1333 }
1334
1335 if let Some(flavor) = sess.opts.cg.linker_flavor
1336 && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1337 {
1338 let flavor = flavor.desc();
1339 sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1340 }
1341
1342 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1343 if sess.target.arch != "x86" && sess.target.arch != "x86_64" {
1344 sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1345 }
1346 }
1347
1348 if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1349 if sess.target.arch != "x86" && sess.target.arch != "x86_64" {
1350 sess.dcx().emit_err(errors::IndirectBranchCsPrefixRequiresX86OrX8664);
1351 }
1352 }
1353
1354 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1355 if regparm > 3 {
1356 sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1357 }
1358 if sess.target.arch != "x86" {
1359 sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1360 }
1361 }
1362 if sess.opts.unstable_opts.reg_struct_return {
1363 if sess.target.arch != "x86" {
1364 sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1365 }
1366 }
1367
1368 match sess.opts.unstable_opts.function_return {
1372 FunctionReturn::Keep => (),
1373 FunctionReturn::ThunkExtern => {
1374 if let Some(code_model) = sess.code_model()
1377 && code_model == CodeModel::Large
1378 {
1379 sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1380 }
1381 }
1382 }
1383
1384 if sess.opts.cg.soft_float {
1385 if sess.target.arch == "arm" {
1386 sess.dcx().emit_warn(errors::SoftFloatDeprecated);
1387 } else {
1388 sess.dcx().emit_warn(errors::SoftFloatIgnored);
1391 }
1392 }
1393}
1394
1395#[derive(Debug)]
1397enum IncrCompSession {
1398 NotInitialized,
1401 Active { session_directory: PathBuf, _lock_file: flock::Lock },
1406 Finalized { session_directory: PathBuf },
1409 InvalidBecauseOfErrors { session_directory: PathBuf },
1413}
1414
1415pub struct EarlyDiagCtxt {
1417 dcx: DiagCtxt,
1418}
1419
1420impl EarlyDiagCtxt {
1421 pub fn new(output: ErrorOutputType) -> Self {
1422 let emitter = mk_emitter(output);
1423 Self { dcx: DiagCtxt::new(emitter) }
1424 }
1425
1426 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1429 assert!(self.dcx.handle().has_errors().is_none());
1430
1431 let emitter = mk_emitter(output);
1432 self.dcx = DiagCtxt::new(emitter);
1433 }
1434
1435 #[allow(rustc::untranslatable_diagnostic)]
1436 #[allow(rustc::diagnostic_outside_of_impl)]
1437 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1438 self.dcx.handle().note(msg)
1439 }
1440
1441 #[allow(rustc::untranslatable_diagnostic)]
1442 #[allow(rustc::diagnostic_outside_of_impl)]
1443 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1444 self.dcx.handle().struct_help(msg).emit()
1445 }
1446
1447 #[allow(rustc::untranslatable_diagnostic)]
1448 #[allow(rustc::diagnostic_outside_of_impl)]
1449 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1450 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1451 self.dcx.handle().err(msg)
1452 }
1453
1454 #[allow(rustc::untranslatable_diagnostic)]
1455 #[allow(rustc::diagnostic_outside_of_impl)]
1456 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1457 self.dcx.handle().fatal(msg)
1458 }
1459
1460 #[allow(rustc::untranslatable_diagnostic)]
1461 #[allow(rustc::diagnostic_outside_of_impl)]
1462 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1463 self.dcx.handle().struct_fatal(msg)
1464 }
1465
1466 #[allow(rustc::untranslatable_diagnostic)]
1467 #[allow(rustc::diagnostic_outside_of_impl)]
1468 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1469 self.dcx.handle().warn(msg)
1470 }
1471
1472 #[allow(rustc::untranslatable_diagnostic)]
1473 #[allow(rustc::diagnostic_outside_of_impl)]
1474 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1475 self.dcx.handle().struct_warn(msg)
1476 }
1477}
1478
1479fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1480 let translator =
1483 Translator::with_fallback_bundle(vec![rustc_errors::DEFAULT_LOCALE_RESOURCE], false);
1484 let emitter: Box<DynEmitter> = match output {
1485 config::ErrorOutputType::HumanReadable { kind, color_config } => {
1486 let short = kind.short();
1487 Box::new(
1488 HumanEmitter::new(stderr_destination(color_config), translator)
1489 .theme(if let HumanReadableErrorType::Unicode = kind {
1490 OutputTheme::Unicode
1491 } else {
1492 OutputTheme::Ascii
1493 })
1494 .short_message(short),
1495 )
1496 }
1497 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1498 Box::new(JsonEmitter::new(
1499 Box::new(io::BufWriter::new(io::stderr())),
1500 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1501 translator,
1502 pretty,
1503 json_rendered,
1504 color_config,
1505 ))
1506 }
1507 };
1508 emitter
1509}
1510
1511pub trait RemapFileNameExt {
1512 type Output<'a>
1513 where
1514 Self: 'a;
1515
1516 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_>;
1520}
1521
1522impl RemapFileNameExt for rustc_span::FileName {
1523 type Output<'a> = rustc_span::FileNameDisplay<'a>;
1524
1525 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1526 assert!(
1527 scope.bits().count_ones() == 1,
1528 "one and only one scope should be passed to for_scope"
1529 );
1530 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1531 self.prefer_remapped_unconditionally()
1532 } else {
1533 self.prefer_local()
1534 }
1535 }
1536}
1537
1538impl RemapFileNameExt for rustc_span::RealFileName {
1539 type Output<'a> = &'a Path;
1540
1541 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1542 assert!(
1543 scope.bits().count_ones() == 1,
1544 "one and only one scope should be passed to for_scope"
1545 );
1546 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1547 self.remapped_path_if_available()
1548 } else {
1549 self.local_path_if_available()
1550 }
1551 }
1552}