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 rustc_data_structures::flock;
10use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
11use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
12use rustc_data_structures::sync::{DynSend, DynSync, Lock, MappedReadGuard, ReadGuard, RwLock};
13use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;
14use rustc_errors::codes::*;
15use rustc_errors::emitter::{
16 DynEmitter, HumanEmitter, HumanReadableErrorType, OutputTheme, stderr_destination,
17};
18use rustc_errors::json::JsonEmitter;
19use rustc_errors::{
20 Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, FatalAbort,
21 FluentBundle, LazyFallbackBundle, TerminalUrl, fallback_fluent_bundle,
22};
23use rustc_macros::HashStable_Generic;
24pub use rustc_span::def_id::StableCrateId;
25use rustc_span::edition::Edition;
26use rustc_span::source_map::{FilePathMapping, SourceMap};
27use rustc_span::{FileNameDisplayPreference, RealFileName, Span, Symbol};
28use rustc_target::asm::InlineAsmArch;
29use rustc_target::spec::{
30 CodeModel, DebuginfoKind, PanicStrategy, RelocModel, RelroLevel, SanitizerSet,
31 SmallDataThresholdSupport, SplitDebuginfo, StackProtector, SymbolVisibility, Target,
32 TargetTuple, TlsModel,
33};
34
35use crate::code_stats::CodeStats;
36pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
37use crate::config::{
38 self, CoverageLevel, CrateType, DebugInfo, ErrorOutputType, FunctionReturn, Input,
39 InstrumentCoverage, OptLevel, OutFileName, OutputType, RemapPathScopeComponents,
40 SwitchWithOptPath,
41};
42use crate::filesearch::FileSearch;
43use crate::parse::{ParseSess, add_feature_diagnostics};
44use crate::search_paths::SearchPath;
45use crate::{errors, filesearch, lint};
46
47#[derive(Clone, Copy)]
49pub enum CtfeBacktrace {
50 Disabled,
52 Capture,
55 Immediate,
57}
58
59#[derive(Clone, Copy, Debug, HashStable_Generic)]
62pub struct Limit(pub usize);
63
64impl Limit {
65 pub fn new(value: usize) -> Self {
67 Limit(value)
68 }
69
70 #[inline]
73 pub fn value_within_limit(&self, value: usize) -> bool {
74 value <= self.0
75 }
76}
77
78impl From<usize> for Limit {
79 fn from(value: usize) -> Self {
80 Self::new(value)
81 }
82}
83
84impl fmt::Display for Limit {
85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 self.0.fmt(f)
87 }
88}
89
90impl Div<usize> for Limit {
91 type Output = Limit;
92
93 fn div(self, rhs: usize) -> Self::Output {
94 Limit::new(self.0 / rhs)
95 }
96}
97
98impl Mul<usize> for Limit {
99 type Output = Limit;
100
101 fn mul(self, rhs: usize) -> Self::Output {
102 Limit::new(self.0 * rhs)
103 }
104}
105
106impl rustc_errors::IntoDiagArg for Limit {
107 fn into_diag_arg(self) -> rustc_errors::DiagArgValue {
108 self.to_string().into_diag_arg()
109 }
110}
111
112#[derive(Clone, Copy, Debug, HashStable_Generic)]
113pub struct Limits {
114 pub recursion_limit: Limit,
117 pub move_size_limit: Limit,
120 pub type_length_limit: Limit,
122}
123
124pub struct CompilerIO {
125 pub input: Input,
126 pub output_dir: Option<PathBuf>,
127 pub output_file: Option<OutFileName>,
128 pub temps_dir: Option<PathBuf>,
129}
130
131pub trait LintStoreMarker: Any + DynSync + DynSend {}
132
133pub struct Session {
136 pub target: Target,
137 pub host: Target,
138 pub opts: config::Options,
139 pub host_tlib_path: Arc<SearchPath>,
140 pub target_tlib_path: Arc<SearchPath>,
141 pub psess: ParseSess,
142 pub sysroot: PathBuf,
143 pub io: CompilerIO,
145
146 incr_comp_session: RwLock<IncrCompSession>,
147
148 pub prof: SelfProfilerRef,
150
151 pub code_stats: CodeStats,
153
154 pub lint_store: Option<Arc<dyn LintStoreMarker>>,
156
157 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
159
160 pub ctfe_backtrace: Lock<CtfeBacktrace>,
167
168 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
173
174 pub asm_arch: Option<InlineAsmArch>,
176
177 pub target_features: FxIndexSet<Symbol>,
179
180 pub unstable_target_features: FxIndexSet<Symbol>,
182
183 pub cfg_version: &'static str,
185
186 pub using_internal_features: &'static AtomicBool,
191
192 pub expanded_args: Vec<String>,
197
198 target_filesearch: FileSearch,
199 host_filesearch: FileSearch,
200}
201
202#[derive(PartialEq, Eq, PartialOrd, Ord)]
203pub enum MetadataKind {
204 None,
205 Uncompressed,
206 Compressed,
207}
208
209#[derive(Clone, Copy)]
210pub enum CodegenUnits {
211 User(usize),
214
215 Default(usize),
219}
220
221impl CodegenUnits {
222 pub fn as_usize(self) -> usize {
223 match self {
224 CodegenUnits::User(n) => n,
225 CodegenUnits::Default(n) => n,
226 }
227 }
228}
229
230impl Session {
231 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
232 self.miri_unleashed_features.lock().push((span, feature_gate));
233 }
234
235 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
236 Some(self.source_map().path_mapping().to_real_filename(self.io.input.opt_path()?))
237 }
238
239 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
240 let mut guar = None;
241 let unleashed_features = self.miri_unleashed_features.lock();
242 if !unleashed_features.is_empty() {
243 let mut must_err = false;
244 self.dcx().emit_warn(errors::SkippingConstChecks {
246 unleashed_features: unleashed_features
247 .iter()
248 .map(|(span, gate)| {
249 gate.map(|gate| {
250 must_err = true;
251 errors::UnleashedFeatureHelp::Named { span: *span, gate }
252 })
253 .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })
254 })
255 .collect(),
256 });
257
258 if must_err && self.dcx().has_errors().is_none() {
260 guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));
262 }
263 }
264 guar
265 }
266
267 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
269 let mut guar = None;
270 guar = guar.or(self.check_miri_unleashed_features());
271 guar = guar.or(self.dcx().emit_stashed_diagnostics());
272 self.dcx().print_error_count();
273 if self.opts.json_future_incompat {
274 self.dcx().emit_future_breakage_report();
275 }
276 guar
277 }
278
279 pub fn is_test_crate(&self) -> bool {
281 self.opts.test
282 }
283
284 #[track_caller]
286 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
287 let mut err = self.dcx().create_err(err);
288 if err.code.is_none() {
289 #[allow(rustc::diagnostic_outside_of_impl)]
290 err.code(E0658);
291 }
292 add_feature_diagnostics(&mut err, self, feature);
293 err
294 }
295
296 pub fn record_trimmed_def_paths(&self) {
299 if self.opts.unstable_opts.print_type_sizes
300 || self.opts.unstable_opts.query_dep_graph
301 || self.opts.unstable_opts.dump_mir.is_some()
302 || self.opts.unstable_opts.unpretty.is_some()
303 || self.opts.output_types.contains_key(&OutputType::Mir)
304 || std::env::var_os("RUSTC_LOG").is_some()
305 {
306 return;
307 }
308
309 self.dcx().set_must_produce_diag()
310 }
311
312 #[inline]
313 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
314 self.psess.dcx()
315 }
316
317 #[inline]
318 pub fn source_map(&self) -> &SourceMap {
319 self.psess.source_map()
320 }
321
322 pub fn enable_internal_lints(&self) -> bool {
326 self.unstable_options() && !self.opts.actually_rustdoc
327 }
328
329 pub fn instrument_coverage(&self) -> bool {
330 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
331 }
332
333 pub fn instrument_coverage_branch(&self) -> bool {
334 self.instrument_coverage()
335 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
336 }
337
338 pub fn instrument_coverage_condition(&self) -> bool {
339 self.instrument_coverage()
340 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
341 }
342
343 pub fn instrument_coverage_mcdc(&self) -> bool {
344 self.instrument_coverage()
345 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Mcdc
346 }
347
348 pub fn coverage_no_mir_spans(&self) -> bool {
350 self.opts.unstable_opts.coverage_options.no_mir_spans
351 }
352
353 pub fn coverage_discard_all_spans_in_codegen(&self) -> bool {
355 self.opts.unstable_opts.coverage_options.discard_all_spans_in_codegen
356 }
357
358 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
359 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::CFI)
360 }
361
362 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
363 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
364 }
365
366 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
367 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
368 }
369
370 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
371 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
372 }
373
374 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
375 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
376 }
377
378 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
379 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::KCFI)
380 }
381
382 pub fn is_split_lto_unit_enabled(&self) -> bool {
383 self.opts.unstable_opts.split_lto_unit == Some(true)
384 }
385
386 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
388 if !self.target.crt_static_respected {
389 return self.target.crt_static_default;
391 }
392
393 let requested_features = self.opts.cg.target_feature.split(',');
394 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
395 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
396
397 #[allow(rustc::bad_opt_access)]
399 if found_positive || found_negative {
400 found_positive
401 } else if crate_type == Some(CrateType::ProcMacro)
402 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
403 {
404 false
408 } else {
409 self.target.crt_static_default
410 }
411 }
412
413 pub fn is_wasi_reactor(&self) -> bool {
414 self.target.options.os == "wasi"
415 && matches!(
416 self.opts.unstable_opts.wasi_exec_model,
417 Some(config::WasiExecModel::Reactor)
418 )
419 }
420
421 pub fn target_can_use_split_dwarf(&self) -> bool {
423 self.target.debuginfo_kind == DebuginfoKind::Dwarf
424 }
425
426 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
427 format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.as_u64())
428 }
429
430 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
431 &self.target_filesearch
432 }
433 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
434 &self.host_filesearch
435 }
436
437 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
441 let bin_path = filesearch::make_target_bin_path(&self.sysroot, config::host_tuple());
442 let fallback_sysroot_paths = filesearch::sysroot_candidates()
443 .into_iter()
444 .filter(|sysroot| *sysroot != self.sysroot)
446 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
447 let search_paths = std::iter::once(bin_path).chain(fallback_sysroot_paths);
448
449 if self_contained {
450 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
454 } else {
455 search_paths.collect()
456 }
457 }
458
459 pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
460 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
461
462 if let IncrCompSession::NotInitialized = *incr_comp_session {
463 } else {
464 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
465 }
466
467 *incr_comp_session =
468 IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
469 }
470
471 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
472 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
473
474 if let IncrCompSession::Active { .. } = *incr_comp_session {
475 } else {
476 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
477 }
478
479 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
481 }
482
483 pub fn mark_incr_comp_session_as_invalid(&self) {
484 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
485
486 let session_directory = match *incr_comp_session {
487 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
488 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
489 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
490 };
491
492 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
494 }
495
496 pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
497 let incr_comp_session = self.incr_comp_session.borrow();
498 ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
499 IncrCompSession::NotInitialized => panic!(
500 "trying to get session directory from `IncrCompSession`: {:?}",
501 *incr_comp_session,
502 ),
503 IncrCompSession::Active { ref session_directory, .. }
504 | IncrCompSession::Finalized { ref session_directory }
505 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
506 session_directory
507 }
508 })
509 }
510
511 pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
512 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
513 }
514
515 pub fn is_rust_2015(&self) -> bool {
517 self.edition().is_rust_2015()
518 }
519
520 pub fn at_least_rust_2018(&self) -> bool {
522 self.edition().at_least_rust_2018()
523 }
524
525 pub fn at_least_rust_2021(&self) -> bool {
527 self.edition().at_least_rust_2021()
528 }
529
530 pub fn at_least_rust_2024(&self) -> bool {
532 self.edition().at_least_rust_2024()
533 }
534
535 pub fn needs_plt(&self) -> bool {
537 let want_plt = self.target.plt_by_default;
540
541 let dbg_opts = &self.opts.unstable_opts;
542
543 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
544
545 let full_relro = RelroLevel::Full == relro_level;
549
550 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
553 }
554
555 pub fn emit_lifetime_markers(&self) -> bool {
557 self.opts.optimize != config::OptLevel::No
558 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
562 }
563
564 pub fn diagnostic_width(&self) -> usize {
565 let default_column_width = 140;
566 if let Some(width) = self.opts.diagnostic_width {
567 width
568 } else if self.opts.unstable_opts.ui_testing {
569 default_column_width
570 } else {
571 termize::dimensions().map_or(default_column_width, |(w, _)| w)
572 }
573 }
574
575 pub fn default_visibility(&self) -> SymbolVisibility {
577 self.opts
578 .unstable_opts
579 .default_visibility
580 .or(self.target.options.default_visibility)
581 .unwrap_or(SymbolVisibility::Interposable)
582 }
583}
584
585#[allow(rustc::bad_opt_access)]
587impl Session {
588 pub fn verbose_internals(&self) -> bool {
589 self.opts.unstable_opts.verbose_internals
590 }
591
592 pub fn print_llvm_stats(&self) -> bool {
593 self.opts.unstable_opts.print_codegen_stats
594 }
595
596 pub fn verify_llvm_ir(&self) -> bool {
597 self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
598 }
599
600 pub fn binary_dep_depinfo(&self) -> bool {
601 self.opts.unstable_opts.binary_dep_depinfo
602 }
603
604 pub fn mir_opt_level(&self) -> usize {
605 self.opts
606 .unstable_opts
607 .mir_opt_level
608 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
609 }
610
611 pub fn lto(&self) -> config::Lto {
613 if self.target.requires_lto {
615 return config::Lto::Fat;
616 }
617
618 match self.opts.cg.lto {
622 config::LtoCli::Unspecified => {
623 }
626 config::LtoCli::No => {
627 return config::Lto::No;
629 }
630 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
631 return config::Lto::Fat;
633 }
634 config::LtoCli::Thin => {
635 return config::Lto::Thin;
637 }
638 }
639
640 if self.opts.cli_forced_local_thinlto_off {
649 return config::Lto::No;
650 }
651
652 if let Some(enabled) = self.opts.unstable_opts.thinlto {
655 if enabled {
656 return config::Lto::ThinLocal;
657 } else {
658 return config::Lto::No;
659 }
660 }
661
662 if self.codegen_units().as_usize() == 1 {
665 return config::Lto::No;
666 }
667
668 match self.opts.optimize {
671 config::OptLevel::No => config::Lto::No,
672 _ => config::Lto::ThinLocal,
673 }
674 }
675
676 pub fn panic_strategy(&self) -> PanicStrategy {
679 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
680 }
681
682 pub fn fewer_names(&self) -> bool {
683 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
684 fewer_names
685 } else {
686 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
687 || self.opts.output_types.contains_key(&OutputType::Bitcode)
688 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
690 !more_names
691 }
692 }
693
694 pub fn unstable_options(&self) -> bool {
695 self.opts.unstable_opts.unstable_options
696 }
697
698 pub fn is_nightly_build(&self) -> bool {
699 self.opts.unstable_features.is_nightly_build()
700 }
701
702 pub fn overflow_checks(&self) -> bool {
703 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
704 }
705
706 pub fn ub_checks(&self) -> bool {
707 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
708 }
709
710 pub fn contract_checks(&self) -> bool {
711 self.opts.unstable_opts.contract_checks.unwrap_or(false)
712 }
713
714 pub fn relocation_model(&self) -> RelocModel {
715 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
716 }
717
718 pub fn code_model(&self) -> Option<CodeModel> {
719 self.opts.cg.code_model.or(self.target.code_model)
720 }
721
722 pub fn tls_model(&self) -> TlsModel {
723 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
724 }
725
726 pub fn direct_access_external_data(&self) -> Option<bool> {
727 self.opts
728 .unstable_opts
729 .direct_access_external_data
730 .or(self.target.direct_access_external_data)
731 }
732
733 pub fn split_debuginfo(&self) -> SplitDebuginfo {
734 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
735 }
736
737 pub fn dwarf_version(&self) -> u32 {
739 self.opts.unstable_opts.dwarf_version.unwrap_or(self.target.default_dwarf_version)
740 }
741
742 pub fn stack_protector(&self) -> StackProtector {
743 if self.target.options.supports_stack_protector {
744 self.opts.unstable_opts.stack_protector
745 } else {
746 StackProtector::None
747 }
748 }
749
750 pub fn must_emit_unwind_tables(&self) -> bool {
751 self.target.requires_uwtable
772 || self.opts.cg.force_unwind_tables.unwrap_or(
773 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
774 )
775 }
776
777 #[inline]
780 pub fn threads(&self) -> usize {
781 self.opts.unstable_opts.threads
782 }
783
784 pub fn codegen_units(&self) -> CodegenUnits {
787 if let Some(n) = self.opts.cli_forced_codegen_units {
788 return CodegenUnits::User(n);
789 }
790 if let Some(n) = self.target.default_codegen_units {
791 return CodegenUnits::Default(n as usize);
792 }
793
794 if self.opts.incremental.is_some() {
798 return CodegenUnits::Default(256);
799 }
800
801 CodegenUnits::Default(16)
852 }
853
854 pub fn teach(&self, code: ErrCode) -> bool {
855 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
856 }
857
858 pub fn edition(&self) -> Edition {
859 self.opts.edition
860 }
861
862 pub fn link_dead_code(&self) -> bool {
863 self.opts.cg.link_dead_code.unwrap_or(false)
864 }
865
866 pub fn filename_display_preference(
867 &self,
868 scope: RemapPathScopeComponents,
869 ) -> FileNameDisplayPreference {
870 assert!(
871 scope.bits().count_ones() == 1,
872 "one and only one scope should be passed to `Session::filename_display_preference`"
873 );
874 if self.opts.unstable_opts.remap_path_scope.contains(scope) {
875 FileNameDisplayPreference::Remapped
876 } else {
877 FileNameDisplayPreference::Local
878 }
879 }
880}
881
882#[allow(rustc::bad_opt_access)]
884fn default_emitter(
885 sopts: &config::Options,
886 source_map: Arc<SourceMap>,
887 bundle: Option<Arc<FluentBundle>>,
888 fallback_bundle: LazyFallbackBundle,
889) -> Box<DynEmitter> {
890 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
891 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
892 let terminal_url = match sopts.unstable_opts.terminal_urls {
893 TerminalUrl::Auto => {
894 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
895 (Ok("truecolor"), Ok("xterm-256color"))
896 if sopts.unstable_features.is_nightly_build() =>
897 {
898 TerminalUrl::Yes
899 }
900 _ => TerminalUrl::No,
901 }
902 }
903 t => t,
904 };
905
906 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
907
908 match sopts.error_format {
909 config::ErrorOutputType::HumanReadable(kind, color_config) => {
910 let short = kind.short();
911
912 if let HumanReadableErrorType::AnnotateSnippet = kind {
913 let emitter = AnnotateSnippetEmitter::new(
914 source_map,
915 bundle,
916 fallback_bundle,
917 short,
918 macro_backtrace,
919 );
920 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
921 } else {
922 let emitter = HumanEmitter::new(stderr_destination(color_config), fallback_bundle)
923 .fluent_bundle(bundle)
924 .sm(source_map)
925 .short_message(short)
926 .teach(sopts.unstable_opts.teach)
927 .diagnostic_width(sopts.diagnostic_width)
928 .macro_backtrace(macro_backtrace)
929 .track_diagnostics(track_diagnostics)
930 .terminal_url(terminal_url)
931 .theme(if let HumanReadableErrorType::Unicode = kind {
932 OutputTheme::Unicode
933 } else {
934 OutputTheme::Ascii
935 })
936 .ignored_directories_in_source_blocks(
937 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
938 );
939 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
940 }
941 }
942 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
943 JsonEmitter::new(
944 Box::new(io::BufWriter::new(io::stderr())),
945 source_map,
946 fallback_bundle,
947 pretty,
948 json_rendered,
949 color_config,
950 )
951 .fluent_bundle(bundle)
952 .ui_testing(sopts.unstable_opts.ui_testing)
953 .ignored_directories_in_source_blocks(
954 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
955 )
956 .diagnostic_width(sopts.diagnostic_width)
957 .macro_backtrace(macro_backtrace)
958 .track_diagnostics(track_diagnostics)
959 .terminal_url(terminal_url),
960 ),
961 }
962}
963
964#[allow(rustc::bad_opt_access)]
966#[allow(rustc::untranslatable_diagnostic)] pub fn build_session(
968 sopts: config::Options,
969 io: CompilerIO,
970 bundle: Option<Arc<rustc_errors::FluentBundle>>,
971 registry: rustc_errors::registry::Registry,
972 fluent_resources: Vec<&'static str>,
973 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
974 target: Target,
975 sysroot: PathBuf,
976 cfg_version: &'static str,
977 ice_file: Option<PathBuf>,
978 using_internal_features: &'static AtomicBool,
979 expanded_args: Vec<String>,
980) -> Session {
981 let warnings_allow = sopts
985 .lint_opts
986 .iter()
987 .rfind(|&(key, _)| *key == "warnings")
988 .is_some_and(|&(_, level)| level == lint::Allow);
989 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
990 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
991
992 let fallback_bundle = fallback_fluent_bundle(
993 fluent_resources,
994 sopts.unstable_opts.translate_directionality_markers,
995 );
996 let source_map = rustc_span::source_map::get_source_map().unwrap();
997 let emitter = default_emitter(&sopts, Arc::clone(&source_map), bundle, fallback_bundle);
998
999 let mut dcx = DiagCtxt::new(emitter)
1000 .with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings))
1001 .with_registry(registry);
1002 if let Some(ice_file) = ice_file {
1003 dcx = dcx.with_ice_file(ice_file);
1004 }
1005
1006 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1007 let (host, target_warnings) = Target::search(&host_triple, &sysroot)
1008 .unwrap_or_else(|e| dcx.handle().fatal(format!("Error loading host specification: {e}")));
1009 for warning in target_warnings.warning_messages() {
1010 dcx.handle().warn(warning)
1011 }
1012
1013 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1014 {
1015 let directory =
1016 if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1017
1018 let profiler = SelfProfiler::new(
1019 directory,
1020 sopts.crate_name.as_deref(),
1021 sopts.unstable_opts.self_profile_events.as_deref(),
1022 &sopts.unstable_opts.self_profile_counter,
1023 );
1024 match profiler {
1025 Ok(profiler) => Some(Arc::new(profiler)),
1026 Err(e) => {
1027 dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1028 None
1029 }
1030 }
1031 } else {
1032 None
1033 };
1034
1035 let mut psess = ParseSess::with_dcx(dcx, source_map);
1036 psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1037
1038 let host_triple = config::host_tuple();
1039 let target_triple = sopts.target_triple.tuple();
1040 let host_tlib_path = Arc::new(SearchPath::from_sysroot_and_triple(&sysroot, host_triple));
1041 let target_tlib_path = if host_triple == target_triple {
1042 Arc::clone(&host_tlib_path)
1045 } else {
1046 Arc::new(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1047 };
1048
1049 let prof = SelfProfilerRef::new(
1050 self_profiler,
1051 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1052 );
1053
1054 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1055 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1056 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1057 _ => CtfeBacktrace::Disabled,
1058 });
1059
1060 let asm_arch = if target.allow_asm { InlineAsmArch::from_str(&target.arch).ok() } else { None };
1061 let target_filesearch =
1062 filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1063 let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1064 let sess = Session {
1065 target,
1066 host,
1067 opts: sopts,
1068 host_tlib_path,
1069 target_tlib_path,
1070 psess,
1071 sysroot,
1072 io,
1073 incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1074 prof,
1075 code_stats: Default::default(),
1076 lint_store: None,
1077 driver_lint_caps,
1078 ctfe_backtrace,
1079 miri_unleashed_features: Lock::new(Default::default()),
1080 asm_arch,
1081 target_features: Default::default(),
1082 unstable_target_features: Default::default(),
1083 cfg_version,
1084 using_internal_features,
1085 expanded_args,
1086 target_filesearch,
1087 host_filesearch,
1088 };
1089
1090 validate_commandline_args_with_session_available(&sess);
1091
1092 sess
1093}
1094
1095#[allow(rustc::bad_opt_access)]
1101fn validate_commandline_args_with_session_available(sess: &Session) {
1102 if sess.opts.cg.linker_plugin_lto.enabled()
1110 && sess.opts.cg.prefer_dynamic
1111 && sess.target.is_like_windows
1112 {
1113 sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1114 }
1115
1116 if let Some(ref path) = sess.opts.cg.profile_use {
1119 if !path.exists() {
1120 sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1121 }
1122 }
1123
1124 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1126 if !path.exists() {
1127 sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1128 }
1129 }
1130
1131 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1133 if sess.target.requires_uwtable && !include_uwtables {
1134 sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1135 }
1136 }
1137
1138 let supported_sanitizers = sess.target.options.supported_sanitizers;
1140 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1141 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == "aarch64" {
1144 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1145 }
1146 match unsupported_sanitizers.into_iter().count() {
1147 0 => {}
1148 1 => {
1149 sess.dcx()
1150 .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1151 }
1152 _ => {
1153 sess.dcx().emit_err(errors::SanitizersNotSupported {
1154 us: unsupported_sanitizers.to_string(),
1155 });
1156 }
1157 }
1158
1159 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1161 sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1162 first: first.to_string(),
1163 second: second.to_string(),
1164 });
1165 }
1166
1167 if sess.crt_static(None)
1169 && !sess.opts.unstable_opts.sanitizer.is_empty()
1170 && !sess.target.is_like_msvc
1171 {
1172 sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1173 }
1174
1175 if sess.is_sanitizer_cfi_enabled()
1177 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1178 {
1179 sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1180 }
1181
1182 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy() != PanicStrategy::Abort {
1184 sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1185 }
1186
1187 if sess.is_sanitizer_cfi_enabled()
1189 && sess.lto() == config::Lto::Fat
1190 && (sess.codegen_units().as_usize() != 1)
1191 {
1192 sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1193 }
1194
1195 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1197 if !sess.is_sanitizer_cfi_enabled() {
1198 sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1199 }
1200 }
1201
1202 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1204 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1205 sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1206 }
1207 }
1208
1209 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1211 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1212 sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1213 }
1214 }
1215
1216 if sess.is_split_lto_unit_enabled()
1218 && !(sess.lto() == config::Lto::Fat
1219 || sess.lto() == config::Lto::Thin
1220 || sess.opts.cg.linker_plugin_lto.enabled())
1221 {
1222 sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1223 }
1224
1225 if sess.lto() != config::Lto::Fat {
1227 if sess.opts.unstable_opts.virtual_function_elimination {
1228 sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1229 }
1230 }
1231
1232 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1233 if !sess.target.options.supports_stack_protector {
1234 sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1235 stack_protector: sess.opts.unstable_opts.stack_protector,
1236 target_triple: &sess.opts.target_triple,
1237 });
1238 }
1239 }
1240
1241 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1242 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1243 sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1244 target_triple: &sess.opts.target_triple,
1245 })
1246 }
1247 }
1248
1249 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != "aarch64" {
1250 sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1251 }
1252
1253 if let Some(dwarf_version) = sess.opts.unstable_opts.dwarf_version {
1254 if dwarf_version < 2 || dwarf_version > 5 {
1256 sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1257 }
1258 }
1259
1260 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1261 && !sess.opts.unstable_opts.unstable_options
1262 {
1263 sess.dcx()
1264 .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1265 }
1266
1267 if sess.opts.unstable_opts.embed_source {
1268 let dwarf_version = sess.dwarf_version();
1269
1270 if dwarf_version < 5 {
1271 sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1272 }
1273
1274 if sess.opts.debuginfo == DebugInfo::None {
1275 sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1276 }
1277 }
1278
1279 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1280 sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1281 }
1282
1283 if let Some(flavor) = sess.opts.cg.linker_flavor {
1284 if let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor) {
1285 let flavor = flavor.desc();
1286 sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1287 }
1288 }
1289
1290 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1291 if sess.target.arch != "x86" && sess.target.arch != "x86_64" {
1292 sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1293 }
1294 }
1295
1296 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1297 if regparm > 3 {
1298 sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1299 }
1300 if sess.target.arch != "x86" {
1301 sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1302 }
1303 }
1304 if sess.opts.unstable_opts.reg_struct_return {
1305 if sess.target.arch != "x86" {
1306 sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1307 }
1308 }
1309
1310 match sess.opts.unstable_opts.function_return {
1314 FunctionReturn::Keep => (),
1315 FunctionReturn::ThunkExtern => {
1316 if let Some(code_model) = sess.code_model()
1319 && code_model == CodeModel::Large
1320 {
1321 sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1322 }
1323 }
1324 }
1325
1326 if sess.opts.cg.soft_float {
1327 if sess.target.arch == "arm" {
1328 sess.dcx().emit_warn(errors::SoftFloatDeprecated);
1329 } else {
1330 sess.dcx().emit_warn(errors::SoftFloatIgnored);
1333 }
1334 }
1335}
1336
1337#[derive(Debug)]
1339enum IncrCompSession {
1340 NotInitialized,
1343 Active { session_directory: PathBuf, _lock_file: flock::Lock },
1348 Finalized { session_directory: PathBuf },
1351 InvalidBecauseOfErrors { session_directory: PathBuf },
1355}
1356
1357pub struct EarlyDiagCtxt {
1359 dcx: DiagCtxt,
1360}
1361
1362impl EarlyDiagCtxt {
1363 pub fn new(output: ErrorOutputType) -> Self {
1364 let emitter = mk_emitter(output);
1365 Self { dcx: DiagCtxt::new(emitter) }
1366 }
1367
1368 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1371 assert!(self.dcx.handle().has_errors().is_none());
1372
1373 let emitter = mk_emitter(output);
1374 self.dcx = DiagCtxt::new(emitter);
1375 }
1376
1377 #[allow(rustc::untranslatable_diagnostic)]
1378 #[allow(rustc::diagnostic_outside_of_impl)]
1379 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1380 self.dcx.handle().note(msg)
1381 }
1382
1383 #[allow(rustc::untranslatable_diagnostic)]
1384 #[allow(rustc::diagnostic_outside_of_impl)]
1385 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1386 self.dcx.handle().struct_help(msg).emit()
1387 }
1388
1389 #[allow(rustc::untranslatable_diagnostic)]
1390 #[allow(rustc::diagnostic_outside_of_impl)]
1391 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1392 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1393 self.dcx.handle().err(msg)
1394 }
1395
1396 #[allow(rustc::untranslatable_diagnostic)]
1397 #[allow(rustc::diagnostic_outside_of_impl)]
1398 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1399 self.dcx.handle().fatal(msg)
1400 }
1401
1402 #[allow(rustc::untranslatable_diagnostic)]
1403 #[allow(rustc::diagnostic_outside_of_impl)]
1404 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1405 self.dcx.handle().struct_fatal(msg)
1406 }
1407
1408 #[allow(rustc::untranslatable_diagnostic)]
1409 #[allow(rustc::diagnostic_outside_of_impl)]
1410 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1411 self.dcx.handle().warn(msg)
1412 }
1413
1414 #[allow(rustc::untranslatable_diagnostic)]
1415 #[allow(rustc::diagnostic_outside_of_impl)]
1416 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1417 self.dcx.handle().struct_warn(msg)
1418 }
1419}
1420
1421fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1422 let fallback_bundle =
1425 fallback_fluent_bundle(vec![rustc_errors::DEFAULT_LOCALE_RESOURCE], false);
1426 let emitter: Box<DynEmitter> = match output {
1427 config::ErrorOutputType::HumanReadable(kind, color_config) => {
1428 let short = kind.short();
1429 Box::new(
1430 HumanEmitter::new(stderr_destination(color_config), fallback_bundle)
1431 .theme(if let HumanReadableErrorType::Unicode = kind {
1432 OutputTheme::Unicode
1433 } else {
1434 OutputTheme::Ascii
1435 })
1436 .short_message(short),
1437 )
1438 }
1439 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1440 Box::new(JsonEmitter::new(
1441 Box::new(io::BufWriter::new(io::stderr())),
1442 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1443 fallback_bundle,
1444 pretty,
1445 json_rendered,
1446 color_config,
1447 ))
1448 }
1449 };
1450 emitter
1451}
1452
1453pub trait RemapFileNameExt {
1454 type Output<'a>
1455 where
1456 Self: 'a;
1457
1458 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_>;
1462}
1463
1464impl RemapFileNameExt for rustc_span::FileName {
1465 type Output<'a> = rustc_span::FileNameDisplay<'a>;
1466
1467 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1468 assert!(
1469 scope.bits().count_ones() == 1,
1470 "one and only one scope should be passed to for_scope"
1471 );
1472 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1473 self.prefer_remapped_unconditionaly()
1474 } else {
1475 self.prefer_local()
1476 }
1477 }
1478}
1479
1480impl RemapFileNameExt for rustc_span::RealFileName {
1481 type Output<'a> = &'a Path;
1482
1483 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1484 assert!(
1485 scope.bits().count_ones() == 1,
1486 "one and only one scope should be passed to for_scope"
1487 );
1488 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1489 self.remapped_path_if_available()
1490 } else {
1491 self.local_path_if_available()
1492 }
1493 }
1494}