1use std::any::Any;
2use std::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_data_structures::base_n::{CASE_INSENSITIVE, ToBaseN};
10use rustc_data_structures::flock;
11use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
12use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
13use rustc_data_structures::sync::{DynSend, DynSync, Lock, MappedReadGuard, ReadGuard, RwLock};
14use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;
15use rustc_errors::codes::*;
16use rustc_errors::emitter::{DynEmitter, HumanReadableErrorType, OutputTheme, stderr_destination};
17use rustc_errors::json::JsonEmitter;
18use rustc_errors::timings::TimingSectionHandler;
19use rustc_errors::translation::Translator;
20use rustc_errors::{
21 Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, FatalAbort,
22 TerminalUrl,
23};
24use rustc_hir::limit::Limit;
25use rustc_macros::HashStable_Generic;
26pub use rustc_span::def_id::StableCrateId;
27use rustc_span::edition::Edition;
28use rustc_span::source_map::{FilePathMapping, SourceMap};
29use rustc_span::{RealFileName, Span, Symbol};
30use rustc_target::asm::InlineAsmArch;
31use rustc_target::spec::{
32 Arch, CodeModel, DebuginfoKind, Os, PanicStrategy, RelocModel, RelroLevel, SanitizerSet,
33 SmallDataThresholdSupport, SplitDebuginfo, StackProtector, SymbolVisibility, Target,
34 TargetTuple, TlsModel, apple,
35};
36
37use crate::code_stats::CodeStats;
38pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
39use crate::config::{
40 self, CoverageLevel, CoverageOptions, CrateType, DebugInfo, ErrorOutputType, FunctionReturn,
41 Input, InstrumentCoverage, OptLevel, OutFileName, OutputType, SwitchWithOptPath,
42};
43use crate::filesearch::FileSearch;
44use crate::lint::LintId;
45use crate::parse::{ParseSess, add_feature_diagnostics};
46use crate::search_paths::SearchPath;
47use crate::{errors, filesearch, lint};
48
49#[derive(#[automatically_derived]
impl ::core::clone::Clone for CtfeBacktrace {
#[inline]
fn clone(&self) -> CtfeBacktrace { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for CtfeBacktrace { }Copy)]
51pub enum CtfeBacktrace {
52 Disabled,
54 Capture,
57 Immediate,
59}
60
61#[derive(#[automatically_derived]
impl ::core::clone::Clone for Limits {
#[inline]
fn clone(&self) -> Limits {
let _: ::core::clone::AssertParamIsClone<Limit>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Limits { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Limits {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f, "Limits",
"recursion_limit", &self.recursion_limit, "move_size_limit",
&self.move_size_limit, "type_length_limit",
&self.type_length_limit, "pattern_complexity_limit",
&&self.pattern_complexity_limit)
}
}Debug, const _: () =
{
impl<__CTX> ::rustc_data_structures::stable_hasher::HashStable<__CTX>
for Limits where __CTX: crate::HashStableContext {
#[inline]
fn hash_stable(&self, __hcx: &mut __CTX,
__hasher:
&mut ::rustc_data_structures::stable_hasher::StableHasher) {
match *self {
Limits {
recursion_limit: ref __binding_0,
move_size_limit: ref __binding_1,
type_length_limit: ref __binding_2,
pattern_complexity_limit: ref __binding_3 } => {
{ __binding_0.hash_stable(__hcx, __hasher); }
{ __binding_1.hash_stable(__hcx, __hasher); }
{ __binding_2.hash_stable(__hcx, __hasher); }
{ __binding_3.hash_stable(__hcx, __hasher); }
}
}
}
}
};HashStable_Generic)]
62pub struct Limits {
63 pub recursion_limit: Limit,
66 pub move_size_limit: Limit,
69 pub type_length_limit: Limit,
71 pub pattern_complexity_limit: Limit,
73}
74
75pub struct CompilerIO {
76 pub input: Input,
77 pub output_dir: Option<PathBuf>,
78 pub output_file: Option<OutFileName>,
79 pub temps_dir: Option<PathBuf>,
80}
81
82pub trait DynLintStore: Any + DynSync + DynSend {
83 fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;
85}
86
87pub struct Session {
90 pub target: Target,
91 pub host: Target,
92 pub opts: config::Options,
93 pub target_tlib_path: Arc<SearchPath>,
94 pub psess: ParseSess,
95 pub io: CompilerIO,
97
98 incr_comp_session: RwLock<IncrCompSession>,
99
100 pub prof: SelfProfilerRef,
102
103 pub timings: TimingSectionHandler,
105
106 pub code_stats: CodeStats,
108
109 pub lint_store: Option<Arc<dyn DynLintStore>>,
111
112 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
114
115 pub ctfe_backtrace: Lock<CtfeBacktrace>,
122
123 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
128
129 pub asm_arch: Option<InlineAsmArch>,
131
132 pub target_features: FxIndexSet<Symbol>,
134
135 pub unstable_target_features: FxIndexSet<Symbol>,
137
138 pub cfg_version: &'static str,
140
141 pub using_internal_features: &'static AtomicBool,
146
147 target_filesearch: FileSearch,
148 host_filesearch: FileSearch,
149
150 pub invocation_temp: Option<String>,
157
158 pub replaced_intrinsics: FxHashSet<Symbol>,
161}
162
163#[derive(#[automatically_derived]
impl ::core::clone::Clone for CodegenUnits {
#[inline]
fn clone(&self) -> CodegenUnits {
let _: ::core::clone::AssertParamIsClone<usize>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for CodegenUnits { }Copy)]
164pub enum CodegenUnits {
165 User(usize),
168
169 Default(usize),
173}
174
175impl CodegenUnits {
176 pub fn as_usize(self) -> usize {
177 match self {
178 CodegenUnits::User(n) => n,
179 CodegenUnits::Default(n) => n,
180 }
181 }
182}
183
184pub struct LintGroup {
185 pub name: &'static str,
186 pub lints: Vec<LintId>,
187 pub is_externally_loaded: bool,
188}
189
190impl Session {
191 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
192 self.miri_unleashed_features.lock().push((span, feature_gate));
193 }
194
195 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
196 Some(
197 self.source_map()
198 .path_mapping()
199 .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),
200 )
201 }
202
203 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
204 let mut guar = None;
205 let unleashed_features = self.miri_unleashed_features.lock();
206 if !unleashed_features.is_empty() {
207 let mut must_err = false;
208 self.dcx().emit_warn(errors::SkippingConstChecks {
210 unleashed_features: unleashed_features
211 .iter()
212 .map(|(span, gate)| {
213 gate.map(|gate| {
214 must_err = true;
215 errors::UnleashedFeatureHelp::Named { span: *span, gate }
216 })
217 .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })
218 })
219 .collect(),
220 });
221
222 if must_err && self.dcx().has_errors().is_none() {
224 guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));
226 }
227 }
228 guar
229 }
230
231 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
233 let mut guar = None;
234 guar = guar.or(self.check_miri_unleashed_features());
235 guar = guar.or(self.dcx().emit_stashed_diagnostics());
236 self.dcx().print_error_count();
237 if self.opts.json_future_incompat {
238 self.dcx().emit_future_breakage_report();
239 }
240 guar
241 }
242
243 pub fn is_test_crate(&self) -> bool {
245 self.opts.test
246 }
247
248 #[track_caller]
250 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
251 let mut err = self.dcx().create_err(err);
252 if err.code.is_none() {
253 err.code(E0658);
254 }
255 add_feature_diagnostics(&mut err, self, feature);
256 err
257 }
258
259 pub fn record_trimmed_def_paths(&self) {
262 if self.opts.unstable_opts.print_type_sizes
263 || self.opts.unstable_opts.query_dep_graph
264 || self.opts.unstable_opts.dump_mir.is_some()
265 || self.opts.unstable_opts.unpretty.is_some()
266 || self.prof.is_args_recording_enabled()
267 || self.opts.output_types.contains_key(&OutputType::Mir)
268 || std::env::var_os("RUSTC_LOG").is_some()
269 {
270 return;
271 }
272
273 self.dcx().set_must_produce_diag()
274 }
275
276 #[inline]
277 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
278 self.psess.dcx()
279 }
280
281 #[inline]
282 pub fn source_map(&self) -> &SourceMap {
283 self.psess.source_map()
284 }
285
286 pub fn enable_internal_lints(&self) -> bool {
290 self.unstable_options() && !self.opts.actually_rustdoc
291 }
292
293 pub fn instrument_coverage(&self) -> bool {
294 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
295 }
296
297 pub fn instrument_coverage_branch(&self) -> bool {
298 self.instrument_coverage()
299 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
300 }
301
302 pub fn instrument_coverage_condition(&self) -> bool {
303 self.instrument_coverage()
304 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
305 }
306
307 pub fn coverage_options(&self) -> &CoverageOptions {
311 &self.opts.unstable_opts.coverage_options
312 }
313
314 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
315 self.sanitizers().contains(SanitizerSet::CFI)
316 }
317
318 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
319 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
320 }
321
322 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
323 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
324 }
325
326 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
327 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
328 }
329
330 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
331 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
332 }
333
334 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
335 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
336 }
337
338 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
339 self.sanitizers().contains(SanitizerSet::KCFI)
340 }
341
342 pub fn is_split_lto_unit_enabled(&self) -> bool {
343 self.opts.unstable_opts.split_lto_unit == Some(true)
344 }
345
346 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
348 if !self.target.crt_static_respected {
349 return self.target.crt_static_default;
351 }
352
353 let requested_features = self.opts.cg.target_feature.split(',');
354 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
355 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
356
357 #[allow(rustc::bad_opt_access)]
359 if found_positive || found_negative {
360 found_positive
361 } else if crate_type == Some(CrateType::ProcMacro)
362 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
363 {
364 false
368 } else {
369 self.target.crt_static_default
370 }
371 }
372
373 pub fn is_wasi_reactor(&self) -> bool {
374 self.target.options.os == Os::Wasi
375 && #[allow(non_exhaustive_omitted_patterns)] match self.opts.unstable_opts.wasi_exec_model
{
Some(config::WasiExecModel::Reactor) => true,
_ => false,
}matches!(
376 self.opts.unstable_opts.wasi_exec_model,
377 Some(config::WasiExecModel::Reactor)
378 )
379 }
380
381 pub fn target_can_use_split_dwarf(&self) -> bool {
383 self.target.debuginfo_kind == DebuginfoKind::Dwarf
384 }
385
386 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
387 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("__rustc_proc_macro_decls_{0:08x}__",
stable_crate_id.as_u64()))
})format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.as_u64())
388 }
389
390 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
391 &self.target_filesearch
392 }
393 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
394 &self.host_filesearch
395 }
396
397 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
401 let search_paths = self
402 .opts
403 .sysroot
404 .all_paths()
405 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
406
407 if self_contained {
408 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
412 } else {
413 search_paths.collect()
414 }
415 }
416
417 pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
418 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
419
420 if let IncrCompSession::NotInitialized = *incr_comp_session {
421 } else {
422 {
::core::panicking::panic_fmt(format_args!("Trying to initialize IncrCompSession `{0:?}`",
*incr_comp_session));
}panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
423 }
424
425 *incr_comp_session =
426 IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
427 }
428
429 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
430 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
431
432 if let IncrCompSession::Active { .. } = *incr_comp_session {
433 } else {
434 {
::core::panicking::panic_fmt(format_args!("trying to finalize `IncrCompSession` `{0:?}`",
*incr_comp_session));
};panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
435 }
436
437 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
439 }
440
441 pub fn mark_incr_comp_session_as_invalid(&self) {
442 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
443
444 let session_directory = match *incr_comp_session {
445 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
446 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
447 _ => {
::core::panicking::panic_fmt(format_args!("trying to invalidate `IncrCompSession` `{0:?}`",
*incr_comp_session));
}panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
448 };
449
450 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
452 }
453
454 pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
455 let incr_comp_session = self.incr_comp_session.borrow();
456 ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
457 IncrCompSession::NotInitialized => {
::core::panicking::panic_fmt(format_args!("trying to get session directory from `IncrCompSession`: {0:?}",
*incr_comp_session));
}panic!(
458 "trying to get session directory from `IncrCompSession`: {:?}",
459 *incr_comp_session,
460 ),
461 IncrCompSession::Active { ref session_directory, .. }
462 | IncrCompSession::Finalized { ref session_directory }
463 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
464 session_directory
465 }
466 })
467 }
468
469 pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
470 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
471 }
472
473 pub fn is_rust_2015(&self) -> bool {
475 self.edition().is_rust_2015()
476 }
477
478 pub fn at_least_rust_2018(&self) -> bool {
480 self.edition().at_least_rust_2018()
481 }
482
483 pub fn at_least_rust_2021(&self) -> bool {
485 self.edition().at_least_rust_2021()
486 }
487
488 pub fn at_least_rust_2024(&self) -> bool {
490 self.edition().at_least_rust_2024()
491 }
492
493 pub fn needs_plt(&self) -> bool {
495 let want_plt = self.target.plt_by_default;
498
499 let dbg_opts = &self.opts.unstable_opts;
500
501 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
502
503 let full_relro = RelroLevel::Full == relro_level;
507
508 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
511 }
512
513 pub fn emit_lifetime_markers(&self) -> bool {
515 self.opts.optimize != config::OptLevel::No
516 || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
520 }
521
522 pub fn diagnostic_width(&self) -> usize {
523 let default_column_width = 140;
524 if let Some(width) = self.opts.diagnostic_width {
525 width
526 } else if self.opts.unstable_opts.ui_testing {
527 default_column_width
528 } else {
529 termize::dimensions().map_or(default_column_width, |(w, _)| w)
530 }
531 }
532
533 pub fn default_visibility(&self) -> SymbolVisibility {
535 self.opts
536 .unstable_opts
537 .default_visibility
538 .or(self.target.options.default_visibility)
539 .unwrap_or(SymbolVisibility::Interposable)
540 }
541
542 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
543 if verbatim {
544 ("", "")
545 } else {
546 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
547 }
548 }
549
550 pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
551 match self.lint_store {
552 Some(ref lint_store) => lint_store.lint_groups_iter(),
553 None => Box::new(std::iter::empty()),
554 }
555 }
556}
557
558#[allow(rustc::bad_opt_access)]
560impl Session {
561 pub fn verbose_internals(&self) -> bool {
562 self.opts.unstable_opts.verbose_internals
563 }
564
565 pub fn print_llvm_stats(&self) -> bool {
566 self.opts.unstable_opts.print_codegen_stats
567 }
568
569 pub fn verify_llvm_ir(&self) -> bool {
570 self.opts.unstable_opts.verify_llvm_ir || ::core::option::Option::None::<&'static str>option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
571 }
572
573 pub fn binary_dep_depinfo(&self) -> bool {
574 self.opts.unstable_opts.binary_dep_depinfo
575 }
576
577 pub fn mir_opt_level(&self) -> usize {
578 self.opts
579 .unstable_opts
580 .mir_opt_level
581 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
582 }
583
584 pub fn lto(&self) -> config::Lto {
586 if self.target.requires_lto {
588 return config::Lto::Fat;
589 }
590
591 match self.opts.cg.lto {
595 config::LtoCli::Unspecified => {
596 }
599 config::LtoCli::No => {
600 return config::Lto::No;
602 }
603 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
604 return config::Lto::Fat;
606 }
607 config::LtoCli::Thin => {
608 return config::Lto::Thin;
610 }
611 }
612
613 if self.opts.cli_forced_local_thinlto_off {
622 return config::Lto::No;
623 }
624
625 if let Some(enabled) = self.opts.unstable_opts.thinlto {
628 if enabled {
629 return config::Lto::ThinLocal;
630 } else {
631 return config::Lto::No;
632 }
633 }
634
635 if self.codegen_units().as_usize() == 1 {
638 return config::Lto::No;
639 }
640
641 match self.opts.optimize {
644 config::OptLevel::No => config::Lto::No,
645 _ => config::Lto::ThinLocal,
646 }
647 }
648
649 pub fn panic_strategy(&self) -> PanicStrategy {
652 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
653 }
654
655 pub fn fewer_names(&self) -> bool {
656 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
657 fewer_names
658 } else {
659 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
660 || self.opts.output_types.contains_key(&OutputType::Bitcode)
661 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
663 !more_names
664 }
665 }
666
667 pub fn unstable_options(&self) -> bool {
668 self.opts.unstable_opts.unstable_options
669 }
670
671 pub fn is_nightly_build(&self) -> bool {
672 self.opts.unstable_features.is_nightly_build()
673 }
674
675 pub fn overflow_checks(&self) -> bool {
676 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
677 }
678
679 pub fn ub_checks(&self) -> bool {
680 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
681 }
682
683 pub fn contract_checks(&self) -> bool {
684 self.opts.unstable_opts.contract_checks.unwrap_or(false)
685 }
686
687 pub fn relocation_model(&self) -> RelocModel {
688 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
689 }
690
691 pub fn code_model(&self) -> Option<CodeModel> {
692 self.opts.cg.code_model.or(self.target.code_model)
693 }
694
695 pub fn tls_model(&self) -> TlsModel {
696 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
697 }
698
699 pub fn direct_access_external_data(&self) -> Option<bool> {
700 self.opts
701 .unstable_opts
702 .direct_access_external_data
703 .or(self.target.direct_access_external_data)
704 }
705
706 pub fn split_debuginfo(&self) -> SplitDebuginfo {
707 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
708 }
709
710 pub fn dwarf_version(&self) -> u32 {
712 self.opts
713 .cg
714 .dwarf_version
715 .or(self.opts.unstable_opts.dwarf_version)
716 .unwrap_or(self.target.default_dwarf_version)
717 }
718
719 pub fn stack_protector(&self) -> StackProtector {
720 if self.target.options.supports_stack_protector {
721 self.opts.unstable_opts.stack_protector
722 } else {
723 StackProtector::None
724 }
725 }
726
727 pub fn must_emit_unwind_tables(&self) -> bool {
728 self.target.requires_uwtable
757 || self
758 .opts
759 .cg
760 .force_unwind_tables
761 .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
762 }
763
764 #[inline]
767 pub fn threads(&self) -> usize {
768 self.opts.unstable_opts.threads
769 }
770
771 pub fn codegen_units(&self) -> CodegenUnits {
774 if let Some(n) = self.opts.cli_forced_codegen_units {
775 return CodegenUnits::User(n);
776 }
777 if let Some(n) = self.target.default_codegen_units {
778 return CodegenUnits::Default(n as usize);
779 }
780
781 if self.opts.incremental.is_some() {
785 return CodegenUnits::Default(256);
786 }
787
788 CodegenUnits::Default(16)
839 }
840
841 pub fn teach(&self, code: ErrCode) -> bool {
842 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
843 }
844
845 pub fn edition(&self) -> Edition {
846 self.opts.edition
847 }
848
849 pub fn link_dead_code(&self) -> bool {
850 self.opts.cg.link_dead_code.unwrap_or(false)
851 }
852
853 pub fn apple_deployment_target(&self) -> apple::OSVersion {
858 let min = apple::OSVersion::minimum_deployment_target(&self.target);
859 let env_var = apple::deployment_target_env_var(&self.target.os);
860
861 if let Ok(deployment_target) = env::var(env_var) {
863 match apple::OSVersion::from_str(&deployment_target) {
864 Ok(version) => {
865 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
866 if version < os_min {
871 self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {
872 env_var,
873 version: version.fmt_pretty().to_string(),
874 os_min: os_min.fmt_pretty().to_string(),
875 });
876 }
877
878 version.max(min)
880 }
881 Err(error) => {
882 self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });
883 min
884 }
885 }
886 } else {
887 min
889 }
890 }
891
892 pub fn sanitizers(&self) -> SanitizerSet {
893 return self.opts.unstable_opts.sanitizer | self.target.options.default_sanitizers;
894 }
895}
896
897#[allow(rustc::bad_opt_access)]
899fn default_emitter(
900 sopts: &config::Options,
901 source_map: Arc<SourceMap>,
902 translator: Translator,
903) -> Box<DynEmitter> {
904 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
905 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
906 let terminal_url = match sopts.unstable_opts.terminal_urls {
907 TerminalUrl::Auto => {
908 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
909 (Ok("truecolor"), Ok("xterm-256color"))
910 if sopts.unstable_features.is_nightly_build() =>
911 {
912 TerminalUrl::Yes
913 }
914 _ => TerminalUrl::No,
915 }
916 }
917 t => t,
918 };
919
920 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
921
922 match sopts.error_format {
923 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
924 HumanReadableErrorType { short, unicode } => {
925 let emitter =
926 AnnotateSnippetEmitter::new(stderr_destination(color_config), translator)
927 .sm(source_map)
928 .short_message(short)
929 .diagnostic_width(sopts.diagnostic_width)
930 .macro_backtrace(macro_backtrace)
931 .track_diagnostics(track_diagnostics)
932 .terminal_url(terminal_url)
933 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
934 .ignored_directories_in_source_blocks(
935 sopts
936 .unstable_opts
937 .ignore_directory_in_diagnostics_source_blocks
938 .clone(),
939 );
940 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
941 }
942 },
943 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
944 JsonEmitter::new(
945 Box::new(io::BufWriter::new(io::stderr())),
946 source_map,
947 translator,
948 pretty,
949 json_rendered,
950 color_config,
951 )
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)]
966pub fn build_session(
967 sopts: config::Options,
968 io: CompilerIO,
969 fluent_bundle: Option<Arc<rustc_errors::FluentBundle>>,
970 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
971 target: Target,
972 cfg_version: &'static str,
973 ice_file: Option<PathBuf>,
974 using_internal_features: &'static AtomicBool,
975) -> Session {
976 let warnings_allow = sopts
980 .lint_opts
981 .iter()
982 .rfind(|&(key, _)| *key == "warnings")
983 .is_some_and(|&(_, level)| level == lint::Allow);
984 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
985 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
986
987 let translator = Translator { fluent_bundle };
988 let source_map = rustc_span::source_map::get_source_map().unwrap();
989 let emitter = default_emitter(&sopts, Arc::clone(&source_map), translator);
990
991 let mut dcx =
992 DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));
993 if let Some(ice_file) = ice_file {
994 dcx = dcx.with_ice_file(ice_file);
995 }
996
997 let host_triple = TargetTuple::from_tuple(config::host_tuple());
998 let (host, target_warnings) =
999 Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)
1000 .unwrap_or_else(|e| {
1001 dcx.handle().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Error loading host specification: {0}",
e))
})format!("Error loading host specification: {e}"))
1002 });
1003 for warning in target_warnings.warning_messages() {
1004 dcx.handle().warn(warning)
1005 }
1006
1007 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1008 {
1009 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1010
1011 let profiler = SelfProfiler::new(
1012 directory,
1013 sopts.crate_name.as_deref(),
1014 sopts.unstable_opts.self_profile_events.as_deref(),
1015 &sopts.unstable_opts.self_profile_counter,
1016 );
1017 match profiler {
1018 Ok(profiler) => Some(Arc::new(profiler)),
1019 Err(e) => {
1020 dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1021 None
1022 }
1023 }
1024 } else {
1025 None
1026 };
1027
1028 let mut psess = ParseSess::with_dcx(dcx, source_map);
1029 psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1030
1031 let host_triple = config::host_tuple();
1032 let target_triple = sopts.target_triple.tuple();
1033 let host_tlib_path =
1035 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1036 let target_tlib_path = if host_triple == target_triple {
1037 Arc::clone(&host_tlib_path)
1040 } else {
1041 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1042 };
1043
1044 let prof = SelfProfilerRef::new(
1045 self_profiler,
1046 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1047 );
1048
1049 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1050 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1051 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1052 _ => CtfeBacktrace::Disabled,
1053 });
1054
1055 let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1056 let target_filesearch =
1057 filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1058 let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1059
1060 let invocation_temp = sopts
1061 .incremental
1062 .as_ref()
1063 .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
1064
1065 let timings = TimingSectionHandler::new(sopts.json_timings);
1066
1067 let sess = Session {
1068 target,
1069 host,
1070 opts: sopts,
1071 target_tlib_path,
1072 psess,
1073 io,
1074 incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1075 prof,
1076 timings,
1077 code_stats: Default::default(),
1078 lint_store: None,
1079 driver_lint_caps,
1080 ctfe_backtrace,
1081 miri_unleashed_features: Lock::new(Default::default()),
1082 asm_arch,
1083 target_features: Default::default(),
1084 unstable_target_features: Default::default(),
1085 cfg_version,
1086 using_internal_features,
1087 target_filesearch,
1088 host_filesearch,
1089 invocation_temp,
1090 replaced_intrinsics: FxHashSet::default(), };
1092
1093 validate_commandline_args_with_session_available(&sess);
1094
1095 sess
1096}
1097
1098#[allow(rustc::bad_opt_access)]
1104fn validate_commandline_args_with_session_available(sess: &Session) {
1105 if sess.opts.cg.linker_plugin_lto.enabled()
1113 && sess.opts.cg.prefer_dynamic
1114 && sess.target.is_like_windows
1115 {
1116 sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1117 }
1118
1119 if let Some(ref path) = sess.opts.cg.profile_use {
1122 if !path.exists() {
1123 sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1124 }
1125 }
1126
1127 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1129 if !path.exists() {
1130 sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1131 }
1132 }
1133
1134 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1136 if sess.target.requires_uwtable && !include_uwtables {
1137 sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1138 }
1139 }
1140
1141 let supported_sanitizers = sess.target.options.supported_sanitizers;
1143 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1144 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1147 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1148 }
1149 match unsupported_sanitizers.into_iter().count() {
1150 0 => {}
1151 1 => {
1152 sess.dcx()
1153 .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1154 }
1155 _ => {
1156 sess.dcx().emit_err(errors::SanitizersNotSupported {
1157 us: unsupported_sanitizers.to_string(),
1158 });
1159 }
1160 }
1161
1162 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1164 sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1165 first: first.to_string(),
1166 second: second.to_string(),
1167 });
1168 }
1169
1170 if sess.crt_static(None)
1172 && !sess.opts.unstable_opts.sanitizer.is_empty()
1173 && !sess.target.is_like_msvc
1174 {
1175 sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1176 }
1177
1178 if sess.is_sanitizer_cfi_enabled()
1180 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1181 {
1182 sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1183 }
1184
1185 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1187 sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1188 }
1189
1190 if sess.is_sanitizer_cfi_enabled()
1192 && sess.lto() == config::Lto::Fat
1193 && (sess.codegen_units().as_usize() != 1)
1194 {
1195 sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1196 }
1197
1198 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1200 if !sess.is_sanitizer_cfi_enabled() {
1201 sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1202 }
1203 }
1204
1205 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1207 sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);
1208 }
1209
1210 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1212 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1213 sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1214 }
1215 }
1216
1217 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1219 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1220 sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1221 }
1222 }
1223
1224 if sess.is_split_lto_unit_enabled()
1226 && !(sess.lto() == config::Lto::Fat
1227 || sess.lto() == config::Lto::Thin
1228 || sess.opts.cg.linker_plugin_lto.enabled())
1229 {
1230 sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1231 }
1232
1233 if sess.lto() != config::Lto::Fat {
1235 if sess.opts.unstable_opts.virtual_function_elimination {
1236 sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1237 }
1238 }
1239
1240 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1241 if !sess.target.options.supports_stack_protector {
1242 sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1243 stack_protector: sess.opts.unstable_opts.stack_protector,
1244 target_triple: &sess.opts.target_triple,
1245 });
1246 }
1247 }
1248
1249 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1250 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1251 sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1252 target_triple: &sess.opts.target_triple,
1253 })
1254 }
1255 }
1256
1257 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1258 sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1259 }
1260
1261 if let Some(dwarf_version) =
1262 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1263 {
1264 if dwarf_version < 2 || dwarf_version > 5 {
1266 sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1267 }
1268 }
1269
1270 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1271 && !sess.opts.unstable_opts.unstable_options
1272 {
1273 sess.dcx()
1274 .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1275 }
1276
1277 if sess.opts.unstable_opts.embed_source {
1278 let dwarf_version = sess.dwarf_version();
1279
1280 if dwarf_version < 5 {
1281 sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1282 }
1283
1284 if sess.opts.debuginfo == DebugInfo::None {
1285 sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1286 }
1287 }
1288
1289 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1290 sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1291 }
1292
1293 if let Some(flavor) = sess.opts.cg.linker_flavor
1294 && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1295 {
1296 let flavor = flavor.desc();
1297 sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1298 }
1299
1300 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1301 if !#[allow(non_exhaustive_omitted_patterns)] match sess.target.arch {
Arch::X86 | Arch::X86_64 => true,
_ => false,
}matches!(sess.target.arch, Arch::X86 | Arch::X86_64) {
1302 sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1303 }
1304 }
1305
1306 if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1307 if !#[allow(non_exhaustive_omitted_patterns)] match sess.target.arch {
Arch::X86 | Arch::X86_64 => true,
_ => false,
}matches!(sess.target.arch, Arch::X86 | Arch::X86_64) {
1308 sess.dcx().emit_err(errors::IndirectBranchCsPrefixRequiresX86OrX8664);
1309 }
1310 }
1311
1312 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1313 if regparm > 3 {
1314 sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1315 }
1316 if sess.target.arch != Arch::X86 {
1317 sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1318 }
1319 }
1320 if sess.opts.unstable_opts.reg_struct_return {
1321 if sess.target.arch != Arch::X86 {
1322 sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1323 }
1324 }
1325
1326 match sess.opts.unstable_opts.function_return {
1330 FunctionReturn::Keep => (),
1331 FunctionReturn::ThunkExtern => {
1332 if let Some(code_model) = sess.code_model()
1335 && code_model == CodeModel::Large
1336 {
1337 sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1338 }
1339 }
1340 }
1341
1342 if sess.opts.cg.soft_float {
1343 if sess.target.arch == Arch::Arm {
1344 sess.dcx().emit_warn(errors::SoftFloatDeprecated);
1345 } else {
1346 sess.dcx().emit_warn(errors::SoftFloatIgnored);
1349 }
1350 }
1351}
1352
1353#[derive(#[automatically_derived]
impl ::core::fmt::Debug for IncrCompSession {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
IncrCompSession::NotInitialized =>
::core::fmt::Formatter::write_str(f, "NotInitialized"),
IncrCompSession::Active {
session_directory: __self_0, _lock_file: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Active", "session_directory", __self_0, "_lock_file",
&__self_1),
IncrCompSession::Finalized { session_directory: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Finalized", "session_directory", &__self_0),
IncrCompSession::InvalidBecauseOfErrors {
session_directory: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"InvalidBecauseOfErrors", "session_directory", &__self_0),
}
}
}Debug)]
1355enum IncrCompSession {
1356 NotInitialized,
1359 Active { session_directory: PathBuf, _lock_file: flock::Lock },
1364 Finalized { session_directory: PathBuf },
1367 InvalidBecauseOfErrors { session_directory: PathBuf },
1371}
1372
1373pub struct EarlyDiagCtxt {
1375 dcx: DiagCtxt,
1376}
1377
1378impl EarlyDiagCtxt {
1379 pub fn new(output: ErrorOutputType) -> Self {
1380 let emitter = mk_emitter(output);
1381 Self { dcx: DiagCtxt::new(emitter) }
1382 }
1383
1384 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1387 if !self.dcx.handle().has_errors().is_none() {
::core::panicking::panic("assertion failed: self.dcx.handle().has_errors().is_none()")
};assert!(self.dcx.handle().has_errors().is_none());
1388
1389 let emitter = mk_emitter(output);
1390 self.dcx = DiagCtxt::new(emitter);
1391 }
1392
1393 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1394 self.dcx.handle().note(msg)
1395 }
1396
1397 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1398 self.dcx.handle().struct_help(msg).emit()
1399 }
1400
1401 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1402 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1403 self.dcx.handle().err(msg)
1404 }
1405
1406 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1407 self.dcx.handle().fatal(msg)
1408 }
1409
1410 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1411 self.dcx.handle().struct_fatal(msg)
1412 }
1413
1414 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1415 self.dcx.handle().warn(msg)
1416 }
1417
1418 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1419 self.dcx.handle().struct_warn(msg)
1420 }
1421}
1422
1423fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1424 let translator = Translator::new();
1427 let emitter: Box<DynEmitter> = match output {
1428 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1429 HumanReadableErrorType { short, unicode } => Box::new(
1430 AnnotateSnippetEmitter::new(stderr_destination(color_config), translator)
1431 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1432 .short_message(short),
1433 ),
1434 },
1435 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1436 Box::new(JsonEmitter::new(
1437 Box::new(io::BufWriter::new(io::stderr())),
1438 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1439 translator,
1440 pretty,
1441 json_rendered,
1442 color_config,
1443 ))
1444 }
1445 };
1446 emitter
1447}