1use std::any::Any;
2use std::path::PathBuf;
3use std::str::FromStr;
4use std::sync::Arc;
5use std::sync::atomic::{AtomicBool, AtomicUsize};
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::{
20 Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, FatalAbort,
21 TerminalUrl,
22};
23use rustc_hir::limit::Limit;
24use rustc_macros::HashStable_Generic;
25pub use rustc_span::def_id::StableCrateId;
26use rustc_span::edition::Edition;
27use rustc_span::source_map::{FilePathMapping, SourceMap};
28use rustc_span::{RealFileName, Span, Symbol};
29use rustc_target::asm::InlineAsmArch;
30use rustc_target::spec::{
31 Arch, CodeModel, DebuginfoKind, Os, PanicStrategy, RelocModel, RelroLevel, SanitizerSet,
32 SmallDataThresholdSupport, SplitDebuginfo, StackProtector, SymbolVisibility, Target,
33 TargetTuple, TlsModel, apple,
34};
35
36use crate::code_stats::CodeStats;
37pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
38use crate::config::{
39 self, CoverageLevel, CoverageOptions, CrateType, DebugInfo, ErrorOutputType, FunctionReturn,
40 Input, InstrumentCoverage, OptLevel, OutFileName, OutputType, SwitchWithOptPath,
41};
42use crate::filesearch::FileSearch;
43use crate::lint::LintId;
44use crate::parse::{ParseSess, add_feature_diagnostics};
45use crate::search_paths::SearchPath;
46use crate::{errors, filesearch, lint};
47
48#[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)]
50pub enum CtfeBacktrace {
51 Disabled,
53 Capture,
56 Immediate,
58}
59
60#[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)]
61pub struct Limits {
62 pub recursion_limit: Limit,
65 pub move_size_limit: Limit,
68 pub type_length_limit: Limit,
70 pub pattern_complexity_limit: Limit,
72}
73
74pub struct CompilerIO {
75 pub input: Input,
76 pub output_dir: Option<PathBuf>,
77 pub output_file: Option<OutFileName>,
78 pub temps_dir: Option<PathBuf>,
79}
80
81pub trait DynLintStore: Any + DynSync + DynSend {
82 fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;
84}
85
86pub struct Session {
89 pub target: Target,
90 pub host: Target,
91 pub opts: config::Options,
92 pub target_tlib_path: Arc<SearchPath>,
93 pub psess: ParseSess,
94 pub io: CompilerIO,
96
97 incr_comp_session: RwLock<IncrCompSession>,
98
99 pub prof: SelfProfilerRef,
101
102 pub timings: TimingSectionHandler,
104
105 pub code_stats: CodeStats,
107
108 pub lint_store: Option<Arc<dyn DynLintStore>>,
110
111 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
113
114 pub ctfe_backtrace: Lock<CtfeBacktrace>,
121
122 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
127
128 pub asm_arch: Option<InlineAsmArch>,
130
131 pub target_features: FxIndexSet<Symbol>,
133
134 pub unstable_target_features: FxIndexSet<Symbol>,
136
137 pub cfg_version: &'static str,
139
140 pub using_internal_features: &'static AtomicBool,
145
146 target_filesearch: FileSearch,
147 host_filesearch: FileSearch,
148
149 pub invocation_temp: Option<String>,
156
157 pub replaced_intrinsics: FxHashSet<Symbol>,
160
161 pub thin_lto_supported: bool,
163
164 pub mir_opt_bisect_eval_count: AtomicUsize,
169
170 pub used_features: Lock<FxHashMap<Symbol, u32>>,
174}
175
176#[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)]
177pub enum CodegenUnits {
178 User(usize),
181
182 Default(usize),
186}
187
188impl CodegenUnits {
189 pub fn as_usize(self) -> usize {
190 match self {
191 CodegenUnits::User(n) => n,
192 CodegenUnits::Default(n) => n,
193 }
194 }
195}
196
197pub struct LintGroup {
198 pub name: &'static str,
199 pub lints: Vec<LintId>,
200 pub is_externally_loaded: bool,
201}
202
203impl Session {
204 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
205 self.miri_unleashed_features.lock().push((span, feature_gate));
206 }
207
208 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
209 Some(
210 self.source_map()
211 .path_mapping()
212 .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),
213 )
214 }
215
216 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
217 let mut guar = None;
218 let unleashed_features = self.miri_unleashed_features.lock();
219 if !unleashed_features.is_empty() {
220 let mut must_err = false;
221 self.dcx().emit_warn(errors::SkippingConstChecks {
223 unleashed_features: unleashed_features
224 .iter()
225 .map(|(span, gate)| {
226 gate.map(|gate| {
227 must_err = true;
228 errors::UnleashedFeatureHelp::Named { span: *span, gate }
229 })
230 .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })
231 })
232 .collect(),
233 });
234
235 if must_err && self.dcx().has_errors().is_none() {
237 guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));
239 }
240 }
241 guar
242 }
243
244 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
246 let mut guar = None;
247 guar = guar.or(self.check_miri_unleashed_features());
248 guar = guar.or(self.dcx().emit_stashed_diagnostics());
249 self.dcx().print_error_count();
250 if self.opts.json_future_incompat {
251 self.dcx().emit_future_breakage_report();
252 }
253 guar
254 }
255
256 pub fn is_test_crate(&self) -> bool {
258 self.opts.test
259 }
260
261 #[track_caller]
263 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
264 let mut err = self.dcx().create_err(err);
265 if err.code.is_none() {
266 err.code(E0658);
267 }
268 add_feature_diagnostics(&mut err, self, feature);
269 err
270 }
271
272 pub fn record_trimmed_def_paths(&self) {
275 if self.opts.unstable_opts.print_type_sizes
276 || self.opts.unstable_opts.query_dep_graph
277 || self.opts.unstable_opts.dump_mir.is_some()
278 || self.opts.unstable_opts.unpretty.is_some()
279 || self.prof.is_args_recording_enabled()
280 || self.opts.output_types.contains_key(&OutputType::Mir)
281 || std::env::var_os("RUSTC_LOG").is_some()
282 {
283 return;
284 }
285
286 self.dcx().set_must_produce_diag()
287 }
288
289 #[inline]
290 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
291 self.psess.dcx()
292 }
293
294 #[inline]
295 pub fn source_map(&self) -> &SourceMap {
296 self.psess.source_map()
297 }
298
299 pub fn enable_internal_lints(&self) -> bool {
303 self.unstable_options() && !self.opts.actually_rustdoc
304 }
305
306 pub fn instrument_coverage(&self) -> bool {
307 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
308 }
309
310 pub fn instrument_coverage_branch(&self) -> bool {
311 self.instrument_coverage()
312 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
313 }
314
315 pub fn instrument_coverage_condition(&self) -> bool {
316 self.instrument_coverage()
317 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
318 }
319
320 pub fn coverage_options(&self) -> &CoverageOptions {
324 &self.opts.unstable_opts.coverage_options
325 }
326
327 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
328 self.sanitizers().contains(SanitizerSet::CFI)
329 }
330
331 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
332 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
333 }
334
335 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
336 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
337 }
338
339 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
340 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
341 }
342
343 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
344 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
345 }
346
347 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
348 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
349 }
350
351 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
352 self.sanitizers().contains(SanitizerSet::KCFI)
353 }
354
355 pub fn is_split_lto_unit_enabled(&self) -> bool {
356 self.opts.unstable_opts.split_lto_unit == Some(true)
357 }
358
359 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
361 if !self.target.crt_static_respected {
362 return self.target.crt_static_default;
364 }
365
366 let requested_features = self.opts.cg.target_feature.split(',');
367 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
368 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
369
370 #[allow(rustc::bad_opt_access)]
372 if found_positive || found_negative {
373 found_positive
374 } else if crate_type == Some(CrateType::ProcMacro)
375 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
376 {
377 false
381 } else {
382 self.target.crt_static_default
383 }
384 }
385
386 pub fn is_wasi_reactor(&self) -> bool {
387 self.target.options.os == Os::Wasi
388 && #[allow(non_exhaustive_omitted_patterns)] match self.opts.unstable_opts.wasi_exec_model
{
Some(config::WasiExecModel::Reactor) => true,
_ => false,
}matches!(
389 self.opts.unstable_opts.wasi_exec_model,
390 Some(config::WasiExecModel::Reactor)
391 )
392 }
393
394 pub fn target_can_use_split_dwarf(&self) -> bool {
396 self.target.debuginfo_kind == DebuginfoKind::Dwarf
397 }
398
399 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
400 ::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())
401 }
402
403 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
404 &self.target_filesearch
405 }
406 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
407 &self.host_filesearch
408 }
409
410 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
414 let search_paths = self
415 .opts
416 .sysroot
417 .all_paths()
418 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
419
420 if self_contained {
421 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
425 } else {
426 search_paths.collect()
427 }
428 }
429
430 pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
431 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
432
433 if let IncrCompSession::NotInitialized = *incr_comp_session {
434 } else {
435 {
::core::panicking::panic_fmt(format_args!("Trying to initialize IncrCompSession `{0:?}`",
*incr_comp_session));
}panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
436 }
437
438 *incr_comp_session =
439 IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
440 }
441
442 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
443 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
444
445 if let IncrCompSession::Active { .. } = *incr_comp_session {
446 } else {
447 {
::core::panicking::panic_fmt(format_args!("trying to finalize `IncrCompSession` `{0:?}`",
*incr_comp_session));
};panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
448 }
449
450 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
452 }
453
454 pub fn mark_incr_comp_session_as_invalid(&self) {
455 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
456
457 let session_directory = match *incr_comp_session {
458 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
459 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
460 _ => {
::core::panicking::panic_fmt(format_args!("trying to invalidate `IncrCompSession` `{0:?}`",
*incr_comp_session));
}panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
461 };
462
463 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
465 }
466
467 pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
468 let incr_comp_session = self.incr_comp_session.borrow();
469 ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
470 IncrCompSession::NotInitialized => {
::core::panicking::panic_fmt(format_args!("trying to get session directory from `IncrCompSession`: {0:?}",
*incr_comp_session));
}panic!(
471 "trying to get session directory from `IncrCompSession`: {:?}",
472 *incr_comp_session,
473 ),
474 IncrCompSession::Active { ref session_directory, .. }
475 | IncrCompSession::Finalized { ref session_directory }
476 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
477 session_directory
478 }
479 })
480 }
481
482 pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
483 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
484 }
485
486 pub fn is_rust_2015(&self) -> bool {
488 self.edition().is_rust_2015()
489 }
490
491 pub fn at_least_rust_2018(&self) -> bool {
493 self.edition().at_least_rust_2018()
494 }
495
496 pub fn at_least_rust_2021(&self) -> bool {
498 self.edition().at_least_rust_2021()
499 }
500
501 pub fn at_least_rust_2024(&self) -> bool {
503 self.edition().at_least_rust_2024()
504 }
505
506 pub fn needs_plt(&self) -> bool {
508 let want_plt = self.target.plt_by_default;
511
512 let dbg_opts = &self.opts.unstable_opts;
513
514 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
515
516 let full_relro = RelroLevel::Full == relro_level;
520
521 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
524 }
525
526 pub fn emit_lifetime_markers(&self) -> bool {
528 self.opts.optimize != config::OptLevel::No
529 || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
533 }
534
535 pub fn diagnostic_width(&self) -> usize {
536 let default_column_width = 140;
537 if let Some(width) = self.opts.diagnostic_width {
538 width
539 } else if self.opts.unstable_opts.ui_testing {
540 default_column_width
541 } else {
542 termize::dimensions().map_or(default_column_width, |(w, _)| w)
543 }
544 }
545
546 pub fn default_visibility(&self) -> SymbolVisibility {
548 self.opts
549 .unstable_opts
550 .default_visibility
551 .or(self.target.options.default_visibility)
552 .unwrap_or(SymbolVisibility::Interposable)
553 }
554
555 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
556 if verbatim {
557 ("", "")
558 } else {
559 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
560 }
561 }
562
563 pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
564 match self.lint_store {
565 Some(ref lint_store) => lint_store.lint_groups_iter(),
566 None => Box::new(std::iter::empty()),
567 }
568 }
569}
570
571#[allow(rustc::bad_opt_access)]
573impl Session {
574 pub fn verbose_internals(&self) -> bool {
575 self.opts.unstable_opts.verbose_internals
576 }
577
578 pub fn print_llvm_stats(&self) -> bool {
579 self.opts.unstable_opts.print_codegen_stats
580 }
581
582 pub fn verify_llvm_ir(&self) -> bool {
583 self.opts.unstable_opts.verify_llvm_ir || ::core::option::Option::None::<&'static str>option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
584 }
585
586 pub fn binary_dep_depinfo(&self) -> bool {
587 self.opts.unstable_opts.binary_dep_depinfo
588 }
589
590 pub fn mir_opt_level(&self) -> usize {
591 self.opts
592 .unstable_opts
593 .mir_opt_level
594 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
595 }
596
597 pub fn lto(&self) -> config::Lto {
599 if self.target.requires_lto {
601 return config::Lto::Fat;
602 }
603
604 match self.opts.cg.lto {
608 config::LtoCli::Unspecified => {
609 }
612 config::LtoCli::No => {
613 return config::Lto::No;
615 }
616 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
617 return config::Lto::Fat;
619 }
620 config::LtoCli::Thin => {
621 if !self.thin_lto_supported {
623 self.dcx().emit_warn(errors::ThinLtoNotSupportedByBackend);
625 return config::Lto::Fat;
626 }
627 return config::Lto::Thin;
628 }
629 }
630
631 if !self.thin_lto_supported {
632 return config::Lto::No;
633 }
634
635 if self.opts.cli_forced_local_thinlto_off {
644 return config::Lto::No;
645 }
646
647 if let Some(enabled) = self.opts.unstable_opts.thinlto {
650 if enabled {
651 return config::Lto::ThinLocal;
652 } else {
653 return config::Lto::No;
654 }
655 }
656
657 if self.codegen_units().as_usize() == 1 {
660 return config::Lto::No;
661 }
662
663 match self.opts.optimize {
666 config::OptLevel::No => config::Lto::No,
667 _ => config::Lto::ThinLocal,
668 }
669 }
670
671 pub fn panic_strategy(&self) -> PanicStrategy {
674 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
675 }
676
677 pub fn fewer_names(&self) -> bool {
678 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
679 fewer_names
680 } else {
681 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
682 || self.opts.output_types.contains_key(&OutputType::Bitcode)
683 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
685 !more_names
686 }
687 }
688
689 pub fn unstable_options(&self) -> bool {
690 self.opts.unstable_opts.unstable_options
691 }
692
693 pub fn is_nightly_build(&self) -> bool {
694 self.opts.unstable_features.is_nightly_build()
695 }
696
697 pub fn overflow_checks(&self) -> bool {
698 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
699 }
700
701 pub fn ub_checks(&self) -> bool {
702 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
703 }
704
705 pub fn contract_checks(&self) -> bool {
706 self.opts.unstable_opts.contract_checks.unwrap_or(false)
707 }
708
709 pub fn relocation_model(&self) -> RelocModel {
710 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
711 }
712
713 pub fn code_model(&self) -> Option<CodeModel> {
714 self.opts.cg.code_model.or(self.target.code_model)
715 }
716
717 pub fn tls_model(&self) -> TlsModel {
718 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
719 }
720
721 pub fn direct_access_external_data(&self) -> Option<bool> {
722 self.opts
723 .unstable_opts
724 .direct_access_external_data
725 .or(self.target.direct_access_external_data)
726 }
727
728 pub fn split_debuginfo(&self) -> SplitDebuginfo {
729 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
730 }
731
732 pub fn dwarf_version(&self) -> u32 {
734 self.opts
735 .cg
736 .dwarf_version
737 .or(self.opts.unstable_opts.dwarf_version)
738 .unwrap_or(self.target.default_dwarf_version)
739 }
740
741 pub fn stack_protector(&self) -> StackProtector {
742 if self.target.options.supports_stack_protector {
743 self.opts.unstable_opts.stack_protector
744 } else {
745 StackProtector::None
746 }
747 }
748
749 pub fn must_emit_unwind_tables(&self) -> bool {
750 self.target.requires_uwtable
779 || self
780 .opts
781 .cg
782 .force_unwind_tables
783 .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
784 }
785
786 #[inline]
789 pub fn threads(&self) -> usize {
790 self.opts.unstable_opts.threads
791 }
792
793 pub fn codegen_units(&self) -> CodegenUnits {
796 if let Some(n) = self.opts.cli_forced_codegen_units {
797 return CodegenUnits::User(n);
798 }
799 if let Some(n) = self.target.default_codegen_units {
800 return CodegenUnits::Default(n as usize);
801 }
802
803 if self.opts.incremental.is_some() {
807 return CodegenUnits::Default(256);
808 }
809
810 CodegenUnits::Default(16)
861 }
862
863 pub fn teach(&self, code: ErrCode) -> bool {
864 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
865 }
866
867 pub fn edition(&self) -> Edition {
868 self.opts.edition
869 }
870
871 pub fn link_dead_code(&self) -> bool {
872 self.opts.cg.link_dead_code.unwrap_or(false)
873 }
874
875 pub fn apple_deployment_target(&self) -> apple::OSVersion {
880 let min = apple::OSVersion::minimum_deployment_target(&self.target);
881 let env_var = apple::deployment_target_env_var(&self.target.os);
882
883 if let Ok(deployment_target) = env::var(env_var) {
885 match apple::OSVersion::from_str(&deployment_target) {
886 Ok(version) => {
887 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
888 if version < os_min {
893 self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {
894 env_var,
895 version: version.fmt_pretty().to_string(),
896 os_min: os_min.fmt_pretty().to_string(),
897 });
898 }
899
900 version.max(min)
902 }
903 Err(error) => {
904 self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });
905 min
906 }
907 }
908 } else {
909 min
911 }
912 }
913
914 pub fn sanitizers(&self) -> SanitizerSet {
915 return self.opts.unstable_opts.sanitizer | self.target.options.default_sanitizers;
916 }
917}
918
919#[allow(rustc::bad_opt_access)]
921fn default_emitter(sopts: &config::Options, source_map: Arc<SourceMap>) -> Box<DynEmitter> {
922 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
923 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
924 let terminal_url = match sopts.unstable_opts.terminal_urls {
925 TerminalUrl::Auto => {
926 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
927 (Ok("truecolor"), Ok("xterm-256color"))
928 if sopts.unstable_features.is_nightly_build() =>
929 {
930 TerminalUrl::Yes
931 }
932 _ => TerminalUrl::No,
933 }
934 }
935 t => t,
936 };
937
938 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
939
940 match sopts.error_format {
941 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
942 HumanReadableErrorType { short, unicode } => {
943 let emitter = AnnotateSnippetEmitter::new(stderr_destination(color_config))
944 .sm(source_map)
945 .short_message(short)
946 .diagnostic_width(sopts.diagnostic_width)
947 .macro_backtrace(macro_backtrace)
948 .track_diagnostics(track_diagnostics)
949 .terminal_url(terminal_url)
950 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
951 .ignored_directories_in_source_blocks(
952 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
953 );
954 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
955 }
956 },
957 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
958 JsonEmitter::new(
959 Box::new(io::BufWriter::new(io::stderr())),
960 source_map,
961 pretty,
962 json_rendered,
963 color_config,
964 )
965 .ui_testing(sopts.unstable_opts.ui_testing)
966 .ignored_directories_in_source_blocks(
967 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
968 )
969 .diagnostic_width(sopts.diagnostic_width)
970 .macro_backtrace(macro_backtrace)
971 .track_diagnostics(track_diagnostics)
972 .terminal_url(terminal_url),
973 ),
974 }
975}
976
977#[allow(rustc::bad_opt_access)]
979pub fn build_session(
980 sopts: config::Options,
981 io: CompilerIO,
982 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
983 target: Target,
984 cfg_version: &'static str,
985 ice_file: Option<PathBuf>,
986 using_internal_features: &'static AtomicBool,
987) -> Session {
988 let warnings_allow = sopts
992 .lint_opts
993 .iter()
994 .rfind(|&(key, _)| *key == "warnings")
995 .is_some_and(|&(_, level)| level == lint::Allow);
996 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
997 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
998
999 let source_map = rustc_span::source_map::get_source_map().unwrap();
1000 let emitter = default_emitter(&sopts, Arc::clone(&source_map));
1001
1002 let mut dcx =
1003 DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));
1004 if let Some(ice_file) = ice_file {
1005 dcx = dcx.with_ice_file(ice_file);
1006 }
1007
1008 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1009 let (host, target_warnings) =
1010 Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)
1011 .unwrap_or_else(|e| {
1012 dcx.handle().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Error loading host specification: {0}",
e))
})format!("Error loading host specification: {e}"))
1013 });
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 =
1046 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1047 let target_tlib_path = if host_triple == target_triple {
1048 Arc::clone(&host_tlib_path)
1051 } else {
1052 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1053 };
1054
1055 let prof = SelfProfilerRef::new(
1056 self_profiler,
1057 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1058 );
1059
1060 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1061 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1062 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1063 _ => CtfeBacktrace::Disabled,
1064 });
1065
1066 let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1067 let target_filesearch =
1068 filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1069 let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1070
1071 let invocation_temp = sopts
1072 .incremental
1073 .as_ref()
1074 .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
1075
1076 let timings = TimingSectionHandler::new(sopts.json_timings);
1077
1078 let sess = Session {
1079 target,
1080 host,
1081 opts: sopts,
1082 target_tlib_path,
1083 psess,
1084 io,
1085 incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1086 prof,
1087 timings,
1088 code_stats: Default::default(),
1089 lint_store: None,
1090 driver_lint_caps,
1091 ctfe_backtrace,
1092 miri_unleashed_features: Lock::new(Default::default()),
1093 asm_arch,
1094 target_features: Default::default(),
1095 unstable_target_features: Default::default(),
1096 cfg_version,
1097 using_internal_features,
1098 target_filesearch,
1099 host_filesearch,
1100 invocation_temp,
1101 replaced_intrinsics: FxHashSet::default(), thin_lto_supported: true, mir_opt_bisect_eval_count: AtomicUsize::new(0),
1104 used_features: Lock::default(),
1105 };
1106
1107 validate_commandline_args_with_session_available(&sess);
1108
1109 sess
1110}
1111
1112#[allow(rustc::bad_opt_access)]
1118fn validate_commandline_args_with_session_available(sess: &Session) {
1119 if sess.opts.cg.linker_plugin_lto.enabled()
1127 && sess.opts.cg.prefer_dynamic
1128 && sess.target.is_like_windows
1129 {
1130 sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1131 }
1132
1133 if let Some(ref path) = sess.opts.cg.profile_use {
1136 if !path.exists() {
1137 sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1138 }
1139 }
1140
1141 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1143 if !path.exists() {
1144 sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1145 }
1146 }
1147
1148 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1150 if sess.target.requires_uwtable && !include_uwtables {
1151 sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1152 }
1153 }
1154
1155 let supported_sanitizers = sess.target.options.supported_sanitizers;
1157 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1158 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1161 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1162 }
1163 match unsupported_sanitizers.into_iter().count() {
1164 0 => {}
1165 1 => {
1166 sess.dcx()
1167 .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1168 }
1169 _ => {
1170 sess.dcx().emit_err(errors::SanitizersNotSupported {
1171 us: unsupported_sanitizers.to_string(),
1172 });
1173 }
1174 }
1175
1176 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1178 sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1179 first: first.to_string(),
1180 second: second.to_string(),
1181 });
1182 }
1183
1184 if sess.crt_static(None)
1186 && !sess.opts.unstable_opts.sanitizer.is_empty()
1187 && !sess.target.is_like_msvc
1188 {
1189 sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1190 }
1191
1192 if sess.is_sanitizer_cfi_enabled()
1194 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1195 {
1196 sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1197 }
1198
1199 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1201 sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1202 }
1203
1204 if sess.is_sanitizer_cfi_enabled()
1206 && sess.lto() == config::Lto::Fat
1207 && (sess.codegen_units().as_usize() != 1)
1208 {
1209 sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1210 }
1211
1212 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1214 if !sess.is_sanitizer_cfi_enabled() {
1215 sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1216 }
1217 }
1218
1219 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1221 sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);
1222 }
1223
1224 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1226 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1227 sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1228 }
1229 }
1230
1231 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1233 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1234 sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1235 }
1236 }
1237
1238 if sess.is_split_lto_unit_enabled()
1240 && !(sess.lto() == config::Lto::Fat
1241 || sess.lto() == config::Lto::Thin
1242 || sess.opts.cg.linker_plugin_lto.enabled())
1243 {
1244 sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1245 }
1246
1247 if sess.lto() != config::Lto::Fat {
1249 if sess.opts.unstable_opts.virtual_function_elimination {
1250 sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1251 }
1252 }
1253
1254 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1255 if !sess.target.options.supports_stack_protector {
1256 sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1257 stack_protector: sess.opts.unstable_opts.stack_protector,
1258 target_triple: &sess.opts.target_triple,
1259 });
1260 }
1261 }
1262
1263 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1264 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1265 sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1266 target_triple: &sess.opts.target_triple,
1267 })
1268 }
1269 }
1270
1271 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1272 sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1273 }
1274
1275 if let Some(dwarf_version) =
1276 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1277 {
1278 if dwarf_version < 2 || dwarf_version > 5 {
1280 sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1281 }
1282 }
1283
1284 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1285 && !sess.opts.unstable_opts.unstable_options
1286 {
1287 sess.dcx()
1288 .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1289 }
1290
1291 if sess.opts.unstable_opts.embed_source {
1292 let dwarf_version = sess.dwarf_version();
1293
1294 if dwarf_version < 5 {
1295 sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1296 }
1297
1298 if sess.opts.debuginfo == DebugInfo::None {
1299 sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1300 }
1301 }
1302
1303 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1304 sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1305 }
1306
1307 if let Some(flavor) = sess.opts.cg.linker_flavor
1308 && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1309 {
1310 let flavor = flavor.desc();
1311 sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1312 }
1313
1314 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1315 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) {
1316 sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1317 }
1318 }
1319
1320 if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1321 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) {
1322 sess.dcx().emit_err(errors::IndirectBranchCsPrefixRequiresX86OrX8664);
1323 }
1324 }
1325
1326 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1327 if regparm > 3 {
1328 sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1329 }
1330 if sess.target.arch != Arch::X86 {
1331 sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1332 }
1333 }
1334 if sess.opts.unstable_opts.reg_struct_return {
1335 if sess.target.arch != Arch::X86 {
1336 sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1337 }
1338 }
1339
1340 match sess.opts.unstable_opts.function_return {
1344 FunctionReturn::Keep => (),
1345 FunctionReturn::ThunkExtern => {
1346 if let Some(code_model) = sess.code_model()
1349 && code_model == CodeModel::Large
1350 {
1351 sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1352 }
1353 }
1354 }
1355
1356 if sess.opts.cg.soft_float {
1357 if sess.target.arch == Arch::Arm {
1358 sess.dcx().emit_warn(errors::SoftFloatDeprecated);
1359 } else {
1360 sess.dcx().emit_warn(errors::SoftFloatIgnored);
1363 }
1364 }
1365}
1366
1367#[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)]
1369enum IncrCompSession {
1370 NotInitialized,
1373 Active { session_directory: PathBuf, _lock_file: flock::Lock },
1378 Finalized { session_directory: PathBuf },
1381 InvalidBecauseOfErrors { session_directory: PathBuf },
1385}
1386
1387pub struct EarlyDiagCtxt {
1389 dcx: DiagCtxt,
1390}
1391
1392impl EarlyDiagCtxt {
1393 pub fn new(output: ErrorOutputType) -> Self {
1394 let emitter = mk_emitter(output);
1395 Self { dcx: DiagCtxt::new(emitter) }
1396 }
1397
1398 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1401 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());
1402
1403 let emitter = mk_emitter(output);
1404 self.dcx = DiagCtxt::new(emitter);
1405 }
1406
1407 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1408 self.dcx.handle().note(msg)
1409 }
1410
1411 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1412 self.dcx.handle().struct_help(msg).emit()
1413 }
1414
1415 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1416 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1417 self.dcx.handle().err(msg)
1418 }
1419
1420 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1421 self.dcx.handle().fatal(msg)
1422 }
1423
1424 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1425 self.dcx.handle().struct_fatal(msg)
1426 }
1427
1428 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1429 self.dcx.handle().warn(msg)
1430 }
1431
1432 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1433 self.dcx.handle().struct_warn(msg)
1434 }
1435}
1436
1437fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1438 let emitter: Box<DynEmitter> = match output {
1439 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1440 HumanReadableErrorType { short, unicode } => Box::new(
1441 AnnotateSnippetEmitter::new(stderr_destination(color_config))
1442 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1443 .short_message(short),
1444 ),
1445 },
1446 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1447 Box::new(JsonEmitter::new(
1448 Box::new(io::BufWriter::new(io::stderr())),
1449 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1450 pretty,
1451 json_rendered,
1452 color_config,
1453 ))
1454 }
1455 };
1456 emitter
1457}