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