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
171#[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)]
172pub enum CodegenUnits {
173 User(usize),
176
177 Default(usize),
181}
182
183impl CodegenUnits {
184 pub fn as_usize(self) -> usize {
185 match self {
186 CodegenUnits::User(n) => n,
187 CodegenUnits::Default(n) => n,
188 }
189 }
190}
191
192pub struct LintGroup {
193 pub name: &'static str,
194 pub lints: Vec<LintId>,
195 pub is_externally_loaded: bool,
196}
197
198impl Session {
199 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
200 self.miri_unleashed_features.lock().push((span, feature_gate));
201 }
202
203 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
204 Some(
205 self.source_map()
206 .path_mapping()
207 .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),
208 )
209 }
210
211 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
212 let mut guar = None;
213 let unleashed_features = self.miri_unleashed_features.lock();
214 if !unleashed_features.is_empty() {
215 let mut must_err = false;
216 self.dcx().emit_warn(errors::SkippingConstChecks {
218 unleashed_features: unleashed_features
219 .iter()
220 .map(|(span, gate)| {
221 gate.map(|gate| {
222 must_err = true;
223 errors::UnleashedFeatureHelp::Named { span: *span, gate }
224 })
225 .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })
226 })
227 .collect(),
228 });
229
230 if must_err && self.dcx().has_errors().is_none() {
232 guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));
234 }
235 }
236 guar
237 }
238
239 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
241 let mut guar = None;
242 guar = guar.or(self.check_miri_unleashed_features());
243 guar = guar.or(self.dcx().emit_stashed_diagnostics());
244 self.dcx().print_error_count();
245 if self.opts.json_future_incompat {
246 self.dcx().emit_future_breakage_report();
247 }
248 guar
249 }
250
251 pub fn is_test_crate(&self) -> bool {
253 self.opts.test
254 }
255
256 #[track_caller]
258 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
259 let mut err = self.dcx().create_err(err);
260 if err.code.is_none() {
261 err.code(E0658);
262 }
263 add_feature_diagnostics(&mut err, self, feature);
264 err
265 }
266
267 pub fn record_trimmed_def_paths(&self) {
270 if self.opts.unstable_opts.print_type_sizes
271 || self.opts.unstable_opts.query_dep_graph
272 || self.opts.unstable_opts.dump_mir.is_some()
273 || self.opts.unstable_opts.unpretty.is_some()
274 || self.prof.is_args_recording_enabled()
275 || self.opts.output_types.contains_key(&OutputType::Mir)
276 || std::env::var_os("RUSTC_LOG").is_some()
277 {
278 return;
279 }
280
281 self.dcx().set_must_produce_diag()
282 }
283
284 #[inline]
285 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
286 self.psess.dcx()
287 }
288
289 #[inline]
290 pub fn source_map(&self) -> &SourceMap {
291 self.psess.source_map()
292 }
293
294 pub fn enable_internal_lints(&self) -> bool {
298 self.unstable_options() && !self.opts.actually_rustdoc
299 }
300
301 pub fn instrument_coverage(&self) -> bool {
302 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
303 }
304
305 pub fn instrument_coverage_branch(&self) -> bool {
306 self.instrument_coverage()
307 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
308 }
309
310 pub fn instrument_coverage_condition(&self) -> bool {
311 self.instrument_coverage()
312 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
313 }
314
315 pub fn coverage_options(&self) -> &CoverageOptions {
319 &self.opts.unstable_opts.coverage_options
320 }
321
322 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
323 self.sanitizers().contains(SanitizerSet::CFI)
324 }
325
326 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
327 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
328 }
329
330 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
331 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
332 }
333
334 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
335 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
336 }
337
338 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
339 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
340 }
341
342 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
343 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
344 }
345
346 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
347 self.sanitizers().contains(SanitizerSet::KCFI)
348 }
349
350 pub fn is_split_lto_unit_enabled(&self) -> bool {
351 self.opts.unstable_opts.split_lto_unit == Some(true)
352 }
353
354 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
356 if !self.target.crt_static_respected {
357 return self.target.crt_static_default;
359 }
360
361 let requested_features = self.opts.cg.target_feature.split(',');
362 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
363 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
364
365 #[allow(rustc::bad_opt_access)]
367 if found_positive || found_negative {
368 found_positive
369 } else if crate_type == Some(CrateType::ProcMacro)
370 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
371 {
372 false
376 } else {
377 self.target.crt_static_default
378 }
379 }
380
381 pub fn is_wasi_reactor(&self) -> bool {
382 self.target.options.os == Os::Wasi
383 && #[allow(non_exhaustive_omitted_patterns)] match self.opts.unstable_opts.wasi_exec_model
{
Some(config::WasiExecModel::Reactor) => true,
_ => false,
}matches!(
384 self.opts.unstable_opts.wasi_exec_model,
385 Some(config::WasiExecModel::Reactor)
386 )
387 }
388
389 pub fn target_can_use_split_dwarf(&self) -> bool {
391 self.target.debuginfo_kind == DebuginfoKind::Dwarf
392 }
393
394 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
395 ::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())
396 }
397
398 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
399 &self.target_filesearch
400 }
401 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
402 &self.host_filesearch
403 }
404
405 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
409 let search_paths = self
410 .opts
411 .sysroot
412 .all_paths()
413 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
414
415 if self_contained {
416 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
420 } else {
421 search_paths.collect()
422 }
423 }
424
425 pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
426 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
427
428 if let IncrCompSession::NotInitialized = *incr_comp_session {
429 } else {
430 {
::core::panicking::panic_fmt(format_args!("Trying to initialize IncrCompSession `{0:?}`",
*incr_comp_session));
}panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
431 }
432
433 *incr_comp_session =
434 IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
435 }
436
437 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
438 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
439
440 if let IncrCompSession::Active { .. } = *incr_comp_session {
441 } else {
442 {
::core::panicking::panic_fmt(format_args!("trying to finalize `IncrCompSession` `{0:?}`",
*incr_comp_session));
};panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
443 }
444
445 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
447 }
448
449 pub fn mark_incr_comp_session_as_invalid(&self) {
450 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
451
452 let session_directory = match *incr_comp_session {
453 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
454 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
455 _ => {
::core::panicking::panic_fmt(format_args!("trying to invalidate `IncrCompSession` `{0:?}`",
*incr_comp_session));
}panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
456 };
457
458 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
460 }
461
462 pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
463 let incr_comp_session = self.incr_comp_session.borrow();
464 ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
465 IncrCompSession::NotInitialized => {
::core::panicking::panic_fmt(format_args!("trying to get session directory from `IncrCompSession`: {0:?}",
*incr_comp_session));
}panic!(
466 "trying to get session directory from `IncrCompSession`: {:?}",
467 *incr_comp_session,
468 ),
469 IncrCompSession::Active { ref session_directory, .. }
470 | IncrCompSession::Finalized { ref session_directory }
471 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
472 session_directory
473 }
474 })
475 }
476
477 pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
478 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
479 }
480
481 pub fn is_rust_2015(&self) -> bool {
483 self.edition().is_rust_2015()
484 }
485
486 pub fn at_least_rust_2018(&self) -> bool {
488 self.edition().at_least_rust_2018()
489 }
490
491 pub fn at_least_rust_2021(&self) -> bool {
493 self.edition().at_least_rust_2021()
494 }
495
496 pub fn at_least_rust_2024(&self) -> bool {
498 self.edition().at_least_rust_2024()
499 }
500
501 pub fn needs_plt(&self) -> bool {
503 let want_plt = self.target.plt_by_default;
506
507 let dbg_opts = &self.opts.unstable_opts;
508
509 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
510
511 let full_relro = RelroLevel::Full == relro_level;
515
516 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
519 }
520
521 pub fn emit_lifetime_markers(&self) -> bool {
523 self.opts.optimize != config::OptLevel::No
524 || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
528 }
529
530 pub fn diagnostic_width(&self) -> usize {
531 let default_column_width = 140;
532 if let Some(width) = self.opts.diagnostic_width {
533 width
534 } else if self.opts.unstable_opts.ui_testing {
535 default_column_width
536 } else {
537 termize::dimensions().map_or(default_column_width, |(w, _)| w)
538 }
539 }
540
541 pub fn default_visibility(&self) -> SymbolVisibility {
543 self.opts
544 .unstable_opts
545 .default_visibility
546 .or(self.target.options.default_visibility)
547 .unwrap_or(SymbolVisibility::Interposable)
548 }
549
550 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
551 if verbatim {
552 ("", "")
553 } else {
554 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
555 }
556 }
557
558 pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
559 match self.lint_store {
560 Some(ref lint_store) => lint_store.lint_groups_iter(),
561 None => Box::new(std::iter::empty()),
562 }
563 }
564}
565
566#[allow(rustc::bad_opt_access)]
568impl Session {
569 pub fn verbose_internals(&self) -> bool {
570 self.opts.unstable_opts.verbose_internals
571 }
572
573 pub fn print_llvm_stats(&self) -> bool {
574 self.opts.unstable_opts.print_codegen_stats
575 }
576
577 pub fn verify_llvm_ir(&self) -> bool {
578 self.opts.unstable_opts.verify_llvm_ir || ::core::option::Option::None::<&'static str>option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
579 }
580
581 pub fn binary_dep_depinfo(&self) -> bool {
582 self.opts.unstable_opts.binary_dep_depinfo
583 }
584
585 pub fn mir_opt_level(&self) -> usize {
586 self.opts
587 .unstable_opts
588 .mir_opt_level
589 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
590 }
591
592 pub fn lto(&self) -> config::Lto {
594 if self.target.requires_lto {
596 return config::Lto::Fat;
597 }
598
599 match self.opts.cg.lto {
603 config::LtoCli::Unspecified => {
604 }
607 config::LtoCli::No => {
608 return config::Lto::No;
610 }
611 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
612 return config::Lto::Fat;
614 }
615 config::LtoCli::Thin => {
616 if !self.thin_lto_supported {
618 self.dcx().emit_warn(errors::ThinLtoNotSupportedByBackend);
620 return config::Lto::No;
621 }
622 return config::Lto::Thin;
623 }
624 }
625
626 if !self.thin_lto_supported {
627 return config::Lto::No;
628 }
629
630 if self.opts.cli_forced_local_thinlto_off {
639 return config::Lto::No;
640 }
641
642 if let Some(enabled) = self.opts.unstable_opts.thinlto {
645 if enabled {
646 return config::Lto::ThinLocal;
647 } else {
648 return config::Lto::No;
649 }
650 }
651
652 if self.codegen_units().as_usize() == 1 {
655 return config::Lto::No;
656 }
657
658 match self.opts.optimize {
661 config::OptLevel::No => config::Lto::No,
662 _ => config::Lto::ThinLocal,
663 }
664 }
665
666 pub fn panic_strategy(&self) -> PanicStrategy {
669 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
670 }
671
672 pub fn fewer_names(&self) -> bool {
673 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
674 fewer_names
675 } else {
676 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
677 || self.opts.output_types.contains_key(&OutputType::Bitcode)
678 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
680 !more_names
681 }
682 }
683
684 pub fn unstable_options(&self) -> bool {
685 self.opts.unstable_opts.unstable_options
686 }
687
688 pub fn is_nightly_build(&self) -> bool {
689 self.opts.unstable_features.is_nightly_build()
690 }
691
692 pub fn overflow_checks(&self) -> bool {
693 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
694 }
695
696 pub fn ub_checks(&self) -> bool {
697 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
698 }
699
700 pub fn contract_checks(&self) -> bool {
701 self.opts.unstable_opts.contract_checks.unwrap_or(false)
702 }
703
704 pub fn relocation_model(&self) -> RelocModel {
705 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
706 }
707
708 pub fn code_model(&self) -> Option<CodeModel> {
709 self.opts.cg.code_model.or(self.target.code_model)
710 }
711
712 pub fn tls_model(&self) -> TlsModel {
713 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
714 }
715
716 pub fn direct_access_external_data(&self) -> Option<bool> {
717 self.opts
718 .unstable_opts
719 .direct_access_external_data
720 .or(self.target.direct_access_external_data)
721 }
722
723 pub fn split_debuginfo(&self) -> SplitDebuginfo {
724 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
725 }
726
727 pub fn dwarf_version(&self) -> u32 {
729 self.opts
730 .cg
731 .dwarf_version
732 .or(self.opts.unstable_opts.dwarf_version)
733 .unwrap_or(self.target.default_dwarf_version)
734 }
735
736 pub fn stack_protector(&self) -> StackProtector {
737 if self.target.options.supports_stack_protector {
738 self.opts.unstable_opts.stack_protector
739 } else {
740 StackProtector::None
741 }
742 }
743
744 pub fn must_emit_unwind_tables(&self) -> bool {
745 self.target.requires_uwtable
774 || self
775 .opts
776 .cg
777 .force_unwind_tables
778 .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
779 }
780
781 #[inline]
784 pub fn threads(&self) -> usize {
785 self.opts.unstable_opts.threads
786 }
787
788 pub fn codegen_units(&self) -> CodegenUnits {
791 if let Some(n) = self.opts.cli_forced_codegen_units {
792 return CodegenUnits::User(n);
793 }
794 if let Some(n) = self.target.default_codegen_units {
795 return CodegenUnits::Default(n as usize);
796 }
797
798 if self.opts.incremental.is_some() {
802 return CodegenUnits::Default(256);
803 }
804
805 CodegenUnits::Default(16)
856 }
857
858 pub fn teach(&self, code: ErrCode) -> bool {
859 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
860 }
861
862 pub fn edition(&self) -> Edition {
863 self.opts.edition
864 }
865
866 pub fn link_dead_code(&self) -> bool {
867 self.opts.cg.link_dead_code.unwrap_or(false)
868 }
869
870 pub fn apple_deployment_target(&self) -> apple::OSVersion {
875 let min = apple::OSVersion::minimum_deployment_target(&self.target);
876 let env_var = apple::deployment_target_env_var(&self.target.os);
877
878 if let Ok(deployment_target) = env::var(env_var) {
880 match apple::OSVersion::from_str(&deployment_target) {
881 Ok(version) => {
882 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
883 if version < os_min {
888 self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {
889 env_var,
890 version: version.fmt_pretty().to_string(),
891 os_min: os_min.fmt_pretty().to_string(),
892 });
893 }
894
895 version.max(min)
897 }
898 Err(error) => {
899 self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });
900 min
901 }
902 }
903 } else {
904 min
906 }
907 }
908
909 pub fn sanitizers(&self) -> SanitizerSet {
910 return self.opts.unstable_opts.sanitizer | self.target.options.default_sanitizers;
911 }
912}
913
914#[allow(rustc::bad_opt_access)]
916fn default_emitter(sopts: &config::Options, source_map: Arc<SourceMap>) -> Box<DynEmitter> {
917 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
918 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
919 let terminal_url = match sopts.unstable_opts.terminal_urls {
920 TerminalUrl::Auto => {
921 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
922 (Ok("truecolor"), Ok("xterm-256color"))
923 if sopts.unstable_features.is_nightly_build() =>
924 {
925 TerminalUrl::Yes
926 }
927 _ => TerminalUrl::No,
928 }
929 }
930 t => t,
931 };
932
933 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
934
935 match sopts.error_format {
936 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
937 HumanReadableErrorType { short, unicode } => {
938 let emitter = AnnotateSnippetEmitter::new(stderr_destination(color_config))
939 .sm(source_map)
940 .short_message(short)
941 .diagnostic_width(sopts.diagnostic_width)
942 .macro_backtrace(macro_backtrace)
943 .track_diagnostics(track_diagnostics)
944 .terminal_url(terminal_url)
945 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
946 .ignored_directories_in_source_blocks(
947 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
948 );
949 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
950 }
951 },
952 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
953 JsonEmitter::new(
954 Box::new(io::BufWriter::new(io::stderr())),
955 source_map,
956 pretty,
957 json_rendered,
958 color_config,
959 )
960 .ui_testing(sopts.unstable_opts.ui_testing)
961 .ignored_directories_in_source_blocks(
962 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
963 )
964 .diagnostic_width(sopts.diagnostic_width)
965 .macro_backtrace(macro_backtrace)
966 .track_diagnostics(track_diagnostics)
967 .terminal_url(terminal_url),
968 ),
969 }
970}
971
972#[allow(rustc::bad_opt_access)]
974pub fn build_session(
975 sopts: config::Options,
976 io: CompilerIO,
977 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
978 target: Target,
979 cfg_version: &'static str,
980 ice_file: Option<PathBuf>,
981 using_internal_features: &'static AtomicBool,
982) -> Session {
983 let warnings_allow = sopts
987 .lint_opts
988 .iter()
989 .rfind(|&(key, _)| *key == "warnings")
990 .is_some_and(|&(_, level)| level == lint::Allow);
991 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
992 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
993
994 let source_map = rustc_span::source_map::get_source_map().unwrap();
995 let emitter = default_emitter(&sopts, Arc::clone(&source_map));
996
997 let mut dcx =
998 DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));
999 if let Some(ice_file) = ice_file {
1000 dcx = dcx.with_ice_file(ice_file);
1001 }
1002
1003 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1004 let (host, target_warnings) =
1005 Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)
1006 .unwrap_or_else(|e| {
1007 dcx.handle().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Error loading host specification: {0}",
e))
})format!("Error loading host specification: {e}"))
1008 });
1009 for warning in target_warnings.warning_messages() {
1010 dcx.handle().warn(warning)
1011 }
1012
1013 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1014 {
1015 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1016
1017 let profiler = SelfProfiler::new(
1018 directory,
1019 sopts.crate_name.as_deref(),
1020 sopts.unstable_opts.self_profile_events.as_deref(),
1021 &sopts.unstable_opts.self_profile_counter,
1022 );
1023 match profiler {
1024 Ok(profiler) => Some(Arc::new(profiler)),
1025 Err(e) => {
1026 dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1027 None
1028 }
1029 }
1030 } else {
1031 None
1032 };
1033
1034 let mut psess = ParseSess::with_dcx(dcx, source_map);
1035 psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1036
1037 let host_triple = config::host_tuple();
1038 let target_triple = sopts.target_triple.tuple();
1039 let host_tlib_path =
1041 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1042 let target_tlib_path = if host_triple == target_triple {
1043 Arc::clone(&host_tlib_path)
1046 } else {
1047 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1048 };
1049
1050 let prof = SelfProfilerRef::new(
1051 self_profiler,
1052 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1053 );
1054
1055 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1056 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1057 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1058 _ => CtfeBacktrace::Disabled,
1059 });
1060
1061 let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1062 let target_filesearch =
1063 filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1064 let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1065
1066 let invocation_temp = sopts
1067 .incremental
1068 .as_ref()
1069 .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
1070
1071 let timings = TimingSectionHandler::new(sopts.json_timings);
1072
1073 let sess = Session {
1074 target,
1075 host,
1076 opts: sopts,
1077 target_tlib_path,
1078 psess,
1079 io,
1080 incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1081 prof,
1082 timings,
1083 code_stats: Default::default(),
1084 lint_store: None,
1085 driver_lint_caps,
1086 ctfe_backtrace,
1087 miri_unleashed_features: Lock::new(Default::default()),
1088 asm_arch,
1089 target_features: Default::default(),
1090 unstable_target_features: Default::default(),
1091 cfg_version,
1092 using_internal_features,
1093 target_filesearch,
1094 host_filesearch,
1095 invocation_temp,
1096 replaced_intrinsics: FxHashSet::default(), thin_lto_supported: true, mir_opt_bisect_eval_count: AtomicUsize::new(0),
1099 };
1100
1101 validate_commandline_args_with_session_available(&sess);
1102
1103 sess
1104}
1105
1106#[allow(rustc::bad_opt_access)]
1112fn validate_commandline_args_with_session_available(sess: &Session) {
1113 if sess.opts.cg.linker_plugin_lto.enabled()
1121 && sess.opts.cg.prefer_dynamic
1122 && sess.target.is_like_windows
1123 {
1124 sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1125 }
1126
1127 if let Some(ref path) = sess.opts.cg.profile_use {
1130 if !path.exists() {
1131 sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1132 }
1133 }
1134
1135 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1137 if !path.exists() {
1138 sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1139 }
1140 }
1141
1142 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1144 if sess.target.requires_uwtable && !include_uwtables {
1145 sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1146 }
1147 }
1148
1149 let supported_sanitizers = sess.target.options.supported_sanitizers;
1151 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1152 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1155 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1156 }
1157 match unsupported_sanitizers.into_iter().count() {
1158 0 => {}
1159 1 => {
1160 sess.dcx()
1161 .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1162 }
1163 _ => {
1164 sess.dcx().emit_err(errors::SanitizersNotSupported {
1165 us: unsupported_sanitizers.to_string(),
1166 });
1167 }
1168 }
1169
1170 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1172 sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1173 first: first.to_string(),
1174 second: second.to_string(),
1175 });
1176 }
1177
1178 if sess.crt_static(None)
1180 && !sess.opts.unstable_opts.sanitizer.is_empty()
1181 && !sess.target.is_like_msvc
1182 {
1183 sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1184 }
1185
1186 if sess.is_sanitizer_cfi_enabled()
1188 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1189 {
1190 sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1191 }
1192
1193 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1195 sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1196 }
1197
1198 if sess.is_sanitizer_cfi_enabled()
1200 && sess.lto() == config::Lto::Fat
1201 && (sess.codegen_units().as_usize() != 1)
1202 {
1203 sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1204 }
1205
1206 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1208 if !sess.is_sanitizer_cfi_enabled() {
1209 sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1210 }
1211 }
1212
1213 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1215 sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);
1216 }
1217
1218 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1220 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1221 sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1222 }
1223 }
1224
1225 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1227 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1228 sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1229 }
1230 }
1231
1232 if sess.is_split_lto_unit_enabled()
1234 && !(sess.lto() == config::Lto::Fat
1235 || sess.lto() == config::Lto::Thin
1236 || sess.opts.cg.linker_plugin_lto.enabled())
1237 {
1238 sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1239 }
1240
1241 if sess.lto() != config::Lto::Fat {
1243 if sess.opts.unstable_opts.virtual_function_elimination {
1244 sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1245 }
1246 }
1247
1248 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1249 if !sess.target.options.supports_stack_protector {
1250 sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1251 stack_protector: sess.opts.unstable_opts.stack_protector,
1252 target_triple: &sess.opts.target_triple,
1253 });
1254 }
1255 }
1256
1257 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1258 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1259 sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1260 target_triple: &sess.opts.target_triple,
1261 })
1262 }
1263 }
1264
1265 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1266 sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1267 }
1268
1269 if let Some(dwarf_version) =
1270 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1271 {
1272 if dwarf_version < 2 || dwarf_version > 5 {
1274 sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1275 }
1276 }
1277
1278 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1279 && !sess.opts.unstable_opts.unstable_options
1280 {
1281 sess.dcx()
1282 .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1283 }
1284
1285 if sess.opts.unstable_opts.embed_source {
1286 let dwarf_version = sess.dwarf_version();
1287
1288 if dwarf_version < 5 {
1289 sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1290 }
1291
1292 if sess.opts.debuginfo == DebugInfo::None {
1293 sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1294 }
1295 }
1296
1297 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1298 sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1299 }
1300
1301 if let Some(flavor) = sess.opts.cg.linker_flavor
1302 && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1303 {
1304 let flavor = flavor.desc();
1305 sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1306 }
1307
1308 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1309 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) {
1310 sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1311 }
1312 }
1313
1314 if sess.opts.unstable_opts.indirect_branch_cs_prefix {
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::IndirectBranchCsPrefixRequiresX86OrX8664);
1317 }
1318 }
1319
1320 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1321 if regparm > 3 {
1322 sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1323 }
1324 if sess.target.arch != Arch::X86 {
1325 sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1326 }
1327 }
1328 if sess.opts.unstable_opts.reg_struct_return {
1329 if sess.target.arch != Arch::X86 {
1330 sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1331 }
1332 }
1333
1334 match sess.opts.unstable_opts.function_return {
1338 FunctionReturn::Keep => (),
1339 FunctionReturn::ThunkExtern => {
1340 if let Some(code_model) = sess.code_model()
1343 && code_model == CodeModel::Large
1344 {
1345 sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1346 }
1347 }
1348 }
1349
1350 if sess.opts.cg.soft_float {
1351 if sess.target.arch == Arch::Arm {
1352 sess.dcx().emit_warn(errors::SoftFloatDeprecated);
1353 } else {
1354 sess.dcx().emit_warn(errors::SoftFloatIgnored);
1357 }
1358 }
1359}
1360
1361#[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)]
1363enum IncrCompSession {
1364 NotInitialized,
1367 Active { session_directory: PathBuf, _lock_file: flock::Lock },
1372 Finalized { session_directory: PathBuf },
1375 InvalidBecauseOfErrors { session_directory: PathBuf },
1379}
1380
1381pub struct EarlyDiagCtxt {
1383 dcx: DiagCtxt,
1384}
1385
1386impl EarlyDiagCtxt {
1387 pub fn new(output: ErrorOutputType) -> Self {
1388 let emitter = mk_emitter(output);
1389 Self { dcx: DiagCtxt::new(emitter) }
1390 }
1391
1392 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1395 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());
1396
1397 let emitter = mk_emitter(output);
1398 self.dcx = DiagCtxt::new(emitter);
1399 }
1400
1401 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1402 self.dcx.handle().note(msg)
1403 }
1404
1405 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1406 self.dcx.handle().struct_help(msg).emit()
1407 }
1408
1409 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1410 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1411 self.dcx.handle().err(msg)
1412 }
1413
1414 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1415 self.dcx.handle().fatal(msg)
1416 }
1417
1418 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1419 self.dcx.handle().struct_fatal(msg)
1420 }
1421
1422 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1423 self.dcx.handle().warn(msg)
1424 }
1425
1426 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1427 self.dcx.handle().struct_warn(msg)
1428 }
1429}
1430
1431fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1432 let emitter: Box<DynEmitter> = match output {
1433 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1434 HumanReadableErrorType { short, unicode } => Box::new(
1435 AnnotateSnippetEmitter::new(stderr_destination(color_config))
1436 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1437 .short_message(short),
1438 ),
1439 },
1440 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1441 Box::new(JsonEmitter::new(
1442 Box::new(io::BufWriter::new(io::stderr())),
1443 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1444 pretty,
1445 json_rendered,
1446 color_config,
1447 ))
1448 }
1449 };
1450 emitter
1451}