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 rustc_data_structures::flock;
9use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
10use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
11use rustc_data_structures::sync::{
12 AppendOnlyVec, DynSend, DynSync, Lock, MappedReadGuard, ReadGuard, RwLock,
13};
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_feature::UnstableFeatures;
24use rustc_hir::limit::Limit;
25use rustc_macros::StableHash;
26pub use rustc_span::def_id::StableCrateId;
27use rustc_span::edition::Edition;
28use rustc_span::source_map::{FilePathMapping, SourceMap};
29use rustc_span::{RealFileName, Span, Symbol};
30use rustc_target::asm::InlineAsmArch;
31use rustc_target::spec::{
32 Arch, CfgAbi, CodeModel, DebuginfoKind, Os, PanicStrategy, RelocModel, RelroLevel,
33 SanitizerSet, SmallDataThresholdSupport, SplitDebuginfo, StackProtector, SymbolVisibility,
34 Target, TargetTuple, TlsModel, apple,
35};
36
37use crate::code_stats::CodeStats;
38pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
39use crate::config::{
40 self, Cfg, CheckCfg, CoverageLevel, CoverageOptions, CrateType, DebugInfo, ErrorOutputType,
41 FunctionReturn, Input, InstrumentCoverage, InstrumentMcount, OptLevel, OutFileName, OutputType,
42 SwitchWithOptPath,
43};
44use crate::filesearch::FileSearch;
45use crate::lint::LintId;
46use crate::parse::ParseSess;
47use crate::search_paths::SearchPath;
48use crate::{diagnostics, filesearch, lint};
49
50#[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)]
52pub enum CtfeBacktrace {
53 Disabled,
55 Capture,
58 Immediate,
60}
61
62#[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 ::rustc_data_structures::stable_hash::StableHash for Limits {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::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.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
{ __binding_2.stable_hash(__hcx, __hasher); }
{ __binding_3.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash)]
63pub struct Limits {
64 pub recursion_limit: Limit,
67 pub move_size_limit: Limit,
70 pub type_length_limit: Limit,
72 pub pattern_complexity_limit: Limit,
74}
75
76pub struct CompilerIO {
77 pub input: Input,
78 pub output_dir: Option<PathBuf>,
79 pub output_file: Option<OutFileName>,
80 pub temps_dir: Option<PathBuf>,
81}
82
83pub trait DynLintStore: Any + DynSync + DynSend {
84 fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;
86}
87
88pub struct Session {
91 pub target: Target,
92 pub host: Target,
93 pub opts: config::Options,
94 pub target_tlib_path: Arc<SearchPath>,
95 pub psess: ParseSess,
96 pub unstable_features: UnstableFeatures,
97 pub config: Cfg,
98 pub check_config: CheckCfg,
99 proc_macro_quoted_spans: AppendOnlyVec<Span>,
102
103 pub io: CompilerIO,
105
106 incr_comp_session: RwLock<IncrCompSession>,
107
108 pub prof: SelfProfilerRef,
110
111 pub timings: TimingSectionHandler,
113
114 pub code_stats: CodeStats,
116
117 pub lint_store: Option<Arc<dyn DynLintStore>>,
119
120 pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
122
123 pub ctfe_backtrace: Lock<CtfeBacktrace>,
130
131 miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
136
137 pub asm_arch: Option<InlineAsmArch>,
139
140 pub target_features: FxIndexSet<Symbol>,
142
143 pub unstable_target_features: FxIndexSet<Symbol>,
145
146 pub cfg_version: &'static str,
148
149 pub using_internal_features: &'static AtomicBool,
154
155 pub env_depinfo: Lock<FxIndexSet<(Symbol, Option<Symbol>)>>,
157
158 pub file_depinfo: Lock<FxIndexSet<Symbol>>,
160
161 target_filesearch: FileSearch,
162 host_filesearch: FileSearch,
163
164 pub replaced_intrinsics: FxHashSet<Symbol>,
167 pub fallback_intrinsics: FxHashSet<Symbol>,
170
171 pub thin_lto_supported: bool,
173
174 pub mir_opt_bisect_eval_count: AtomicUsize,
179
180 pub used_features: Lock<FxHashMap<Symbol, u32>>,
184
185 pub removed_rustc_main_attr: AtomicBool,
188}
189
190#[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)]
191pub enum CodegenUnits {
192 User(usize),
195
196 Default(usize),
200}
201
202impl CodegenUnits {
203 pub fn as_usize(self) -> usize {
204 match self {
205 CodegenUnits::User(n) => n,
206 CodegenUnits::Default(n) => n,
207 }
208 }
209}
210
211pub struct LintGroup {
212 pub name: &'static str,
213 pub lints: Vec<LintId>,
214 pub is_externally_loaded: bool,
215}
216
217impl Session {
218 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
219 self.miri_unleashed_features.lock().push((span, feature_gate));
220 }
221
222 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
223 Some(
224 self.source_map()
225 .path_mapping()
226 .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),
227 )
228 }
229
230 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
231 let mut guar = None;
232 let unleashed_features = self.miri_unleashed_features.lock();
233 if !unleashed_features.is_empty() {
234 let mut must_err = false;
235 self.dcx().emit_warn(diagnostics::SkippingConstChecks {
237 unleashed_features: unleashed_features
238 .iter()
239 .map(|(span, gate)| {
240 gate.map(|gate| {
241 must_err = true;
242 diagnostics::UnleashedFeatureHelp::Named { span: *span, gate }
243 })
244 .unwrap_or(diagnostics::UnleashedFeatureHelp::Unnamed { span: *span })
245 })
246 .collect(),
247 });
248
249 if must_err && self.dcx().has_errors().is_none() {
251 guar = Some(self.dcx().emit_err(diagnostics::NotCircumventFeature));
253 }
254 }
255 guar
256 }
257
258 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
260 let mut guar = None;
261 guar = guar.or(self.check_miri_unleashed_features());
262 guar = guar.or(self.dcx().emit_stashed_diagnostics());
263 self.dcx().print_error_count();
264 if self.opts.json_future_incompat {
265 self.dcx().emit_future_breakage_report();
266 }
267 guar
268 }
269
270 pub fn is_test_crate(&self) -> bool {
272 self.opts.test
273 }
274
275 #[track_caller]
277 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
278 let mut err = self.dcx().create_err(err);
279 if err.code.is_none() {
280 err.code(E0658);
281 }
282 diagnostics::add_feature_diagnostics(&mut err, self, feature);
283 err
284 }
285
286 pub fn record_trimmed_def_paths(&self) {
289 if self.opts.unstable_opts.print_type_sizes
290 || self.opts.unstable_opts.query_dep_graph
291 || self.opts.unstable_opts.dump_mir.is_some()
292 || self.opts.unstable_opts.unpretty.is_some()
293 || self.prof.is_args_recording_enabled()
294 || self.opts.output_types.contains_key(&OutputType::Mir)
295 || std::env::var_os("RUSTC_LOG").is_some()
296 {
297 return;
298 }
299
300 self.dcx().set_must_produce_diag()
301 }
302
303 #[inline]
304 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
305 self.psess.dcx()
306 }
307
308 #[inline]
309 pub fn source_map(&self) -> &SourceMap {
310 self.psess.source_map()
311 }
312
313 pub fn proc_macro_quoted_spans(&self) -> impl Iterator<Item = (usize, Span)> {
314 self.proc_macro_quoted_spans.iter_enumerated()
317 }
318
319 pub fn save_proc_macro_span(&self, span: Span) -> usize {
320 self.proc_macro_quoted_spans.push(span)
321 }
322
323 pub fn enable_internal_lints(&self) -> bool {
327 self.unstable_options() && !self.opts.actually_rustdoc
328 }
329
330 pub fn instrument_coverage(&self) -> bool {
331 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
332 }
333
334 pub fn instrument_coverage_branch(&self) -> bool {
335 self.instrument_coverage()
336 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
337 }
338
339 pub fn instrument_coverage_condition(&self) -> bool {
340 self.instrument_coverage()
341 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
342 }
343
344 pub fn coverage_options(&self) -> &CoverageOptions {
348 &self.opts.unstable_opts.coverage_options
349 }
350
351 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
352 self.sanitizers().contains(SanitizerSet::CFI)
353 }
354
355 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
356 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
357 }
358
359 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
360 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
361 }
362
363 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
364 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
365 }
366
367 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
368 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
369 }
370
371 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
372 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
373 }
374
375 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
376 self.sanitizers().contains(SanitizerSet::KCFI)
377 }
378
379 pub fn is_split_lto_unit_enabled(&self) -> bool {
380 self.opts.unstable_opts.split_lto_unit == Some(true)
381 }
382
383 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
385 if !self.target.crt_static_respected {
386 return self.target.crt_static_default;
388 }
389
390 let requested_features = self.opts.cg.target_feature.split(',');
391 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
392 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
393
394 #[allow(rustc::bad_opt_access)]
396 if found_positive || found_negative {
397 found_positive
398 } else if crate_type == Some(CrateType::ProcMacro)
399 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
400 {
401 false
405 } else {
406 self.target.crt_static_default
407 }
408 }
409
410 pub fn is_wasi_reactor(&self) -> bool {
411 self.target.options.os == Os::Wasi
412 && #[allow(non_exhaustive_omitted_patterns)] match self.opts.unstable_opts.wasi_exec_model
{
Some(config::WasiExecModel::Reactor) => true,
_ => false,
}matches!(
413 self.opts.unstable_opts.wasi_exec_model,
414 Some(config::WasiExecModel::Reactor)
415 )
416 }
417
418 pub fn target_can_use_split_dwarf(&self) -> bool {
420 self.target.debuginfo_kind == DebuginfoKind::Dwarf
421 }
422
423 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
424 &self.target_filesearch
425 }
426 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
427 &self.host_filesearch
428 }
429
430 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
434 let search_paths = self
435 .opts
436 .sysroot
437 .all_paths()
438 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
439
440 if self_contained {
441 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
445 } else {
446 search_paths.collect()
447 }
448 }
449
450 pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
451 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
452
453 if let IncrCompSession::NotInitialized = *incr_comp_session {
454 } else {
455 {
::core::panicking::panic_fmt(format_args!("Trying to initialize IncrCompSession `{0:?}`",
*incr_comp_session));
}panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
456 }
457
458 *incr_comp_session =
459 IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
460 }
461
462 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
463 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
464
465 if let IncrCompSession::Active { .. } = *incr_comp_session {
466 } else {
467 {
::core::panicking::panic_fmt(format_args!("trying to finalize `IncrCompSession` `{0:?}`",
*incr_comp_session));
};panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
468 }
469
470 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
472 }
473
474 pub fn mark_incr_comp_session_as_invalid(&self) {
475 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
476
477 let session_directory = match *incr_comp_session {
478 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
479 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
480 _ => {
::core::panicking::panic_fmt(format_args!("trying to invalidate `IncrCompSession` `{0:?}`",
*incr_comp_session));
}panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
481 };
482
483 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
485 }
486
487 pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
488 let incr_comp_session = self.incr_comp_session.borrow();
489 ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
490 IncrCompSession::NotInitialized => {
::core::panicking::panic_fmt(format_args!("trying to get session directory from `IncrCompSession`: {0:?}",
*incr_comp_session));
}panic!(
491 "trying to get session directory from `IncrCompSession`: {:?}",
492 *incr_comp_session,
493 ),
494 IncrCompSession::Active { ref session_directory, .. }
495 | IncrCompSession::Finalized { ref session_directory }
496 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
497 session_directory
498 }
499 })
500 }
501
502 pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
503 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
504 }
505
506 pub fn is_rust_2015(&self) -> bool {
508 self.edition().is_rust_2015()
509 }
510
511 pub fn at_least_rust_2018(&self) -> bool {
513 self.edition().at_least_rust_2018()
514 }
515
516 pub fn at_least_rust_2021(&self) -> bool {
518 self.edition().at_least_rust_2021()
519 }
520
521 pub fn at_least_rust_2024(&self) -> bool {
523 self.edition().at_least_rust_2024()
524 }
525
526 pub fn needs_plt(&self) -> bool {
528 let want_plt = self.target.plt_by_default;
531
532 let dbg_opts = &self.opts.unstable_opts;
533
534 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
535
536 let full_relro = RelroLevel::Full == relro_level;
540
541 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
544 }
545
546 pub fn emit_lifetime_markers(&self) -> bool {
548 self.opts.optimize != config::OptLevel::No
549 || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS | SanitizerSet::KERNELHWADDRESS)
556 || self.opts.unstable_opts.codegen_emit_retag.is_some()
558 }
559
560 pub fn diagnostic_width(&self) -> usize {
561 let default_column_width = 140;
562 if let Some(width) = self.opts.diagnostic_width {
563 width
564 } else if self.opts.unstable_opts.ui_testing {
565 default_column_width
566 } else {
567 termize::dimensions().map_or(default_column_width, |(w, _)| w)
568 }
569 }
570
571 pub fn default_visibility(&self) -> SymbolVisibility {
573 self.opts
574 .unstable_opts
575 .default_visibility
576 .or(self.target.options.default_visibility)
577 .unwrap_or(SymbolVisibility::Interposable)
578 }
579
580 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
581 if verbatim {
582 ("", "")
583 } else {
584 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
585 }
586 }
587
588 pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
589 match self.lint_store {
590 Some(ref lint_store) => lint_store.lint_groups_iter(),
591 None => Box::new(std::iter::empty()),
592 }
593 }
594}
595
596#[allow(rustc::bad_opt_access)]
598impl Session {
599 pub fn verbose_internals(&self) -> bool {
600 self.opts.unstable_opts.verbose_internals
601 }
602
603 pub fn print_llvm_stats(&self) -> bool {
604 self.opts.unstable_opts.print_codegen_stats
605 }
606
607 pub fn print_llvm_stats_json(&self) -> Option<&String> {
608 self.opts.unstable_opts.print_codegen_stats_json.as_ref()
609 }
610
611 pub fn verify_llvm_ir(&self) -> bool {
612 self.opts.unstable_opts.verify_llvm_ir || ::core::option::Option::None::<&'static str>option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
613 }
614
615 pub fn binary_dep_depinfo(&self) -> bool {
616 self.opts.unstable_opts.binary_dep_depinfo
617 }
618
619 pub fn mir_opt_level(&self) -> usize {
620 self.opts
621 .unstable_opts
622 .mir_opt_level
623 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
624 }
625
626 pub fn lto(&self) -> config::Lto {
628 if self.target.requires_lto {
630 return config::Lto::Fat;
631 }
632
633 match self.opts.cg.lto {
637 config::LtoCli::Unspecified => {
638 }
641 config::LtoCli::No => {
642 return config::Lto::No;
644 }
645 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
646 return config::Lto::Fat;
648 }
649 config::LtoCli::Thin => {
650 if !self.thin_lto_supported {
652 self.dcx().emit_warn(diagnostics::ThinLtoNotSupportedByBackend);
654 return config::Lto::Fat;
655 }
656 return config::Lto::Thin;
657 }
658 }
659
660 if !self.thin_lto_supported {
661 return config::Lto::No;
662 }
663
664 if self.opts.cli_forced_local_thinlto_off {
673 return config::Lto::No;
674 }
675
676 if let Some(enabled) = self.opts.unstable_opts.thinlto {
679 if enabled {
680 return config::Lto::ThinLocal;
681 } else {
682 return config::Lto::No;
683 }
684 }
685
686 if self.codegen_units().as_usize() == 1 {
689 return config::Lto::No;
690 }
691
692 match self.opts.optimize {
695 config::OptLevel::No => config::Lto::No,
696 _ => config::Lto::ThinLocal,
697 }
698 }
699
700 pub fn panic_strategy(&self) -> PanicStrategy {
703 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
704 }
705
706 pub fn fewer_names(&self) -> bool {
707 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
708 fewer_names
709 } else {
710 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
711 || self.opts.output_types.contains_key(&OutputType::Bitcode)
712 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
714 !more_names
715 }
716 }
717
718 pub fn unstable_options(&self) -> bool {
719 self.opts.unstable_opts.unstable_options
720 }
721
722 pub fn is_nightly_build(&self) -> bool {
723 self.opts.unstable_features.is_nightly_build()
724 }
725
726 pub fn overflow_checks(&self) -> bool {
727 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
728 }
729
730 pub fn ub_checks(&self) -> bool {
731 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
732 }
733
734 pub fn contract_checks(&self) -> bool {
735 self.opts.unstable_opts.contract_checks.unwrap_or(false)
736 }
737
738 pub fn relocation_model(&self) -> RelocModel {
739 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
740 }
741
742 pub fn code_model(&self) -> Option<CodeModel> {
743 self.opts.cg.code_model.or(self.target.code_model)
744 }
745
746 pub fn tls_model(&self) -> TlsModel {
747 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
748 }
749
750 pub fn direct_access_external_data(&self) -> Option<bool> {
751 self.opts
752 .unstable_opts
753 .direct_access_external_data
754 .or(self.target.direct_access_external_data)
755 }
756
757 pub fn split_debuginfo(&self) -> SplitDebuginfo {
758 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
759 }
760
761 pub fn dwarf_version(&self) -> u32 {
763 self.opts
764 .cg
765 .dwarf_version
766 .or(self.opts.unstable_opts.dwarf_version)
767 .unwrap_or(self.target.default_dwarf_version)
768 }
769
770 pub fn stack_protector(&self) -> StackProtector {
771 if self.target.options.supports_stack_protector {
772 self.opts.unstable_opts.stack_protector
773 } else {
774 StackProtector::None
775 }
776 }
777
778 pub fn must_emit_unwind_tables(&self) -> bool {
779 self.target.requires_uwtable
808 || self
809 .opts
810 .cg
811 .force_unwind_tables
812 .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
813 }
814
815 #[inline]
820 pub fn threads(&self) -> Option<usize> {
821 self.opts.unstable_opts.threads
822 }
823
824 pub fn codegen_units(&self) -> CodegenUnits {
827 if let Some(n) = self.opts.cli_forced_codegen_units {
828 return CodegenUnits::User(n);
829 }
830 if let Some(n) = self.target.default_codegen_units {
831 return CodegenUnits::Default(n as usize);
832 }
833
834 if self.opts.incremental.is_some() {
838 return CodegenUnits::Default(256);
839 }
840
841 CodegenUnits::Default(16)
892 }
893
894 pub fn teach(&self, code: ErrCode) -> bool {
895 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
896 }
897
898 pub fn edition(&self) -> Edition {
899 self.opts.edition
900 }
901
902 pub fn link_dead_code(&self) -> bool {
903 self.opts.cg.link_dead_code.unwrap_or(false)
904 }
905
906 pub fn apple_deployment_target(&self) -> apple::OSVersion {
911 let min = apple::OSVersion::minimum_deployment_target(&self.target);
912 let env_var = apple::deployment_target_env_var(&self.target.os);
913
914 if let Ok(deployment_target) = env::var(env_var) {
916 match apple::OSVersion::from_str(&deployment_target) {
917 Ok(version) => {
918 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
919 if version < os_min {
924 self.dcx().emit_warn(diagnostics::AppleDeploymentTarget::TooLow {
925 env_var,
926 version: version.fmt_pretty().to_string(),
927 os_min: os_min.fmt_pretty().to_string(),
928 });
929 }
930
931 version.max(min)
933 }
934 Err(error) => {
935 self.dcx()
936 .emit_err(diagnostics::AppleDeploymentTarget::Invalid { env_var, error });
937 min
938 }
939 }
940 } else {
941 min
943 }
944 }
945
946 pub fn sanitizers(&self) -> SanitizerSet {
947 return self.opts.unstable_opts.sanitizer | self.target.options.default_sanitizers;
948 }
949}
950
951#[allow(rustc::bad_opt_access)]
953fn default_emitter(sopts: &config::Options, source_map: Arc<SourceMap>) -> Box<DynEmitter> {
954 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
955 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
956 let terminal_url = match sopts.unstable_opts.terminal_urls {
957 TerminalUrl::Auto => {
958 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
959 (Ok("truecolor"), Ok("xterm-256color"))
960 if sopts.unstable_features.is_nightly_build() =>
961 {
962 TerminalUrl::Yes
963 }
964 _ => TerminalUrl::No,
965 }
966 }
967 t => t,
968 };
969
970 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
971
972 match sopts.error_format {
973 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
974 HumanReadableErrorType { short, unicode } => {
975 let emitter = AnnotateSnippetEmitter::new(stderr_destination(color_config))
976 .sm(source_map)
977 .short_message(short)
978 .diagnostic_width(sopts.diagnostic_width)
979 .macro_backtrace(macro_backtrace)
980 .track_diagnostics(track_diagnostics)
981 .terminal_url(terminal_url)
982 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
983 .ignored_directories_in_source_blocks(
984 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
985 );
986 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
987 }
988 },
989 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
990 JsonEmitter::new(
991 Box::new(io::BufWriter::new(io::stderr())),
992 source_map,
993 pretty,
994 json_rendered,
995 color_config,
996 )
997 .ui_testing(sopts.unstable_opts.ui_testing)
998 .ignored_directories_in_source_blocks(
999 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
1000 )
1001 .diagnostic_width(sopts.diagnostic_width)
1002 .macro_backtrace(macro_backtrace)
1003 .track_diagnostics(track_diagnostics)
1004 .terminal_url(terminal_url),
1005 ),
1006 }
1007}
1008
1009#[allow(rustc::bad_opt_access)]
1011pub fn build_session(
1012 sopts: config::Options,
1013 io: CompilerIO,
1014 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1015 target: Target,
1016 cfg_version: &'static str,
1017 ice_file: Option<PathBuf>,
1018 using_internal_features: &'static AtomicBool,
1019) -> Session {
1020 let warnings_allow = sopts
1024 .lint_opts
1025 .iter()
1026 .rfind(|&(key, _)| *key == "warnings")
1027 .is_some_and(|&(_, level)| level == lint::Allow);
1028 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1029 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1030
1031 let source_map = rustc_span::source_map::get_source_map().unwrap();
1032 let emitter = default_emitter(&sopts, Arc::clone(&source_map));
1033
1034 let mut dcx =
1035 DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));
1036 if let Some(ice_file) = ice_file {
1037 dcx = dcx.with_ice_file(ice_file);
1038 }
1039
1040 if let Some(msrv) = sopts.unstable_opts.hint_msrv {
1041 dcx = dcx.with_msrv(msrv);
1042 }
1043
1044 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1045 let (host, target_warnings) =
1046 Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)
1047 .unwrap_or_else(|e| {
1048 dcx.handle().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Error loading host specification: {0}",
e))
})format!("Error loading host specification: {e}"))
1049 });
1050 for warning in target_warnings.warning_messages() {
1051 dcx.handle().warn(warning)
1052 }
1053
1054 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1055 {
1056 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1057
1058 let profiler = SelfProfiler::new(
1059 directory,
1060 sopts.crate_name.as_deref(),
1061 sopts.unstable_opts.self_profile_events.as_deref(),
1062 &sopts.unstable_opts.self_profile_counter,
1063 );
1064 match profiler {
1065 Ok(profiler) => Some(Arc::new(profiler)),
1066 Err(e) => {
1067 dcx.handle().emit_warn(diagnostics::FailedToCreateProfiler { err: e.to_string() });
1068 None
1069 }
1070 }
1071 } else {
1072 None
1073 };
1074
1075 let psess = ParseSess::with_dcx(dcx, source_map);
1076
1077 let host_triple = config::host_tuple();
1078 let target_triple = sopts.target_triple.tuple();
1079 let host_tlib_path =
1081 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1082 let target_tlib_path = if host_triple == target_triple {
1083 Arc::clone(&host_tlib_path)
1086 } else {
1087 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1088 };
1089
1090 let prof = SelfProfilerRef::new(
1091 self_profiler,
1092 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1093 );
1094
1095 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1096 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1097 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1098 _ => CtfeBacktrace::Disabled,
1099 });
1100
1101 let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1102 let target_filesearch =
1103 filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1104 let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1105
1106 let timings = TimingSectionHandler::new(sopts.json_timings);
1107
1108 let sess = Session {
1109 target,
1110 host,
1111 opts: sopts,
1112 target_tlib_path,
1113 psess,
1114 unstable_features: UnstableFeatures::from_environment(None),
1115 config: Cfg::default(),
1116 check_config: CheckCfg::default(),
1117 proc_macro_quoted_spans: Default::default(),
1118 io,
1119 incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1120 prof,
1121 timings,
1122 code_stats: Default::default(),
1123 lint_store: None,
1124 driver_lint_caps,
1125 ctfe_backtrace,
1126 miri_unleashed_features: Lock::new(Default::default()),
1127 asm_arch,
1128 target_features: Default::default(),
1129 unstable_target_features: Default::default(),
1130 cfg_version,
1131 using_internal_features,
1132 env_depinfo: Default::default(),
1133 file_depinfo: Default::default(),
1134 target_filesearch,
1135 host_filesearch,
1136 replaced_intrinsics: FxHashSet::default(), fallback_intrinsics: FxHashSet::default(), thin_lto_supported: true, mir_opt_bisect_eval_count: AtomicUsize::new(0),
1140 used_features: Lock::default(),
1141 removed_rustc_main_attr: AtomicBool::new(false),
1142 };
1143
1144 validate_commandline_args_with_session_available(&sess);
1145
1146 sess
1147}
1148
1149pub fn generate_proc_macro_decls_symbol(stable_crate_id: StableCrateId) -> String {
1150 ::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())
1151}
1152
1153#[allow(rustc::bad_opt_access)]
1159fn validate_commandline_args_with_session_available(sess: &Session) {
1160 if sess.opts.cg.linker_plugin_lto.enabled()
1168 && sess.opts.cg.prefer_dynamic
1169 && sess.target.is_like_windows
1170 {
1171 sess.dcx().emit_err(diagnostics::LinkerPluginToWindowsNotSupported);
1172 }
1173
1174 if let Some(ref path) = sess.opts.cg.profile_use {
1177 if !path.exists() {
1178 sess.dcx().emit_err(diagnostics::ProfileUseFileDoesNotExist { path });
1179 }
1180 }
1181
1182 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1184 if !path.exists() {
1185 sess.dcx().emit_err(diagnostics::ProfileSampleUseFileDoesNotExist { path });
1186 }
1187 }
1188
1189 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1191 if sess.target.requires_uwtable && !include_uwtables {
1192 sess.dcx().emit_err(diagnostics::TargetRequiresUnwindTables);
1193 }
1194 }
1195
1196 let supported_sanitizers = sess.target.options.supported_sanitizers;
1198 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1199 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1202 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1203 }
1204 match unsupported_sanitizers.into_iter().count() {
1205 0 => {}
1206 1 => {
1207 sess.dcx().emit_err(diagnostics::SanitizerNotSupported {
1208 us: unsupported_sanitizers.to_string(),
1209 });
1210 }
1211 _ => {
1212 sess.dcx().emit_err(diagnostics::SanitizersNotSupported {
1213 us: unsupported_sanitizers.to_string(),
1214 });
1215 }
1216 }
1217
1218 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1220 sess.dcx().emit_err(diagnostics::CannotMixAndMatchSanitizers {
1221 first: first.to_string(),
1222 second: second.to_string(),
1223 });
1224 }
1225
1226 if sess.crt_static(None)
1228 && !sess.opts.unstable_opts.sanitizer.is_empty()
1229 && !sess.target.is_like_msvc
1230 {
1231 sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticLinux);
1232 }
1233
1234 if sess.crt_static(None) && sess.target.cfg_abi == CfgAbi::Pauthtest {
1238 sess.dcx().emit_err(diagnostics::CannotEnableCrtStaticPointerAuth);
1239 }
1240
1241 if sess.is_sanitizer_cfi_enabled()
1243 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1244 {
1245 sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresLto);
1246 }
1247
1248 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1250 sess.dcx().emit_err(diagnostics::SanitizerKcfiRequiresPanicAbort);
1251 }
1252
1253 if sess.is_sanitizer_cfi_enabled()
1255 && sess.lto() == config::Lto::Fat
1256 && (sess.codegen_units().as_usize() != 1)
1257 {
1258 sess.dcx().emit_err(diagnostics::SanitizerCfiRequiresSingleCodegenUnit);
1259 }
1260
1261 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1263 if !sess.is_sanitizer_cfi_enabled() {
1264 sess.dcx().emit_err(diagnostics::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1265 }
1266 }
1267
1268 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1270 sess.dcx().emit_err(diagnostics::SanitizerKcfiArityRequiresKcfi);
1271 }
1272
1273 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1275 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1276 sess.dcx().emit_err(diagnostics::SanitizerCfiGeneralizePointersRequiresCfi);
1277 }
1278 }
1279
1280 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1282 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1283 sess.dcx().emit_err(diagnostics::SanitizerCfiNormalizeIntegersRequiresCfi);
1284 }
1285 }
1286
1287 if sess.is_split_lto_unit_enabled()
1289 && !(sess.lto() == config::Lto::Fat
1290 || sess.lto() == config::Lto::Thin
1291 || sess.opts.cg.linker_plugin_lto.enabled())
1292 {
1293 sess.dcx().emit_err(diagnostics::SplitLtoUnitRequiresLto);
1294 }
1295
1296 if sess.lto() != config::Lto::Fat {
1298 if sess.opts.unstable_opts.virtual_function_elimination {
1299 sess.dcx().emit_err(diagnostics::UnstableVirtualFunctionElimination);
1300 }
1301 }
1302
1303 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1304 if !sess.target.options.supports_stack_protector {
1305 sess.dcx().emit_warn(diagnostics::StackProtectorNotSupportedForTarget {
1306 stack_protector: sess.opts.unstable_opts.stack_protector,
1307 target_triple: &sess.opts.target_triple,
1308 });
1309 }
1310 }
1311
1312 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1313 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1314 sess.dcx().emit_warn(diagnostics::SmallDataThresholdNotSupportedForTarget {
1315 target_triple: &sess.opts.target_triple,
1316 })
1317 }
1318 }
1319
1320 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1321 sess.dcx().emit_err(diagnostics::BranchProtectionRequiresAArch64);
1322 }
1323
1324 if let Some(dwarf_version) =
1325 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1326 {
1327 if dwarf_version < 2 || dwarf_version > 5 {
1329 sess.dcx().emit_err(diagnostics::UnsupportedDwarfVersion { dwarf_version });
1330 }
1331 }
1332
1333 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1334 && !sess.opts.unstable_opts.unstable_options
1335 {
1336 sess.dcx().emit_err(diagnostics::SplitDebugInfoUnstablePlatform {
1337 debuginfo: sess.split_debuginfo(),
1338 });
1339 }
1340
1341 if sess.opts.unstable_opts.embed_source {
1342 let dwarf_version = sess.dwarf_version();
1343
1344 if dwarf_version < 5 {
1345 sess.dcx()
1346 .emit_warn(diagnostics::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1347 }
1348
1349 if sess.opts.debuginfo == DebugInfo::None {
1350 sess.dcx().emit_warn(diagnostics::EmbedSourceRequiresDebugInfo);
1351 }
1352 }
1353
1354 if sess.opts.unstable_opts.instrument_mcount == InstrumentMcount::Fentry
1355 && !sess.target.options.supports_fentry
1356 {
1357 sess.dcx().emit_err(diagnostics::InstrumentationNotSupported { us: "fentry".to_string() });
1358 }
1359
1360 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1361 sess.dcx().emit_err(diagnostics::InstrumentationNotSupported { us: "XRay".to_string() });
1362 }
1363
1364 if let Some(flavor) = sess.opts.cg.linker_flavor
1365 && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1366 {
1367 let flavor = flavor.desc();
1368 sess.dcx().emit_err(diagnostics::IncompatibleLinkerFlavor { flavor, compatible_list });
1369 }
1370
1371 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1372 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) {
1373 sess.dcx().emit_err(diagnostics::FunctionReturnRequiresX86OrX8664);
1374 }
1375 }
1376
1377 if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1378 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) {
1379 sess.dcx().emit_err(diagnostics::IndirectBranchCsPrefixRequiresX86OrX8664);
1380 }
1381 }
1382
1383 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1384 if regparm > 3 {
1385 sess.dcx().emit_err(diagnostics::UnsupportedRegparm { regparm });
1386 }
1387 if sess.target.arch != Arch::X86 {
1388 sess.dcx().emit_err(diagnostics::UnsupportedRegparmArch);
1389 }
1390 }
1391 if sess.opts.unstable_opts.reg_struct_return {
1392 if sess.target.arch != Arch::X86 {
1393 sess.dcx().emit_err(diagnostics::UnsupportedRegStructReturnArch);
1394 }
1395 }
1396
1397 match sess.opts.unstable_opts.function_return {
1401 FunctionReturn::Keep => (),
1402 FunctionReturn::ThunkExtern => {
1403 if let Some(code_model) = sess.code_model()
1406 && code_model == CodeModel::Large
1407 {
1408 sess.dcx()
1409 .emit_err(diagnostics::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1410 }
1411 }
1412 }
1413
1414 if sess.opts.unstable_opts.packed_stack {
1415 if sess.target.arch != Arch::S390x {
1416 sess.dcx().emit_err(diagnostics::UnsupportedPackedStack);
1417 }
1418 }
1419}
1420
1421#[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)]
1423enum IncrCompSession {
1424 NotInitialized,
1427 Active { session_directory: PathBuf, _lock_file: flock::Lock },
1432 Finalized { session_directory: PathBuf },
1435 InvalidBecauseOfErrors { session_directory: PathBuf },
1439}
1440
1441pub struct EarlyDiagCtxt {
1443 dcx: DiagCtxt,
1444}
1445
1446impl EarlyDiagCtxt {
1447 pub fn new(output: ErrorOutputType) -> Self {
1448 let emitter = mk_emitter(output);
1449 Self { dcx: DiagCtxt::new(emitter) }
1450 }
1451
1452 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1455 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());
1456
1457 let emitter = mk_emitter(output);
1458 self.dcx = DiagCtxt::new(emitter);
1459 }
1460
1461 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1462 self.dcx.handle().note(msg)
1463 }
1464
1465 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1466 self.dcx.handle().struct_help(msg).emit()
1467 }
1468
1469 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1470 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1471 self.dcx.handle().err(msg)
1472 }
1473
1474 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1475 self.dcx.handle().fatal(msg)
1476 }
1477
1478 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1479 self.dcx.handle().struct_fatal(msg)
1480 }
1481
1482 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1483 self.dcx.handle().warn(msg)
1484 }
1485
1486 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1487 self.dcx.handle().struct_warn(msg)
1488 }
1489}
1490
1491fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1492 let emitter: Box<DynEmitter> = match output {
1493 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1494 HumanReadableErrorType { short, unicode } => Box::new(
1495 AnnotateSnippetEmitter::new(stderr_destination(color_config))
1496 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1497 .short_message(short),
1498 ),
1499 },
1500 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1501 Box::new(JsonEmitter::new(
1502 Box::new(io::BufWriter::new(io::stderr())),
1503 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1504 pretty,
1505 json_rendered,
1506 color_config,
1507 ))
1508 }
1509 };
1510 emitter
1511}