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