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