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 pub fn unlimited() -> Self {
72 Limit(usize::MAX)
73 }
74
75 #[inline]
78 pub fn value_within_limit(&self, value: usize) -> bool {
79 value <= self.0
80 }
81}
82
83impl From<usize> for Limit {
84 fn from(value: usize) -> Self {
85 Self::new(value)
86 }
87}
88
89impl fmt::Display for Limit {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 self.0.fmt(f)
92 }
93}
94
95impl Div<usize> for Limit {
96 type Output = Limit;
97
98 fn div(self, rhs: usize) -> Self::Output {
99 Limit::new(self.0 / rhs)
100 }
101}
102
103impl Mul<usize> for Limit {
104 type Output = Limit;
105
106 fn mul(self, rhs: usize) -> Self::Output {
107 Limit::new(self.0 * rhs)
108 }
109}
110
111impl rustc_errors::IntoDiagArg for Limit {
112 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
113 self.to_string().into_diag_arg(&mut None)
114 }
115}
116
117#[derive(Clone, Copy, Debug, HashStable_Generic)]
118pub struct Limits {
119 pub recursion_limit: Limit,
122 pub move_size_limit: Limit,
125 pub type_length_limit: Limit,
127 pub pattern_complexity_limit: Limit,
129}
130
131pub struct CompilerIO {
132 pub input: Input,
133 pub output_dir: Option<PathBuf>,
134 pub output_file: Option<OutFileName>,
135 pub temps_dir: Option<PathBuf>,
136}
137
138pub trait LintStoreMarker: Any + DynSync + DynSend {}
139
140pub struct Session {
143 pub target: Target,
144 pub host: Target,
145 pub opts: config::Options,
146 pub target_tlib_path: Arc<SearchPath>,
147 pub psess: ParseSess,
148 pub sysroot: PathBuf,
149 pub io: CompilerIO,
151
152 incr_comp_session: RwLock<IncrCompSession>,
153
154 pub prof: SelfProfilerRef,
156
157 pub code_stats: CodeStats,
159
160 pub lint_store: Option<Arc<dyn LintStoreMarker>>,
162
163 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
165
166 pub ctfe_backtrace: Lock<CtfeBacktrace>,
173
174 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
179
180 pub asm_arch: Option<InlineAsmArch>,
182
183 pub target_features: FxIndexSet<Symbol>,
185
186 pub unstable_target_features: FxIndexSet<Symbol>,
188
189 pub cfg_version: &'static str,
191
192 pub using_internal_features: &'static AtomicBool,
197
198 pub expanded_args: Vec<String>,
203
204 target_filesearch: FileSearch,
205 host_filesearch: FileSearch,
206}
207
208#[derive(PartialEq, Eq, PartialOrd, Ord)]
209pub enum MetadataKind {
210 None,
211 Uncompressed,
212 Compressed,
213}
214
215#[derive(Clone, Copy)]
216pub enum CodegenUnits {
217 User(usize),
220
221 Default(usize),
225}
226
227impl CodegenUnits {
228 pub fn as_usize(self) -> usize {
229 match self {
230 CodegenUnits::User(n) => n,
231 CodegenUnits::Default(n) => n,
232 }
233 }
234}
235
236impl Session {
237 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
238 self.miri_unleashed_features.lock().push((span, feature_gate));
239 }
240
241 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
242 Some(self.source_map().path_mapping().to_real_filename(self.io.input.opt_path()?))
243 }
244
245 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
246 let mut guar = None;
247 let unleashed_features = self.miri_unleashed_features.lock();
248 if !unleashed_features.is_empty() {
249 let mut must_err = false;
250 self.dcx().emit_warn(errors::SkippingConstChecks {
252 unleashed_features: unleashed_features
253 .iter()
254 .map(|(span, gate)| {
255 gate.map(|gate| {
256 must_err = true;
257 errors::UnleashedFeatureHelp::Named { span: *span, gate }
258 })
259 .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })
260 })
261 .collect(),
262 });
263
264 if must_err && self.dcx().has_errors().is_none() {
266 guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));
268 }
269 }
270 guar
271 }
272
273 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
275 let mut guar = None;
276 guar = guar.or(self.check_miri_unleashed_features());
277 guar = guar.or(self.dcx().emit_stashed_diagnostics());
278 self.dcx().print_error_count();
279 if self.opts.json_future_incompat {
280 self.dcx().emit_future_breakage_report();
281 }
282 guar
283 }
284
285 pub fn is_test_crate(&self) -> bool {
287 self.opts.test
288 }
289
290 #[track_caller]
292 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
293 let mut err = self.dcx().create_err(err);
294 if err.code.is_none() {
295 #[allow(rustc::diagnostic_outside_of_impl)]
296 err.code(E0658);
297 }
298 add_feature_diagnostics(&mut err, self, feature);
299 err
300 }
301
302 pub fn record_trimmed_def_paths(&self) {
305 if self.opts.unstable_opts.print_type_sizes
306 || self.opts.unstable_opts.query_dep_graph
307 || self.opts.unstable_opts.dump_mir.is_some()
308 || self.opts.unstable_opts.unpretty.is_some()
309 || self.opts.output_types.contains_key(&OutputType::Mir)
310 || std::env::var_os("RUSTC_LOG").is_some()
311 {
312 return;
313 }
314
315 self.dcx().set_must_produce_diag()
316 }
317
318 #[inline]
319 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
320 self.psess.dcx()
321 }
322
323 #[inline]
324 pub fn source_map(&self) -> &SourceMap {
325 self.psess.source_map()
326 }
327
328 pub fn enable_internal_lints(&self) -> bool {
332 self.unstable_options() && !self.opts.actually_rustdoc
333 }
334
335 pub fn instrument_coverage(&self) -> bool {
336 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
337 }
338
339 pub fn instrument_coverage_branch(&self) -> bool {
340 self.instrument_coverage()
341 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
342 }
343
344 pub fn instrument_coverage_condition(&self) -> bool {
345 self.instrument_coverage()
346 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
347 }
348
349 pub fn instrument_coverage_mcdc(&self) -> bool {
350 self.instrument_coverage()
351 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Mcdc
352 }
353
354 pub fn coverage_no_mir_spans(&self) -> bool {
356 self.opts.unstable_opts.coverage_options.no_mir_spans
357 }
358
359 pub fn coverage_discard_all_spans_in_codegen(&self) -> bool {
361 self.opts.unstable_opts.coverage_options.discard_all_spans_in_codegen
362 }
363
364 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
365 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::CFI)
366 }
367
368 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
369 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
370 }
371
372 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
373 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
374 }
375
376 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
377 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
378 }
379
380 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
381 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
382 }
383
384 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
385 self.opts.unstable_opts.sanitizer.contains(SanitizerSet::KCFI)
386 }
387
388 pub fn is_split_lto_unit_enabled(&self) -> bool {
389 self.opts.unstable_opts.split_lto_unit == Some(true)
390 }
391
392 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
394 if !self.target.crt_static_respected {
395 return self.target.crt_static_default;
397 }
398
399 let requested_features = self.opts.cg.target_feature.split(',');
400 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
401 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
402
403 #[allow(rustc::bad_opt_access)]
405 if found_positive || found_negative {
406 found_positive
407 } else if crate_type == Some(CrateType::ProcMacro)
408 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
409 {
410 false
414 } else {
415 self.target.crt_static_default
416 }
417 }
418
419 pub fn is_wasi_reactor(&self) -> bool {
420 self.target.options.os == "wasi"
421 && matches!(
422 self.opts.unstable_opts.wasi_exec_model,
423 Some(config::WasiExecModel::Reactor)
424 )
425 }
426
427 pub fn target_can_use_split_dwarf(&self) -> bool {
429 self.target.debuginfo_kind == DebuginfoKind::Dwarf
430 }
431
432 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
433 format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.as_u64())
434 }
435
436 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
437 &self.target_filesearch
438 }
439 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
440 &self.host_filesearch
441 }
442
443 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
447 let bin_path = filesearch::make_target_bin_path(&self.sysroot, config::host_tuple());
448 let fallback_sysroot_paths = filesearch::sysroot_candidates()
449 .into_iter()
450 .filter(|sysroot| *sysroot != self.sysroot)
452 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
453 let search_paths = std::iter::once(bin_path).chain(fallback_sysroot_paths);
454
455 if self_contained {
456 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
460 } else {
461 search_paths.collect()
462 }
463 }
464
465 pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
466 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
467
468 if let IncrCompSession::NotInitialized = *incr_comp_session {
469 } else {
470 panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
471 }
472
473 *incr_comp_session =
474 IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
475 }
476
477 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
478 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
479
480 if let IncrCompSession::Active { .. } = *incr_comp_session {
481 } else {
482 panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
483 }
484
485 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
487 }
488
489 pub fn mark_incr_comp_session_as_invalid(&self) {
490 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
491
492 let session_directory = match *incr_comp_session {
493 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
494 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
495 _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
496 };
497
498 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
500 }
501
502 pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
503 let incr_comp_session = self.incr_comp_session.borrow();
504 ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
505 IncrCompSession::NotInitialized => panic!(
506 "trying to get session directory from `IncrCompSession`: {:?}",
507 *incr_comp_session,
508 ),
509 IncrCompSession::Active { ref session_directory, .. }
510 | IncrCompSession::Finalized { ref session_directory }
511 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
512 session_directory
513 }
514 })
515 }
516
517 pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
518 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
519 }
520
521 pub fn is_rust_2015(&self) -> bool {
523 self.edition().is_rust_2015()
524 }
525
526 pub fn at_least_rust_2018(&self) -> bool {
528 self.edition().at_least_rust_2018()
529 }
530
531 pub fn at_least_rust_2021(&self) -> bool {
533 self.edition().at_least_rust_2021()
534 }
535
536 pub fn at_least_rust_2024(&self) -> bool {
538 self.edition().at_least_rust_2024()
539 }
540
541 pub fn needs_plt(&self) -> bool {
543 let want_plt = self.target.plt_by_default;
546
547 let dbg_opts = &self.opts.unstable_opts;
548
549 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
550
551 let full_relro = RelroLevel::Full == relro_level;
555
556 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
559 }
560
561 pub fn emit_lifetime_markers(&self) -> bool {
563 self.opts.optimize != config::OptLevel::No
564 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
568 }
569
570 pub fn diagnostic_width(&self) -> usize {
571 let default_column_width = 140;
572 if let Some(width) = self.opts.diagnostic_width {
573 width
574 } else if self.opts.unstable_opts.ui_testing {
575 default_column_width
576 } else {
577 termize::dimensions().map_or(default_column_width, |(w, _)| w)
578 }
579 }
580
581 pub fn default_visibility(&self) -> SymbolVisibility {
583 self.opts
584 .unstable_opts
585 .default_visibility
586 .or(self.target.options.default_visibility)
587 .unwrap_or(SymbolVisibility::Interposable)
588 }
589}
590
591#[allow(rustc::bad_opt_access)]
593impl Session {
594 pub fn verbose_internals(&self) -> bool {
595 self.opts.unstable_opts.verbose_internals
596 }
597
598 pub fn print_llvm_stats(&self) -> bool {
599 self.opts.unstable_opts.print_codegen_stats
600 }
601
602 pub fn verify_llvm_ir(&self) -> bool {
603 self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
604 }
605
606 pub fn binary_dep_depinfo(&self) -> bool {
607 self.opts.unstable_opts.binary_dep_depinfo
608 }
609
610 pub fn mir_opt_level(&self) -> usize {
611 self.opts
612 .unstable_opts
613 .mir_opt_level
614 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
615 }
616
617 pub fn lto(&self) -> config::Lto {
619 if self.target.requires_lto {
621 return config::Lto::Fat;
622 }
623
624 match self.opts.cg.lto {
628 config::LtoCli::Unspecified => {
629 }
632 config::LtoCli::No => {
633 return config::Lto::No;
635 }
636 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
637 return config::Lto::Fat;
639 }
640 config::LtoCli::Thin => {
641 return config::Lto::Thin;
643 }
644 }
645
646 if self.opts.cli_forced_local_thinlto_off {
655 return config::Lto::No;
656 }
657
658 if let Some(enabled) = self.opts.unstable_opts.thinlto {
661 if enabled {
662 return config::Lto::ThinLocal;
663 } else {
664 return config::Lto::No;
665 }
666 }
667
668 if self.codegen_units().as_usize() == 1 {
671 return config::Lto::No;
672 }
673
674 match self.opts.optimize {
677 config::OptLevel::No => config::Lto::No,
678 _ => config::Lto::ThinLocal,
679 }
680 }
681
682 pub fn panic_strategy(&self) -> PanicStrategy {
685 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
686 }
687
688 pub fn fewer_names(&self) -> bool {
689 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
690 fewer_names
691 } else {
692 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
693 || self.opts.output_types.contains_key(&OutputType::Bitcode)
694 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
696 !more_names
697 }
698 }
699
700 pub fn unstable_options(&self) -> bool {
701 self.opts.unstable_opts.unstable_options
702 }
703
704 pub fn is_nightly_build(&self) -> bool {
705 self.opts.unstable_features.is_nightly_build()
706 }
707
708 pub fn overflow_checks(&self) -> bool {
709 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
710 }
711
712 pub fn ub_checks(&self) -> bool {
713 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
714 }
715
716 pub fn contract_checks(&self) -> bool {
717 self.opts.unstable_opts.contract_checks.unwrap_or(false)
718 }
719
720 pub fn relocation_model(&self) -> RelocModel {
721 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
722 }
723
724 pub fn code_model(&self) -> Option<CodeModel> {
725 self.opts.cg.code_model.or(self.target.code_model)
726 }
727
728 pub fn tls_model(&self) -> TlsModel {
729 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
730 }
731
732 pub fn direct_access_external_data(&self) -> Option<bool> {
733 self.opts
734 .unstable_opts
735 .direct_access_external_data
736 .or(self.target.direct_access_external_data)
737 }
738
739 pub fn split_debuginfo(&self) -> SplitDebuginfo {
740 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
741 }
742
743 pub fn dwarf_version(&self) -> u32 {
745 self.opts.unstable_opts.dwarf_version.unwrap_or(self.target.default_dwarf_version)
746 }
747
748 pub fn stack_protector(&self) -> StackProtector {
749 if self.target.options.supports_stack_protector {
750 self.opts.unstable_opts.stack_protector
751 } else {
752 StackProtector::None
753 }
754 }
755
756 pub fn must_emit_unwind_tables(&self) -> bool {
757 self.target.requires_uwtable
778 || self.opts.cg.force_unwind_tables.unwrap_or(
779 self.panic_strategy() == PanicStrategy::Unwind || self.target.default_uwtable,
780 )
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
888#[allow(rustc::bad_opt_access)]
890fn default_emitter(
891 sopts: &config::Options,
892 source_map: Arc<SourceMap>,
893 bundle: Option<Arc<FluentBundle>>,
894 fallback_bundle: LazyFallbackBundle,
895) -> Box<DynEmitter> {
896 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
897 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
898 let terminal_url = match sopts.unstable_opts.terminal_urls {
899 TerminalUrl::Auto => {
900 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
901 (Ok("truecolor"), Ok("xterm-256color"))
902 if sopts.unstable_features.is_nightly_build() =>
903 {
904 TerminalUrl::Yes
905 }
906 _ => TerminalUrl::No,
907 }
908 }
909 t => t,
910 };
911
912 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
913
914 match sopts.error_format {
915 config::ErrorOutputType::HumanReadable { kind, color_config } => {
916 let short = kind.short();
917
918 if let HumanReadableErrorType::AnnotateSnippet = kind {
919 let emitter = AnnotateSnippetEmitter::new(
920 source_map,
921 bundle,
922 fallback_bundle,
923 short,
924 macro_backtrace,
925 );
926 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
927 } else {
928 let emitter = HumanEmitter::new(stderr_destination(color_config), fallback_bundle)
929 .fluent_bundle(bundle)
930 .sm(source_map)
931 .short_message(short)
932 .diagnostic_width(sopts.diagnostic_width)
933 .macro_backtrace(macro_backtrace)
934 .track_diagnostics(track_diagnostics)
935 .terminal_url(terminal_url)
936 .theme(if let HumanReadableErrorType::Unicode = kind {
937 OutputTheme::Unicode
938 } else {
939 OutputTheme::Ascii
940 })
941 .ignored_directories_in_source_blocks(
942 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
943 );
944 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
945 }
946 }
947 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
948 JsonEmitter::new(
949 Box::new(io::BufWriter::new(io::stderr())),
950 source_map,
951 fallback_bundle,
952 pretty,
953 json_rendered,
954 color_config,
955 )
956 .fluent_bundle(bundle)
957 .ui_testing(sopts.unstable_opts.ui_testing)
958 .ignored_directories_in_source_blocks(
959 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
960 )
961 .diagnostic_width(sopts.diagnostic_width)
962 .macro_backtrace(macro_backtrace)
963 .track_diagnostics(track_diagnostics)
964 .terminal_url(terminal_url),
965 ),
966 }
967}
968
969#[allow(rustc::bad_opt_access)]
971#[allow(rustc::untranslatable_diagnostic)] pub fn build_session(
973 sopts: config::Options,
974 io: CompilerIO,
975 bundle: Option<Arc<rustc_errors::FluentBundle>>,
976 registry: rustc_errors::registry::Registry,
977 fluent_resources: Vec<&'static str>,
978 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
979 target: Target,
980 sysroot: PathBuf,
981 cfg_version: &'static str,
982 ice_file: Option<PathBuf>,
983 using_internal_features: &'static AtomicBool,
984 expanded_args: Vec<String>,
985) -> Session {
986 let warnings_allow = sopts
990 .lint_opts
991 .iter()
992 .rfind(|&(key, _)| *key == "warnings")
993 .is_some_and(|&(_, level)| level == lint::Allow);
994 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
995 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
996
997 let fallback_bundle = fallback_fluent_bundle(
998 fluent_resources,
999 sopts.unstable_opts.translate_directionality_markers,
1000 );
1001 let source_map = rustc_span::source_map::get_source_map().unwrap();
1002 let emitter = default_emitter(&sopts, Arc::clone(&source_map), bundle, fallback_bundle);
1003
1004 let mut dcx = DiagCtxt::new(emitter)
1005 .with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings))
1006 .with_registry(registry);
1007 if let Some(ice_file) = ice_file {
1008 dcx = dcx.with_ice_file(ice_file);
1009 }
1010
1011 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1012 let (host, target_warnings) = Target::search(&host_triple, &sysroot)
1013 .unwrap_or_else(|e| dcx.handle().fatal(format!("Error loading host specification: {e}")));
1014 for warning in target_warnings.warning_messages() {
1015 dcx.handle().warn(warning)
1016 }
1017
1018 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1019 {
1020 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1021
1022 let profiler = SelfProfiler::new(
1023 directory,
1024 sopts.crate_name.as_deref(),
1025 sopts.unstable_opts.self_profile_events.as_deref(),
1026 &sopts.unstable_opts.self_profile_counter,
1027 );
1028 match profiler {
1029 Ok(profiler) => Some(Arc::new(profiler)),
1030 Err(e) => {
1031 dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1032 None
1033 }
1034 }
1035 } else {
1036 None
1037 };
1038
1039 let mut psess = ParseSess::with_dcx(dcx, source_map);
1040 psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1041
1042 let host_triple = config::host_tuple();
1043 let target_triple = sopts.target_triple.tuple();
1044 let host_tlib_path = Arc::new(SearchPath::from_sysroot_and_triple(&sysroot, host_triple));
1046 let target_tlib_path = if host_triple == target_triple {
1047 Arc::clone(&host_tlib_path)
1050 } else {
1051 Arc::new(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1052 };
1053
1054 let prof = SelfProfilerRef::new(
1055 self_profiler,
1056 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1057 );
1058
1059 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1060 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1061 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1062 _ => CtfeBacktrace::Disabled,
1063 });
1064
1065 let asm_arch = if target.allow_asm { InlineAsmArch::from_str(&target.arch).ok() } else { None };
1066 let target_filesearch =
1067 filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1068 let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1069 let sess = Session {
1070 target,
1071 host,
1072 opts: sopts,
1073 target_tlib_path,
1074 psess,
1075 sysroot,
1076 io,
1077 incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1078 prof,
1079 code_stats: Default::default(),
1080 lint_store: None,
1081 driver_lint_caps,
1082 ctfe_backtrace,
1083 miri_unleashed_features: Lock::new(Default::default()),
1084 asm_arch,
1085 target_features: Default::default(),
1086 unstable_target_features: Default::default(),
1087 cfg_version,
1088 using_internal_features,
1089 expanded_args,
1090 target_filesearch,
1091 host_filesearch,
1092 };
1093
1094 validate_commandline_args_with_session_available(&sess);
1095
1096 sess
1097}
1098
1099#[allow(rustc::bad_opt_access)]
1105fn validate_commandline_args_with_session_available(sess: &Session) {
1106 if sess.opts.cg.linker_plugin_lto.enabled()
1114 && sess.opts.cg.prefer_dynamic
1115 && sess.target.is_like_windows
1116 {
1117 sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1118 }
1119
1120 if let Some(ref path) = sess.opts.cg.profile_use {
1123 if !path.exists() {
1124 sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1125 }
1126 }
1127
1128 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1130 if !path.exists() {
1131 sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1132 }
1133 }
1134
1135 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1137 if sess.target.requires_uwtable && !include_uwtables {
1138 sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1139 }
1140 }
1141
1142 let supported_sanitizers = sess.target.options.supported_sanitizers;
1144 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1145 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == "aarch64" {
1148 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1149 }
1150 match unsupported_sanitizers.into_iter().count() {
1151 0 => {}
1152 1 => {
1153 sess.dcx()
1154 .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1155 }
1156 _ => {
1157 sess.dcx().emit_err(errors::SanitizersNotSupported {
1158 us: unsupported_sanitizers.to_string(),
1159 });
1160 }
1161 }
1162
1163 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1165 sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1166 first: first.to_string(),
1167 second: second.to_string(),
1168 });
1169 }
1170
1171 if sess.crt_static(None)
1173 && !sess.opts.unstable_opts.sanitizer.is_empty()
1174 && !sess.target.is_like_msvc
1175 {
1176 sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1177 }
1178
1179 if sess.is_sanitizer_cfi_enabled()
1181 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1182 {
1183 sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1184 }
1185
1186 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy() != PanicStrategy::Abort {
1188 sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1189 }
1190
1191 if sess.is_sanitizer_cfi_enabled()
1193 && sess.lto() == config::Lto::Fat
1194 && (sess.codegen_units().as_usize() != 1)
1195 {
1196 sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1197 }
1198
1199 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1201 if !sess.is_sanitizer_cfi_enabled() {
1202 sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1203 }
1204 }
1205
1206 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1208 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1209 sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1210 }
1211 }
1212
1213 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1215 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1216 sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1217 }
1218 }
1219
1220 if sess.is_split_lto_unit_enabled()
1222 && !(sess.lto() == config::Lto::Fat
1223 || sess.lto() == config::Lto::Thin
1224 || sess.opts.cg.linker_plugin_lto.enabled())
1225 {
1226 sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1227 }
1228
1229 if sess.lto() != config::Lto::Fat {
1231 if sess.opts.unstable_opts.virtual_function_elimination {
1232 sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1233 }
1234 }
1235
1236 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1237 if !sess.target.options.supports_stack_protector {
1238 sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1239 stack_protector: sess.opts.unstable_opts.stack_protector,
1240 target_triple: &sess.opts.target_triple,
1241 });
1242 }
1243 }
1244
1245 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1246 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1247 sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1248 target_triple: &sess.opts.target_triple,
1249 })
1250 }
1251 }
1252
1253 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != "aarch64" {
1254 sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1255 }
1256
1257 if let Some(dwarf_version) = sess.opts.unstable_opts.dwarf_version {
1258 if dwarf_version < 2 || dwarf_version > 5 {
1260 sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1261 }
1262 }
1263
1264 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1265 && !sess.opts.unstable_opts.unstable_options
1266 {
1267 sess.dcx()
1268 .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1269 }
1270
1271 if sess.opts.unstable_opts.embed_source {
1272 let dwarf_version = sess.dwarf_version();
1273
1274 if dwarf_version < 5 {
1275 sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1276 }
1277
1278 if sess.opts.debuginfo == DebugInfo::None {
1279 sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1280 }
1281 }
1282
1283 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1284 sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1285 }
1286
1287 if let Some(flavor) = sess.opts.cg.linker_flavor {
1288 if let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor) {
1289 let flavor = flavor.desc();
1290 sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1291 }
1292 }
1293
1294 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1295 if sess.target.arch != "x86" && sess.target.arch != "x86_64" {
1296 sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1297 }
1298 }
1299
1300 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1301 if regparm > 3 {
1302 sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1303 }
1304 if sess.target.arch != "x86" {
1305 sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1306 }
1307 }
1308 if sess.opts.unstable_opts.reg_struct_return {
1309 if sess.target.arch != "x86" {
1310 sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1311 }
1312 }
1313
1314 match sess.opts.unstable_opts.function_return {
1318 FunctionReturn::Keep => (),
1319 FunctionReturn::ThunkExtern => {
1320 if let Some(code_model) = sess.code_model()
1323 && code_model == CodeModel::Large
1324 {
1325 sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1326 }
1327 }
1328 }
1329
1330 if sess.opts.cg.soft_float {
1331 if sess.target.arch == "arm" {
1332 sess.dcx().emit_warn(errors::SoftFloatDeprecated);
1333 } else {
1334 sess.dcx().emit_warn(errors::SoftFloatIgnored);
1337 }
1338 }
1339}
1340
1341#[derive(Debug)]
1343enum IncrCompSession {
1344 NotInitialized,
1347 Active { session_directory: PathBuf, _lock_file: flock::Lock },
1352 Finalized { session_directory: PathBuf },
1355 InvalidBecauseOfErrors { session_directory: PathBuf },
1359}
1360
1361pub struct EarlyDiagCtxt {
1363 dcx: DiagCtxt,
1364}
1365
1366impl EarlyDiagCtxt {
1367 pub fn new(output: ErrorOutputType) -> Self {
1368 let emitter = mk_emitter(output);
1369 Self { dcx: DiagCtxt::new(emitter) }
1370 }
1371
1372 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1375 assert!(self.dcx.handle().has_errors().is_none());
1376
1377 let emitter = mk_emitter(output);
1378 self.dcx = DiagCtxt::new(emitter);
1379 }
1380
1381 #[allow(rustc::untranslatable_diagnostic)]
1382 #[allow(rustc::diagnostic_outside_of_impl)]
1383 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1384 self.dcx.handle().note(msg)
1385 }
1386
1387 #[allow(rustc::untranslatable_diagnostic)]
1388 #[allow(rustc::diagnostic_outside_of_impl)]
1389 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1390 self.dcx.handle().struct_help(msg).emit()
1391 }
1392
1393 #[allow(rustc::untranslatable_diagnostic)]
1394 #[allow(rustc::diagnostic_outside_of_impl)]
1395 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1396 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1397 self.dcx.handle().err(msg)
1398 }
1399
1400 #[allow(rustc::untranslatable_diagnostic)]
1401 #[allow(rustc::diagnostic_outside_of_impl)]
1402 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1403 self.dcx.handle().fatal(msg)
1404 }
1405
1406 #[allow(rustc::untranslatable_diagnostic)]
1407 #[allow(rustc::diagnostic_outside_of_impl)]
1408 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1409 self.dcx.handle().struct_fatal(msg)
1410 }
1411
1412 #[allow(rustc::untranslatable_diagnostic)]
1413 #[allow(rustc::diagnostic_outside_of_impl)]
1414 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1415 self.dcx.handle().warn(msg)
1416 }
1417
1418 #[allow(rustc::untranslatable_diagnostic)]
1419 #[allow(rustc::diagnostic_outside_of_impl)]
1420 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1421 self.dcx.handle().struct_warn(msg)
1422 }
1423}
1424
1425fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1426 let fallback_bundle =
1429 fallback_fluent_bundle(vec![rustc_errors::DEFAULT_LOCALE_RESOURCE], false);
1430 let emitter: Box<DynEmitter> = match output {
1431 config::ErrorOutputType::HumanReadable { kind, color_config } => {
1432 let short = kind.short();
1433 Box::new(
1434 HumanEmitter::new(stderr_destination(color_config), fallback_bundle)
1435 .theme(if let HumanReadableErrorType::Unicode = kind {
1436 OutputTheme::Unicode
1437 } else {
1438 OutputTheme::Ascii
1439 })
1440 .short_message(short),
1441 )
1442 }
1443 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1444 Box::new(JsonEmitter::new(
1445 Box::new(io::BufWriter::new(io::stderr())),
1446 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1447 fallback_bundle,
1448 pretty,
1449 json_rendered,
1450 color_config,
1451 ))
1452 }
1453 };
1454 emitter
1455}
1456
1457pub trait RemapFileNameExt {
1458 type Output<'a>
1459 where
1460 Self: 'a;
1461
1462 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_>;
1466}
1467
1468impl RemapFileNameExt for rustc_span::FileName {
1469 type Output<'a> = rustc_span::FileNameDisplay<'a>;
1470
1471 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1472 assert!(
1473 scope.bits().count_ones() == 1,
1474 "one and only one scope should be passed to for_scope"
1475 );
1476 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1477 self.prefer_remapped_unconditionaly()
1478 } else {
1479 self.prefer_local()
1480 }
1481 }
1482}
1483
1484impl RemapFileNameExt for rustc_span::RealFileName {
1485 type Output<'a> = &'a Path;
1486
1487 fn for_scope(&self, sess: &Session, scope: RemapPathScopeComponents) -> Self::Output<'_> {
1488 assert!(
1489 scope.bits().count_ones() == 1,
1490 "one and only one scope should be passed to for_scope"
1491 );
1492 if sess.opts.unstable_opts.remap_path_scope.contains(scope) {
1493 self.remapped_path_if_available()
1494 } else {
1495 self.local_path_if_available()
1496 }
1497 }
1498}