1use std::any::Any;
2use std::path::PathBuf;
3use std::str::FromStr;
4use std::sync::Arc;
5use std::sync::atomic::{AtomicBool, AtomicUsize};
6use std::{env, io};
7
8use rand::{RngCore, rng};
9use rustc_data_structures::base_n::{CASE_INSENSITIVE, ToBaseN};
10use rustc_data_structures::flock;
11use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
12use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
13use rustc_data_structures::sync::{DynSend, DynSync, Lock, MappedReadGuard, ReadGuard, RwLock};
14use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;
15use rustc_errors::codes::*;
16use rustc_errors::emitter::{DynEmitter, HumanReadableErrorType, OutputTheme, stderr_destination};
17use rustc_errors::json::JsonEmitter;
18use rustc_errors::timings::TimingSectionHandler;
19use rustc_errors::{
20 Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, FatalAbort,
21 TerminalUrl,
22};
23use rustc_hir::limit::Limit;
24use rustc_macros::HashStable_Generic;
25pub use rustc_span::def_id::StableCrateId;
26use rustc_span::edition::Edition;
27use rustc_span::source_map::{FilePathMapping, SourceMap};
28use rustc_span::{RealFileName, Span, Symbol};
29use rustc_target::asm::InlineAsmArch;
30use rustc_target::spec::{
31 Arch, CodeModel, DebuginfoKind, Os, PanicStrategy, RelocModel, RelroLevel, SanitizerSet,
32 SmallDataThresholdSupport, SplitDebuginfo, StackProtector, SymbolVisibility, Target,
33 TargetTuple, TlsModel, apple,
34};
35
36use crate::code_stats::CodeStats;
37pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
38use crate::config::{
39 self, CoverageLevel, CoverageOptions, CrateType, DebugInfo, ErrorOutputType, FunctionReturn,
40 Input, InstrumentCoverage, OptLevel, OutFileName, OutputType, SwitchWithOptPath,
41};
42use crate::filesearch::FileSearch;
43use crate::lint::{CheckLintNameResult, LintId, RegisteredTools};
44use crate::parse::{ParseSess, add_feature_diagnostics};
45use crate::search_paths::SearchPath;
46use crate::{errors, filesearch, lint};
47
48#[derive(#[automatically_derived]
impl ::core::clone::Clone for CtfeBacktrace {
#[inline]
fn clone(&self) -> CtfeBacktrace { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for CtfeBacktrace { }Copy)]
50pub enum CtfeBacktrace {
51 Disabled,
53 Capture,
56 Immediate,
58}
59
60#[derive(#[automatically_derived]
impl ::core::clone::Clone for Limits {
#[inline]
fn clone(&self) -> Limits {
let _: ::core::clone::AssertParamIsClone<Limit>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Limits { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Limits {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f, "Limits",
"recursion_limit", &self.recursion_limit, "move_size_limit",
&self.move_size_limit, "type_length_limit",
&self.type_length_limit, "pattern_complexity_limit",
&&self.pattern_complexity_limit)
}
}Debug, const _: () =
{
impl<__CTX> ::rustc_data_structures::stable_hasher::HashStable<__CTX>
for Limits where __CTX: ::rustc_span::HashStableContext {
#[inline]
fn hash_stable(&self, __hcx: &mut __CTX,
__hasher:
&mut ::rustc_data_structures::stable_hasher::StableHasher) {
match *self {
Limits {
recursion_limit: ref __binding_0,
move_size_limit: ref __binding_1,
type_length_limit: ref __binding_2,
pattern_complexity_limit: ref __binding_3 } => {
{ __binding_0.hash_stable(__hcx, __hasher); }
{ __binding_1.hash_stable(__hcx, __hasher); }
{ __binding_2.hash_stable(__hcx, __hasher); }
{ __binding_3.hash_stable(__hcx, __hasher); }
}
}
}
}
};HashStable_Generic)]
61pub struct Limits {
62 pub recursion_limit: Limit,
65 pub move_size_limit: Limit,
68 pub type_length_limit: Limit,
70 pub pattern_complexity_limit: Limit,
72}
73
74pub struct CompilerIO {
75 pub input: Input,
76 pub output_dir: Option<PathBuf>,
77 pub output_file: Option<OutFileName>,
78 pub temps_dir: Option<PathBuf>,
79}
80
81pub trait DynLintStore: Any + DynSync + DynSend {
82 fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_>;
84
85 fn check_lint_name(
86 &self,
87 lint_name: &str,
88 tool_name: Option<Symbol>,
89 registered_tools: &RegisteredTools,
90 ) -> CheckLintNameResult<'_>;
91
92 fn find_lints(&self, lint_name: &str) -> Option<&[LintId]>;
93}
94
95pub struct Session {
98 pub target: Target,
99 pub host: Target,
100 pub opts: config::Options,
101 pub target_tlib_path: Arc<SearchPath>,
102 pub psess: ParseSess,
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 invocation_temp: Option<String>,
171
172 pub replaced_intrinsics: FxHashSet<Symbol>,
175
176 pub thin_lto_supported: bool,
178
179 pub mir_opt_bisect_eval_count: AtomicUsize,
184
185 pub used_features: Lock<FxHashMap<Symbol, u32>>,
189}
190
191#[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)]
192pub enum CodegenUnits {
193 User(usize),
196
197 Default(usize),
201}
202
203impl CodegenUnits {
204 pub fn as_usize(self) -> usize {
205 match self {
206 CodegenUnits::User(n) => n,
207 CodegenUnits::Default(n) => n,
208 }
209 }
210}
211
212pub struct LintGroup {
213 pub name: &'static str,
214 pub lints: Vec<LintId>,
215 pub is_externally_loaded: bool,
216}
217
218impl Session {
219 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
220 self.miri_unleashed_features.lock().push((span, feature_gate));
221 }
222
223 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
224 Some(
225 self.source_map()
226 .path_mapping()
227 .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),
228 )
229 }
230
231 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
232 let mut guar = None;
233 let unleashed_features = self.miri_unleashed_features.lock();
234 if !unleashed_features.is_empty() {
235 let mut must_err = false;
236 self.dcx().emit_warn(errors::SkippingConstChecks {
238 unleashed_features: unleashed_features
239 .iter()
240 .map(|(span, gate)| {
241 gate.map(|gate| {
242 must_err = true;
243 errors::UnleashedFeatureHelp::Named { span: *span, gate }
244 })
245 .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })
246 })
247 .collect(),
248 });
249
250 if must_err && self.dcx().has_errors().is_none() {
252 guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));
254 }
255 }
256 guar
257 }
258
259 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
261 let mut guar = None;
262 guar = guar.or(self.check_miri_unleashed_features());
263 guar = guar.or(self.dcx().emit_stashed_diagnostics());
264 self.dcx().print_error_count();
265 if self.opts.json_future_incompat {
266 self.dcx().emit_future_breakage_report();
267 }
268 guar
269 }
270
271 pub fn is_test_crate(&self) -> bool {
273 self.opts.test
274 }
275
276 #[track_caller]
278 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
279 let mut err = self.dcx().create_err(err);
280 if err.code.is_none() {
281 err.code(E0658);
282 }
283 add_feature_diagnostics(&mut err, self, feature);
284 err
285 }
286
287 pub fn record_trimmed_def_paths(&self) {
290 if self.opts.unstable_opts.print_type_sizes
291 || self.opts.unstable_opts.query_dep_graph
292 || self.opts.unstable_opts.dump_mir.is_some()
293 || self.opts.unstable_opts.unpretty.is_some()
294 || self.prof.is_args_recording_enabled()
295 || self.opts.output_types.contains_key(&OutputType::Mir)
296 || std::env::var_os("RUSTC_LOG").is_some()
297 {
298 return;
299 }
300
301 self.dcx().set_must_produce_diag()
302 }
303
304 #[inline]
305 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
306 self.psess.dcx()
307 }
308
309 #[inline]
310 pub fn source_map(&self) -> &SourceMap {
311 self.psess.source_map()
312 }
313
314 pub fn enable_internal_lints(&self) -> bool {
318 self.unstable_options() && !self.opts.actually_rustdoc
319 }
320
321 pub fn instrument_coverage(&self) -> bool {
322 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
323 }
324
325 pub fn instrument_coverage_branch(&self) -> bool {
326 self.instrument_coverage()
327 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
328 }
329
330 pub fn instrument_coverage_condition(&self) -> bool {
331 self.instrument_coverage()
332 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
333 }
334
335 pub fn coverage_options(&self) -> &CoverageOptions {
339 &self.opts.unstable_opts.coverage_options
340 }
341
342 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
343 self.sanitizers().contains(SanitizerSet::CFI)
344 }
345
346 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
347 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
348 }
349
350 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
351 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
352 }
353
354 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
355 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
356 }
357
358 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
359 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
360 }
361
362 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
363 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
364 }
365
366 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
367 self.sanitizers().contains(SanitizerSet::KCFI)
368 }
369
370 pub fn is_split_lto_unit_enabled(&self) -> bool {
371 self.opts.unstable_opts.split_lto_unit == Some(true)
372 }
373
374 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
376 if !self.target.crt_static_respected {
377 return self.target.crt_static_default;
379 }
380
381 let requested_features = self.opts.cg.target_feature.split(',');
382 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
383 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
384
385 #[allow(rustc::bad_opt_access)]
387 if found_positive || found_negative {
388 found_positive
389 } else if crate_type == Some(CrateType::ProcMacro)
390 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
391 {
392 false
396 } else {
397 self.target.crt_static_default
398 }
399 }
400
401 pub fn is_wasi_reactor(&self) -> bool {
402 self.target.options.os == Os::Wasi
403 && #[allow(non_exhaustive_omitted_patterns)] match self.opts.unstable_opts.wasi_exec_model
{
Some(config::WasiExecModel::Reactor) => true,
_ => false,
}matches!(
404 self.opts.unstable_opts.wasi_exec_model,
405 Some(config::WasiExecModel::Reactor)
406 )
407 }
408
409 pub fn target_can_use_split_dwarf(&self) -> bool {
411 self.target.debuginfo_kind == DebuginfoKind::Dwarf
412 }
413
414 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
415 ::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())
416 }
417
418 pub fn target_filesearch(&self) -> &filesearch::FileSearch {
419 &self.target_filesearch
420 }
421 pub fn host_filesearch(&self) -> &filesearch::FileSearch {
422 &self.host_filesearch
423 }
424
425 pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
429 let search_paths = self
430 .opts
431 .sysroot
432 .all_paths()
433 .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_tuple()));
434
435 if self_contained {
436 search_paths.flat_map(|path| [path.clone(), path.join("self-contained")]).collect()
440 } else {
441 search_paths.collect()
442 }
443 }
444
445 pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {
446 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
447
448 if let IncrCompSession::NotInitialized = *incr_comp_session {
449 } else {
450 {
::core::panicking::panic_fmt(format_args!("Trying to initialize IncrCompSession `{0:?}`",
*incr_comp_session));
}panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
451 }
452
453 *incr_comp_session =
454 IncrCompSession::Active { session_directory: session_dir, _lock_file: lock_file };
455 }
456
457 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
458 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
459
460 if let IncrCompSession::Active { .. } = *incr_comp_session {
461 } else {
462 {
::core::panicking::panic_fmt(format_args!("trying to finalize `IncrCompSession` `{0:?}`",
*incr_comp_session));
};panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
463 }
464
465 *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
467 }
468
469 pub fn mark_incr_comp_session_as_invalid(&self) {
470 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
471
472 let session_directory = match *incr_comp_session {
473 IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
474 IncrCompSession::InvalidBecauseOfErrors { .. } => return,
475 _ => {
::core::panicking::panic_fmt(format_args!("trying to invalidate `IncrCompSession` `{0:?}`",
*incr_comp_session));
}panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
476 };
477
478 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
480 }
481
482 pub fn incr_comp_session_dir(&self) -> MappedReadGuard<'_, PathBuf> {
483 let incr_comp_session = self.incr_comp_session.borrow();
484 ReadGuard::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
485 IncrCompSession::NotInitialized => {
::core::panicking::panic_fmt(format_args!("trying to get session directory from `IncrCompSession`: {0:?}",
*incr_comp_session));
}panic!(
486 "trying to get session directory from `IncrCompSession`: {:?}",
487 *incr_comp_session,
488 ),
489 IncrCompSession::Active { ref session_directory, .. }
490 | IncrCompSession::Finalized { ref session_directory }
491 | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
492 session_directory
493 }
494 })
495 }
496
497 pub fn incr_comp_session_dir_opt(&self) -> Option<MappedReadGuard<'_, PathBuf>> {
498 self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
499 }
500
501 pub fn is_rust_2015(&self) -> bool {
503 self.edition().is_rust_2015()
504 }
505
506 pub fn at_least_rust_2018(&self) -> bool {
508 self.edition().at_least_rust_2018()
509 }
510
511 pub fn at_least_rust_2021(&self) -> bool {
513 self.edition().at_least_rust_2021()
514 }
515
516 pub fn at_least_rust_2024(&self) -> bool {
518 self.edition().at_least_rust_2024()
519 }
520
521 pub fn needs_plt(&self) -> bool {
523 let want_plt = self.target.plt_by_default;
526
527 let dbg_opts = &self.opts.unstable_opts;
528
529 let relro_level = self.opts.cg.relro_level.unwrap_or(self.target.relro_level);
530
531 let full_relro = RelroLevel::Full == relro_level;
535
536 dbg_opts.plt.unwrap_or(want_plt || !full_relro)
539 }
540
541 pub fn emit_lifetime_markers(&self) -> bool {
543 self.opts.optimize != config::OptLevel::No
544 || self.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS | SanitizerSet::KERNELHWADDRESS)
551 }
552
553 pub fn diagnostic_width(&self) -> usize {
554 let default_column_width = 140;
555 if let Some(width) = self.opts.diagnostic_width {
556 width
557 } else if self.opts.unstable_opts.ui_testing {
558 default_column_width
559 } else {
560 termize::dimensions().map_or(default_column_width, |(w, _)| w)
561 }
562 }
563
564 pub fn default_visibility(&self) -> SymbolVisibility {
566 self.opts
567 .unstable_opts
568 .default_visibility
569 .or(self.target.options.default_visibility)
570 .unwrap_or(SymbolVisibility::Interposable)
571 }
572
573 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
574 if verbatim {
575 ("", "")
576 } else {
577 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
578 }
579 }
580
581 pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
582 match self.lint_store {
583 Some(ref lint_store) => lint_store.lint_groups_iter(),
584 None => Box::new(std::iter::empty()),
585 }
586 }
587}
588
589#[allow(rustc::bad_opt_access)]
591impl Session {
592 pub fn verbose_internals(&self) -> bool {
593 self.opts.unstable_opts.verbose_internals
594 }
595
596 pub fn print_llvm_stats(&self) -> bool {
597 self.opts.unstable_opts.print_codegen_stats
598 }
599
600 pub fn verify_llvm_ir(&self) -> bool {
601 self.opts.unstable_opts.verify_llvm_ir || ::core::option::Option::None::<&'static str>option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
602 }
603
604 pub fn binary_dep_depinfo(&self) -> bool {
605 self.opts.unstable_opts.binary_dep_depinfo
606 }
607
608 pub fn mir_opt_level(&self) -> usize {
609 self.opts
610 .unstable_opts
611 .mir_opt_level
612 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
613 }
614
615 pub fn lto(&self) -> config::Lto {
617 if self.target.requires_lto {
619 return config::Lto::Fat;
620 }
621
622 match self.opts.cg.lto {
626 config::LtoCli::Unspecified => {
627 }
630 config::LtoCli::No => {
631 return config::Lto::No;
633 }
634 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
635 return config::Lto::Fat;
637 }
638 config::LtoCli::Thin => {
639 if !self.thin_lto_supported {
641 self.dcx().emit_warn(errors::ThinLtoNotSupportedByBackend);
643 return config::Lto::Fat;
644 }
645 return config::Lto::Thin;
646 }
647 }
648
649 if !self.thin_lto_supported {
650 return config::Lto::No;
651 }
652
653 if self.opts.cli_forced_local_thinlto_off {
662 return config::Lto::No;
663 }
664
665 if let Some(enabled) = self.opts.unstable_opts.thinlto {
668 if enabled {
669 return config::Lto::ThinLocal;
670 } else {
671 return config::Lto::No;
672 }
673 }
674
675 if self.codegen_units().as_usize() == 1 {
678 return config::Lto::No;
679 }
680
681 match self.opts.optimize {
684 config::OptLevel::No => config::Lto::No,
685 _ => config::Lto::ThinLocal,
686 }
687 }
688
689 pub fn panic_strategy(&self) -> PanicStrategy {
692 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
693 }
694
695 pub fn fewer_names(&self) -> bool {
696 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
697 fewer_names
698 } else {
699 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
700 || self.opts.output_types.contains_key(&OutputType::Bitcode)
701 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
703 !more_names
704 }
705 }
706
707 pub fn unstable_options(&self) -> bool {
708 self.opts.unstable_opts.unstable_options
709 }
710
711 pub fn is_nightly_build(&self) -> bool {
712 self.opts.unstable_features.is_nightly_build()
713 }
714
715 pub fn overflow_checks(&self) -> bool {
716 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
717 }
718
719 pub fn ub_checks(&self) -> bool {
720 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
721 }
722
723 pub fn contract_checks(&self) -> bool {
724 self.opts.unstable_opts.contract_checks.unwrap_or(false)
725 }
726
727 pub fn relocation_model(&self) -> RelocModel {
728 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
729 }
730
731 pub fn code_model(&self) -> Option<CodeModel> {
732 self.opts.cg.code_model.or(self.target.code_model)
733 }
734
735 pub fn tls_model(&self) -> TlsModel {
736 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
737 }
738
739 pub fn direct_access_external_data(&self) -> Option<bool> {
740 self.opts
741 .unstable_opts
742 .direct_access_external_data
743 .or(self.target.direct_access_external_data)
744 }
745
746 pub fn split_debuginfo(&self) -> SplitDebuginfo {
747 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
748 }
749
750 pub fn dwarf_version(&self) -> u32 {
752 self.opts
753 .cg
754 .dwarf_version
755 .or(self.opts.unstable_opts.dwarf_version)
756 .unwrap_or(self.target.default_dwarf_version)
757 }
758
759 pub fn stack_protector(&self) -> StackProtector {
760 if self.target.options.supports_stack_protector {
761 self.opts.unstable_opts.stack_protector
762 } else {
763 StackProtector::None
764 }
765 }
766
767 pub fn must_emit_unwind_tables(&self) -> bool {
768 self.target.requires_uwtable
797 || self
798 .opts
799 .cg
800 .force_unwind_tables
801 .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
802 }
803
804 #[inline]
807 pub fn threads(&self) -> usize {
808 self.opts.unstable_opts.threads
809 }
810
811 pub fn codegen_units(&self) -> CodegenUnits {
814 if let Some(n) = self.opts.cli_forced_codegen_units {
815 return CodegenUnits::User(n);
816 }
817 if let Some(n) = self.target.default_codegen_units {
818 return CodegenUnits::Default(n as usize);
819 }
820
821 if self.opts.incremental.is_some() {
825 return CodegenUnits::Default(256);
826 }
827
828 CodegenUnits::Default(16)
879 }
880
881 pub fn teach(&self, code: ErrCode) -> bool {
882 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
883 }
884
885 pub fn edition(&self) -> Edition {
886 self.opts.edition
887 }
888
889 pub fn link_dead_code(&self) -> bool {
890 self.opts.cg.link_dead_code.unwrap_or(false)
891 }
892
893 pub fn apple_deployment_target(&self) -> apple::OSVersion {
898 let min = apple::OSVersion::minimum_deployment_target(&self.target);
899 let env_var = apple::deployment_target_env_var(&self.target.os);
900
901 if let Ok(deployment_target) = env::var(env_var) {
903 match apple::OSVersion::from_str(&deployment_target) {
904 Ok(version) => {
905 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
906 if version < os_min {
911 self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {
912 env_var,
913 version: version.fmt_pretty().to_string(),
914 os_min: os_min.fmt_pretty().to_string(),
915 });
916 }
917
918 version.max(min)
920 }
921 Err(error) => {
922 self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });
923 min
924 }
925 }
926 } else {
927 min
929 }
930 }
931
932 pub fn sanitizers(&self) -> SanitizerSet {
933 return self.opts.unstable_opts.sanitizer | self.target.options.default_sanitizers;
934 }
935}
936
937#[allow(rustc::bad_opt_access)]
939fn default_emitter(sopts: &config::Options, source_map: Arc<SourceMap>) -> Box<DynEmitter> {
940 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
941 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
942 let terminal_url = match sopts.unstable_opts.terminal_urls {
943 TerminalUrl::Auto => {
944 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
945 (Ok("truecolor"), Ok("xterm-256color"))
946 if sopts.unstable_features.is_nightly_build() =>
947 {
948 TerminalUrl::Yes
949 }
950 _ => TerminalUrl::No,
951 }
952 }
953 t => t,
954 };
955
956 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
957
958 match sopts.error_format {
959 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
960 HumanReadableErrorType { short, unicode } => {
961 let emitter = AnnotateSnippetEmitter::new(stderr_destination(color_config))
962 .sm(source_map)
963 .short_message(short)
964 .diagnostic_width(sopts.diagnostic_width)
965 .macro_backtrace(macro_backtrace)
966 .track_diagnostics(track_diagnostics)
967 .terminal_url(terminal_url)
968 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
969 .ignored_directories_in_source_blocks(
970 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
971 );
972 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
973 }
974 },
975 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
976 JsonEmitter::new(
977 Box::new(io::BufWriter::new(io::stderr())),
978 source_map,
979 pretty,
980 json_rendered,
981 color_config,
982 )
983 .ui_testing(sopts.unstable_opts.ui_testing)
984 .ignored_directories_in_source_blocks(
985 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
986 )
987 .diagnostic_width(sopts.diagnostic_width)
988 .macro_backtrace(macro_backtrace)
989 .track_diagnostics(track_diagnostics)
990 .terminal_url(terminal_url),
991 ),
992 }
993}
994
995#[allow(rustc::bad_opt_access)]
997pub fn build_session(
998 sopts: config::Options,
999 io: CompilerIO,
1000 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1001 target: Target,
1002 cfg_version: &'static str,
1003 ice_file: Option<PathBuf>,
1004 using_internal_features: &'static AtomicBool,
1005) -> Session {
1006 let warnings_allow = sopts
1010 .lint_opts
1011 .iter()
1012 .rfind(|&(key, _)| *key == "warnings")
1013 .is_some_and(|&(_, level)| level == lint::Allow);
1014 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1015 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1016
1017 let source_map = rustc_span::source_map::get_source_map().unwrap();
1018 let emitter = default_emitter(&sopts, Arc::clone(&source_map));
1019
1020 let mut dcx =
1021 DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));
1022 if let Some(ice_file) = ice_file {
1023 dcx = dcx.with_ice_file(ice_file);
1024 }
1025
1026 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1027 let (host, target_warnings) =
1028 Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)
1029 .unwrap_or_else(|e| {
1030 dcx.handle().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Error loading host specification: {0}",
e))
})format!("Error loading host specification: {e}"))
1031 });
1032 for warning in target_warnings.warning_messages() {
1033 dcx.handle().warn(warning)
1034 }
1035
1036 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1037 {
1038 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1039
1040 let profiler = SelfProfiler::new(
1041 directory,
1042 sopts.crate_name.as_deref(),
1043 sopts.unstable_opts.self_profile_events.as_deref(),
1044 &sopts.unstable_opts.self_profile_counter,
1045 );
1046 match profiler {
1047 Ok(profiler) => Some(Arc::new(profiler)),
1048 Err(e) => {
1049 dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1050 None
1051 }
1052 }
1053 } else {
1054 None
1055 };
1056
1057 let mut psess = ParseSess::with_dcx(dcx, source_map);
1058 psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
1059
1060 let host_triple = config::host_tuple();
1061 let target_triple = sopts.target_triple.tuple();
1062 let host_tlib_path =
1064 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1065 let target_tlib_path = if host_triple == target_triple {
1066 Arc::clone(&host_tlib_path)
1069 } else {
1070 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1071 };
1072
1073 let prof = SelfProfilerRef::new(
1074 self_profiler,
1075 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1076 );
1077
1078 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1079 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1080 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1081 _ => CtfeBacktrace::Disabled,
1082 });
1083
1084 let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1085 let target_filesearch =
1086 filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1087 let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1088
1089 let invocation_temp = sopts
1090 .incremental
1091 .as_ref()
1092 .map(|_| rng().next_u32().to_base_fixed_len(CASE_INSENSITIVE).to_string());
1093
1094 let timings = TimingSectionHandler::new(sopts.json_timings);
1095
1096 let sess = Session {
1097 target,
1098 host,
1099 opts: sopts,
1100 target_tlib_path,
1101 psess,
1102 io,
1103 incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1104 prof,
1105 timings,
1106 code_stats: Default::default(),
1107 lint_store: None,
1108 driver_lint_caps,
1109 ctfe_backtrace,
1110 miri_unleashed_features: Lock::new(Default::default()),
1111 asm_arch,
1112 target_features: Default::default(),
1113 unstable_target_features: Default::default(),
1114 cfg_version,
1115 using_internal_features,
1116 env_depinfo: Default::default(),
1117 file_depinfo: Default::default(),
1118 target_filesearch,
1119 host_filesearch,
1120 invocation_temp,
1121 replaced_intrinsics: FxHashSet::default(), thin_lto_supported: true, mir_opt_bisect_eval_count: AtomicUsize::new(0),
1124 used_features: Lock::default(),
1125 };
1126
1127 validate_commandline_args_with_session_available(&sess);
1128
1129 sess
1130}
1131
1132#[allow(rustc::bad_opt_access)]
1138fn validate_commandline_args_with_session_available(sess: &Session) {
1139 if sess.opts.cg.linker_plugin_lto.enabled()
1147 && sess.opts.cg.prefer_dynamic
1148 && sess.target.is_like_windows
1149 {
1150 sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1151 }
1152
1153 if let Some(ref path) = sess.opts.cg.profile_use {
1156 if !path.exists() {
1157 sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1158 }
1159 }
1160
1161 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1163 if !path.exists() {
1164 sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1165 }
1166 }
1167
1168 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1170 if sess.target.requires_uwtable && !include_uwtables {
1171 sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1172 }
1173 }
1174
1175 let supported_sanitizers = sess.target.options.supported_sanitizers;
1177 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1178 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1181 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1182 }
1183 match unsupported_sanitizers.into_iter().count() {
1184 0 => {}
1185 1 => {
1186 sess.dcx()
1187 .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1188 }
1189 _ => {
1190 sess.dcx().emit_err(errors::SanitizersNotSupported {
1191 us: unsupported_sanitizers.to_string(),
1192 });
1193 }
1194 }
1195
1196 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1198 sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1199 first: first.to_string(),
1200 second: second.to_string(),
1201 });
1202 }
1203
1204 if sess.crt_static(None)
1206 && !sess.opts.unstable_opts.sanitizer.is_empty()
1207 && !sess.target.is_like_msvc
1208 {
1209 sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1210 }
1211
1212 if sess.is_sanitizer_cfi_enabled()
1214 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1215 {
1216 sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1217 }
1218
1219 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1221 sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1222 }
1223
1224 if sess.is_sanitizer_cfi_enabled()
1226 && sess.lto() == config::Lto::Fat
1227 && (sess.codegen_units().as_usize() != 1)
1228 {
1229 sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1230 }
1231
1232 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1234 if !sess.is_sanitizer_cfi_enabled() {
1235 sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1236 }
1237 }
1238
1239 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1241 sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);
1242 }
1243
1244 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1246 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1247 sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1248 }
1249 }
1250
1251 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1253 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1254 sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1255 }
1256 }
1257
1258 if sess.is_split_lto_unit_enabled()
1260 && !(sess.lto() == config::Lto::Fat
1261 || sess.lto() == config::Lto::Thin
1262 || sess.opts.cg.linker_plugin_lto.enabled())
1263 {
1264 sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1265 }
1266
1267 if sess.lto() != config::Lto::Fat {
1269 if sess.opts.unstable_opts.virtual_function_elimination {
1270 sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1271 }
1272 }
1273
1274 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1275 if !sess.target.options.supports_stack_protector {
1276 sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1277 stack_protector: sess.opts.unstable_opts.stack_protector,
1278 target_triple: &sess.opts.target_triple,
1279 });
1280 }
1281 }
1282
1283 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1284 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1285 sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1286 target_triple: &sess.opts.target_triple,
1287 })
1288 }
1289 }
1290
1291 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1292 sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1293 }
1294
1295 if let Some(dwarf_version) =
1296 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1297 {
1298 if dwarf_version < 2 || dwarf_version > 5 {
1300 sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1301 }
1302 }
1303
1304 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1305 && !sess.opts.unstable_opts.unstable_options
1306 {
1307 sess.dcx()
1308 .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1309 }
1310
1311 if sess.opts.unstable_opts.embed_source {
1312 let dwarf_version = sess.dwarf_version();
1313
1314 if dwarf_version < 5 {
1315 sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1316 }
1317
1318 if sess.opts.debuginfo == DebugInfo::None {
1319 sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1320 }
1321 }
1322
1323 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1324 sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1325 }
1326
1327 if let Some(flavor) = sess.opts.cg.linker_flavor
1328 && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1329 {
1330 let flavor = flavor.desc();
1331 sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1332 }
1333
1334 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1335 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) {
1336 sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1337 }
1338 }
1339
1340 if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1341 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) {
1342 sess.dcx().emit_err(errors::IndirectBranchCsPrefixRequiresX86OrX8664);
1343 }
1344 }
1345
1346 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1347 if regparm > 3 {
1348 sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1349 }
1350 if sess.target.arch != Arch::X86 {
1351 sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1352 }
1353 }
1354 if sess.opts.unstable_opts.reg_struct_return {
1355 if sess.target.arch != Arch::X86 {
1356 sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1357 }
1358 }
1359
1360 match sess.opts.unstable_opts.function_return {
1364 FunctionReturn::Keep => (),
1365 FunctionReturn::ThunkExtern => {
1366 if let Some(code_model) = sess.code_model()
1369 && code_model == CodeModel::Large
1370 {
1371 sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1372 }
1373 }
1374 }
1375
1376 if sess.opts.unstable_opts.packed_stack {
1377 if sess.target.arch != Arch::S390x {
1378 sess.dcx().emit_err(errors::UnsupportedPackedStack);
1379 }
1380 }
1381}
1382
1383#[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)]
1385enum IncrCompSession {
1386 NotInitialized,
1389 Active { session_directory: PathBuf, _lock_file: flock::Lock },
1394 Finalized { session_directory: PathBuf },
1397 InvalidBecauseOfErrors { session_directory: PathBuf },
1401}
1402
1403pub struct EarlyDiagCtxt {
1405 dcx: DiagCtxt,
1406}
1407
1408impl EarlyDiagCtxt {
1409 pub fn new(output: ErrorOutputType) -> Self {
1410 let emitter = mk_emitter(output);
1411 Self { dcx: DiagCtxt::new(emitter) }
1412 }
1413
1414 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1417 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());
1418
1419 let emitter = mk_emitter(output);
1420 self.dcx = DiagCtxt::new(emitter);
1421 }
1422
1423 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1424 self.dcx.handle().note(msg)
1425 }
1426
1427 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1428 self.dcx.handle().struct_help(msg).emit()
1429 }
1430
1431 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1432 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1433 self.dcx.handle().err(msg)
1434 }
1435
1436 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1437 self.dcx.handle().fatal(msg)
1438 }
1439
1440 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1441 self.dcx.handle().struct_fatal(msg)
1442 }
1443
1444 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1445 self.dcx.handle().warn(msg)
1446 }
1447
1448 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1449 self.dcx.handle().struct_warn(msg)
1450 }
1451}
1452
1453fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1454 let emitter: Box<DynEmitter> = match output {
1455 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1456 HumanReadableErrorType { short, unicode } => Box::new(
1457 AnnotateSnippetEmitter::new(stderr_destination(color_config))
1458 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1459 .short_message(short),
1460 ),
1461 },
1462 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1463 Box::new(JsonEmitter::new(
1464 Box::new(io::BufWriter::new(io::stderr())),
1465 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1466 pretty,
1467 json_rendered,
1468 color_config,
1469 ))
1470 }
1471 };
1472 emitter
1473}