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_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
186#[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)]
187pub enum CodegenUnits {
188 User(usize),
191
192 Default(usize),
196}
197
198impl CodegenUnits {
199 pub fn as_usize(self) -> usize {
200 match self {
201 CodegenUnits::User(n) => n,
202 CodegenUnits::Default(n) => n,
203 }
204 }
205}
206
207pub struct LintGroup {
208 pub name: &'static str,
209 pub lints: Vec<LintId>,
210 pub is_externally_loaded: bool,
211}
212
213impl Session {
214 pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
215 self.miri_unleashed_features.lock().push((span, feature_gate));
216 }
217
218 pub fn local_crate_source_file(&self) -> Option<RealFileName> {
219 Some(
220 self.source_map()
221 .path_mapping()
222 .to_real_filename(self.source_map().working_dir(), self.io.input.opt_path()?),
223 )
224 }
225
226 fn check_miri_unleashed_features(&self) -> Option<ErrorGuaranteed> {
227 let mut guar = None;
228 let unleashed_features = self.miri_unleashed_features.lock();
229 if !unleashed_features.is_empty() {
230 let mut must_err = false;
231 self.dcx().emit_warn(errors::SkippingConstChecks {
233 unleashed_features: unleashed_features
234 .iter()
235 .map(|(span, gate)| {
236 gate.map(|gate| {
237 must_err = true;
238 errors::UnleashedFeatureHelp::Named { span: *span, gate }
239 })
240 .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span })
241 })
242 .collect(),
243 });
244
245 if must_err && self.dcx().has_errors().is_none() {
247 guar = Some(self.dcx().emit_err(errors::NotCircumventFeature));
249 }
250 }
251 guar
252 }
253
254 pub fn finish_diagnostics(&self) -> Option<ErrorGuaranteed> {
256 let mut guar = None;
257 guar = guar.or(self.check_miri_unleashed_features());
258 guar = guar.or(self.dcx().emit_stashed_diagnostics());
259 self.dcx().print_error_count();
260 if self.opts.json_future_incompat {
261 self.dcx().emit_future_breakage_report();
262 }
263 guar
264 }
265
266 pub fn is_test_crate(&self) -> bool {
268 self.opts.test
269 }
270
271 #[track_caller]
273 pub fn create_feature_err<'a>(&'a self, err: impl Diagnostic<'a>, feature: Symbol) -> Diag<'a> {
274 let mut err = self.dcx().create_err(err);
275 if err.code.is_none() {
276 err.code(E0658);
277 }
278 errors::add_feature_diagnostics(&mut err, self, feature);
279 err
280 }
281
282 pub fn record_trimmed_def_paths(&self) {
285 if self.opts.unstable_opts.print_type_sizes
286 || self.opts.unstable_opts.query_dep_graph
287 || self.opts.unstable_opts.dump_mir.is_some()
288 || self.opts.unstable_opts.unpretty.is_some()
289 || self.prof.is_args_recording_enabled()
290 || self.opts.output_types.contains_key(&OutputType::Mir)
291 || std::env::var_os("RUSTC_LOG").is_some()
292 {
293 return;
294 }
295
296 self.dcx().set_must_produce_diag()
297 }
298
299 #[inline]
300 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
301 self.psess.dcx()
302 }
303
304 #[inline]
305 pub fn source_map(&self) -> &SourceMap {
306 self.psess.source_map()
307 }
308
309 pub fn proc_macro_quoted_spans(&self) -> impl Iterator<Item = (usize, Span)> {
310 self.proc_macro_quoted_spans.iter_enumerated()
313 }
314
315 pub fn save_proc_macro_span(&self, span: Span) -> usize {
316 self.proc_macro_quoted_spans.push(span)
317 }
318
319 pub fn enable_internal_lints(&self) -> bool {
323 self.unstable_options() && !self.opts.actually_rustdoc
324 }
325
326 pub fn instrument_coverage(&self) -> bool {
327 self.opts.cg.instrument_coverage() != InstrumentCoverage::No
328 }
329
330 pub fn instrument_coverage_branch(&self) -> bool {
331 self.instrument_coverage()
332 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Branch
333 }
334
335 pub fn instrument_coverage_condition(&self) -> bool {
336 self.instrument_coverage()
337 && self.opts.unstable_opts.coverage_options.level >= CoverageLevel::Condition
338 }
339
340 pub fn coverage_options(&self) -> &CoverageOptions {
344 &self.opts.unstable_opts.coverage_options
345 }
346
347 pub fn is_sanitizer_cfi_enabled(&self) -> bool {
348 self.sanitizers().contains(SanitizerSet::CFI)
349 }
350
351 pub fn is_sanitizer_cfi_canonical_jump_tables_disabled(&self) -> bool {
352 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(false)
353 }
354
355 pub fn is_sanitizer_cfi_canonical_jump_tables_enabled(&self) -> bool {
356 self.opts.unstable_opts.sanitizer_cfi_canonical_jump_tables == Some(true)
357 }
358
359 pub fn is_sanitizer_cfi_generalize_pointers_enabled(&self) -> bool {
360 self.opts.unstable_opts.sanitizer_cfi_generalize_pointers == Some(true)
361 }
362
363 pub fn is_sanitizer_cfi_normalize_integers_enabled(&self) -> bool {
364 self.opts.unstable_opts.sanitizer_cfi_normalize_integers == Some(true)
365 }
366
367 pub fn is_sanitizer_kcfi_arity_enabled(&self) -> bool {
368 self.opts.unstable_opts.sanitizer_kcfi_arity == Some(true)
369 }
370
371 pub fn is_sanitizer_kcfi_enabled(&self) -> bool {
372 self.sanitizers().contains(SanitizerSet::KCFI)
373 }
374
375 pub fn is_split_lto_unit_enabled(&self) -> bool {
376 self.opts.unstable_opts.split_lto_unit == Some(true)
377 }
378
379 pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
381 if !self.target.crt_static_respected {
382 return self.target.crt_static_default;
384 }
385
386 let requested_features = self.opts.cg.target_feature.split(',');
387 let found_negative = requested_features.clone().any(|r| r == "-crt-static");
388 let found_positive = requested_features.clone().any(|r| r == "+crt-static");
389
390 #[allow(rustc::bad_opt_access)]
392 if found_positive || found_negative {
393 found_positive
394 } else if crate_type == Some(CrateType::ProcMacro)
395 || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
396 {
397 false
401 } else {
402 self.target.crt_static_default
403 }
404 }
405
406 pub fn is_wasi_reactor(&self) -> bool {
407 self.target.options.os == Os::Wasi
408 && #[allow(non_exhaustive_omitted_patterns)] match self.opts.unstable_opts.wasi_exec_model
{
Some(config::WasiExecModel::Reactor) => true,
_ => false,
}matches!(
409 self.opts.unstable_opts.wasi_exec_model,
410 Some(config::WasiExecModel::Reactor)
411 )
412 }
413
414 pub fn target_can_use_split_dwarf(&self) -> bool {
416 self.target.debuginfo_kind == DebuginfoKind::Dwarf
417 }
418
419 pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String {
420 ::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())
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 }
557
558 pub fn diagnostic_width(&self) -> usize {
559 let default_column_width = 140;
560 if let Some(width) = self.opts.diagnostic_width {
561 width
562 } else if self.opts.unstable_opts.ui_testing {
563 default_column_width
564 } else {
565 termize::dimensions().map_or(default_column_width, |(w, _)| w)
566 }
567 }
568
569 pub fn default_visibility(&self) -> SymbolVisibility {
571 self.opts
572 .unstable_opts
573 .default_visibility
574 .or(self.target.options.default_visibility)
575 .unwrap_or(SymbolVisibility::Interposable)
576 }
577
578 pub fn staticlib_components(&self, verbatim: bool) -> (&str, &str) {
579 if verbatim {
580 ("", "")
581 } else {
582 (&*self.target.staticlib_prefix, &*self.target.staticlib_suffix)
583 }
584 }
585
586 pub fn lint_groups_iter(&self) -> Box<dyn Iterator<Item = LintGroup> + '_> {
587 match self.lint_store {
588 Some(ref lint_store) => lint_store.lint_groups_iter(),
589 None => Box::new(std::iter::empty()),
590 }
591 }
592}
593
594#[allow(rustc::bad_opt_access)]
596impl Session {
597 pub fn verbose_internals(&self) -> bool {
598 self.opts.unstable_opts.verbose_internals
599 }
600
601 pub fn print_llvm_stats(&self) -> bool {
602 self.opts.unstable_opts.print_codegen_stats
603 }
604
605 pub fn print_llvm_stats_json(&self) -> Option<&String> {
606 self.opts.unstable_opts.print_codegen_stats_json.as_ref()
607 }
608
609 pub fn verify_llvm_ir(&self) -> bool {
610 self.opts.unstable_opts.verify_llvm_ir || ::core::option::Option::None::<&'static str>option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
611 }
612
613 pub fn binary_dep_depinfo(&self) -> bool {
614 self.opts.unstable_opts.binary_dep_depinfo
615 }
616
617 pub fn mir_opt_level(&self) -> usize {
618 self.opts
619 .unstable_opts
620 .mir_opt_level
621 .unwrap_or_else(|| if self.opts.optimize != OptLevel::No { 2 } else { 1 })
622 }
623
624 pub fn lto(&self) -> config::Lto {
626 if self.target.requires_lto {
628 return config::Lto::Fat;
629 }
630
631 match self.opts.cg.lto {
635 config::LtoCli::Unspecified => {
636 }
639 config::LtoCli::No => {
640 return config::Lto::No;
642 }
643 config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
644 return config::Lto::Fat;
646 }
647 config::LtoCli::Thin => {
648 if !self.thin_lto_supported {
650 self.dcx().emit_warn(errors::ThinLtoNotSupportedByBackend);
652 return config::Lto::Fat;
653 }
654 return config::Lto::Thin;
655 }
656 }
657
658 if !self.thin_lto_supported {
659 return config::Lto::No;
660 }
661
662 if self.opts.cli_forced_local_thinlto_off {
671 return config::Lto::No;
672 }
673
674 if let Some(enabled) = self.opts.unstable_opts.thinlto {
677 if enabled {
678 return config::Lto::ThinLocal;
679 } else {
680 return config::Lto::No;
681 }
682 }
683
684 if self.codegen_units().as_usize() == 1 {
687 return config::Lto::No;
688 }
689
690 match self.opts.optimize {
693 config::OptLevel::No => config::Lto::No,
694 _ => config::Lto::ThinLocal,
695 }
696 }
697
698 pub fn panic_strategy(&self) -> PanicStrategy {
701 self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
702 }
703
704 pub fn fewer_names(&self) -> bool {
705 if let Some(fewer_names) = self.opts.unstable_opts.fewer_names {
706 fewer_names
707 } else {
708 let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
709 || self.opts.output_types.contains_key(&OutputType::Bitcode)
710 || self.opts.unstable_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
712 !more_names
713 }
714 }
715
716 pub fn unstable_options(&self) -> bool {
717 self.opts.unstable_opts.unstable_options
718 }
719
720 pub fn is_nightly_build(&self) -> bool {
721 self.opts.unstable_features.is_nightly_build()
722 }
723
724 pub fn overflow_checks(&self) -> bool {
725 self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)
726 }
727
728 pub fn ub_checks(&self) -> bool {
729 self.opts.unstable_opts.ub_checks.unwrap_or(self.opts.debug_assertions)
730 }
731
732 pub fn contract_checks(&self) -> bool {
733 self.opts.unstable_opts.contract_checks.unwrap_or(false)
734 }
735
736 pub fn relocation_model(&self) -> RelocModel {
737 self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
738 }
739
740 pub fn code_model(&self) -> Option<CodeModel> {
741 self.opts.cg.code_model.or(self.target.code_model)
742 }
743
744 pub fn tls_model(&self) -> TlsModel {
745 self.opts.unstable_opts.tls_model.unwrap_or(self.target.tls_model)
746 }
747
748 pub fn direct_access_external_data(&self) -> Option<bool> {
749 self.opts
750 .unstable_opts
751 .direct_access_external_data
752 .or(self.target.direct_access_external_data)
753 }
754
755 pub fn split_debuginfo(&self) -> SplitDebuginfo {
756 self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
757 }
758
759 pub fn dwarf_version(&self) -> u32 {
761 self.opts
762 .cg
763 .dwarf_version
764 .or(self.opts.unstable_opts.dwarf_version)
765 .unwrap_or(self.target.default_dwarf_version)
766 }
767
768 pub fn stack_protector(&self) -> StackProtector {
769 if self.target.options.supports_stack_protector {
770 self.opts.unstable_opts.stack_protector
771 } else {
772 StackProtector::None
773 }
774 }
775
776 pub fn must_emit_unwind_tables(&self) -> bool {
777 self.target.requires_uwtable
806 || self
807 .opts
808 .cg
809 .force_unwind_tables
810 .unwrap_or(self.panic_strategy().unwinds() || self.target.default_uwtable)
811 }
812
813 #[inline]
818 pub fn threads(&self) -> Option<usize> {
819 self.opts.unstable_opts.threads
820 }
821
822 pub fn codegen_units(&self) -> CodegenUnits {
825 if let Some(n) = self.opts.cli_forced_codegen_units {
826 return CodegenUnits::User(n);
827 }
828 if let Some(n) = self.target.default_codegen_units {
829 return CodegenUnits::Default(n as usize);
830 }
831
832 if self.opts.incremental.is_some() {
836 return CodegenUnits::Default(256);
837 }
838
839 CodegenUnits::Default(16)
890 }
891
892 pub fn teach(&self, code: ErrCode) -> bool {
893 self.opts.unstable_opts.teach && self.dcx().must_teach(code)
894 }
895
896 pub fn edition(&self) -> Edition {
897 self.opts.edition
898 }
899
900 pub fn link_dead_code(&self) -> bool {
901 self.opts.cg.link_dead_code.unwrap_or(false)
902 }
903
904 pub fn apple_deployment_target(&self) -> apple::OSVersion {
909 let min = apple::OSVersion::minimum_deployment_target(&self.target);
910 let env_var = apple::deployment_target_env_var(&self.target.os);
911
912 if let Ok(deployment_target) = env::var(env_var) {
914 match apple::OSVersion::from_str(&deployment_target) {
915 Ok(version) => {
916 let os_min = apple::OSVersion::os_minimum_deployment_target(&self.target.os);
917 if version < os_min {
922 self.dcx().emit_warn(errors::AppleDeploymentTarget::TooLow {
923 env_var,
924 version: version.fmt_pretty().to_string(),
925 os_min: os_min.fmt_pretty().to_string(),
926 });
927 }
928
929 version.max(min)
931 }
932 Err(error) => {
933 self.dcx().emit_err(errors::AppleDeploymentTarget::Invalid { env_var, error });
934 min
935 }
936 }
937 } else {
938 min
940 }
941 }
942
943 pub fn sanitizers(&self) -> SanitizerSet {
944 return self.opts.unstable_opts.sanitizer | self.target.options.default_sanitizers;
945 }
946}
947
948#[allow(rustc::bad_opt_access)]
950fn default_emitter(sopts: &config::Options, source_map: Arc<SourceMap>) -> Box<DynEmitter> {
951 let macro_backtrace = sopts.unstable_opts.macro_backtrace;
952 let track_diagnostics = sopts.unstable_opts.track_diagnostics;
953 let terminal_url = match sopts.unstable_opts.terminal_urls {
954 TerminalUrl::Auto => {
955 match (std::env::var("COLORTERM").as_deref(), std::env::var("TERM").as_deref()) {
956 (Ok("truecolor"), Ok("xterm-256color"))
957 if sopts.unstable_features.is_nightly_build() =>
958 {
959 TerminalUrl::Yes
960 }
961 _ => TerminalUrl::No,
962 }
963 }
964 t => t,
965 };
966
967 let source_map = if sopts.unstable_opts.link_only { None } else { Some(source_map) };
968
969 match sopts.error_format {
970 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
971 HumanReadableErrorType { short, unicode } => {
972 let emitter = AnnotateSnippetEmitter::new(stderr_destination(color_config))
973 .sm(source_map)
974 .short_message(short)
975 .diagnostic_width(sopts.diagnostic_width)
976 .macro_backtrace(macro_backtrace)
977 .track_diagnostics(track_diagnostics)
978 .terminal_url(terminal_url)
979 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
980 .ignored_directories_in_source_blocks(
981 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
982 );
983 Box::new(emitter.ui_testing(sopts.unstable_opts.ui_testing))
984 }
985 },
986 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => Box::new(
987 JsonEmitter::new(
988 Box::new(io::BufWriter::new(io::stderr())),
989 source_map,
990 pretty,
991 json_rendered,
992 color_config,
993 )
994 .ui_testing(sopts.unstable_opts.ui_testing)
995 .ignored_directories_in_source_blocks(
996 sopts.unstable_opts.ignore_directory_in_diagnostics_source_blocks.clone(),
997 )
998 .diagnostic_width(sopts.diagnostic_width)
999 .macro_backtrace(macro_backtrace)
1000 .track_diagnostics(track_diagnostics)
1001 .terminal_url(terminal_url),
1002 ),
1003 }
1004}
1005
1006#[allow(rustc::bad_opt_access)]
1008pub fn build_session(
1009 sopts: config::Options,
1010 io: CompilerIO,
1011 driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1012 target: Target,
1013 cfg_version: &'static str,
1014 ice_file: Option<PathBuf>,
1015 using_internal_features: &'static AtomicBool,
1016) -> Session {
1017 let warnings_allow = sopts
1021 .lint_opts
1022 .iter()
1023 .rfind(|&(key, _)| *key == "warnings")
1024 .is_some_and(|&(_, level)| level == lint::Allow);
1025 let cap_lints_allow = sopts.lint_cap.is_some_and(|cap| cap == lint::Allow);
1026 let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1027
1028 let source_map = rustc_span::source_map::get_source_map().unwrap();
1029 let emitter = default_emitter(&sopts, Arc::clone(&source_map));
1030
1031 let mut dcx =
1032 DiagCtxt::new(emitter).with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));
1033 if let Some(ice_file) = ice_file {
1034 dcx = dcx.with_ice_file(ice_file);
1035 }
1036
1037 let host_triple = TargetTuple::from_tuple(config::host_tuple());
1038 let (host, target_warnings) =
1039 Target::search(&host_triple, sopts.sysroot.path(), sopts.unstable_opts.unstable_options)
1040 .unwrap_or_else(|e| {
1041 dcx.handle().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Error loading host specification: {0}",
e))
})format!("Error loading host specification: {e}"))
1042 });
1043 for warning in target_warnings.warning_messages() {
1044 dcx.handle().warn(warning)
1045 }
1046
1047 let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
1048 {
1049 let directory = if let Some(directory) = d { directory } else { std::path::Path::new(".") };
1050
1051 let profiler = SelfProfiler::new(
1052 directory,
1053 sopts.crate_name.as_deref(),
1054 sopts.unstable_opts.self_profile_events.as_deref(),
1055 &sopts.unstable_opts.self_profile_counter,
1056 );
1057 match profiler {
1058 Ok(profiler) => Some(Arc::new(profiler)),
1059 Err(e) => {
1060 dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1061 None
1062 }
1063 }
1064 } else {
1065 None
1066 };
1067
1068 let psess = ParseSess::with_dcx(dcx, source_map);
1069
1070 let host_triple = config::host_tuple();
1071 let target_triple = sopts.target_triple.tuple();
1072 let host_tlib_path =
1074 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), host_triple));
1075 let target_tlib_path = if host_triple == target_triple {
1076 Arc::clone(&host_tlib_path)
1079 } else {
1080 Arc::new(SearchPath::from_sysroot_and_triple(sopts.sysroot.path(), target_triple))
1081 };
1082
1083 let prof = SelfProfilerRef::new(
1084 self_profiler,
1085 sopts.unstable_opts.time_passes.then(|| sopts.unstable_opts.time_passes_format),
1086 );
1087
1088 let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1089 Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1090 Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1091 _ => CtfeBacktrace::Disabled,
1092 });
1093
1094 let asm_arch = if target.allow_asm { InlineAsmArch::from_arch(&target.arch) } else { None };
1095 let target_filesearch =
1096 filesearch::FileSearch::new(&sopts.search_paths, &target_tlib_path, &target);
1097 let host_filesearch = filesearch::FileSearch::new(&sopts.search_paths, &host_tlib_path, &host);
1098
1099 let timings = TimingSectionHandler::new(sopts.json_timings);
1100
1101 let sess = Session {
1102 target,
1103 host,
1104 opts: sopts,
1105 target_tlib_path,
1106 psess,
1107 unstable_features: UnstableFeatures::from_environment(None),
1108 config: Cfg::default(),
1109 check_config: CheckCfg::default(),
1110 proc_macro_quoted_spans: Default::default(),
1111 io,
1112 incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
1113 prof,
1114 timings,
1115 code_stats: Default::default(),
1116 lint_store: None,
1117 driver_lint_caps,
1118 ctfe_backtrace,
1119 miri_unleashed_features: Lock::new(Default::default()),
1120 asm_arch,
1121 target_features: Default::default(),
1122 unstable_target_features: Default::default(),
1123 cfg_version,
1124 using_internal_features,
1125 env_depinfo: Default::default(),
1126 file_depinfo: Default::default(),
1127 target_filesearch,
1128 host_filesearch,
1129 replaced_intrinsics: FxHashSet::default(), fallback_intrinsics: FxHashSet::default(), thin_lto_supported: true, mir_opt_bisect_eval_count: AtomicUsize::new(0),
1133 used_features: Lock::default(),
1134 };
1135
1136 validate_commandline_args_with_session_available(&sess);
1137
1138 sess
1139}
1140
1141#[allow(rustc::bad_opt_access)]
1147fn validate_commandline_args_with_session_available(sess: &Session) {
1148 if sess.opts.cg.linker_plugin_lto.enabled()
1156 && sess.opts.cg.prefer_dynamic
1157 && sess.target.is_like_windows
1158 {
1159 sess.dcx().emit_err(errors::LinkerPluginToWindowsNotSupported);
1160 }
1161
1162 if let Some(ref path) = sess.opts.cg.profile_use {
1165 if !path.exists() {
1166 sess.dcx().emit_err(errors::ProfileUseFileDoesNotExist { path });
1167 }
1168 }
1169
1170 if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use {
1172 if !path.exists() {
1173 sess.dcx().emit_err(errors::ProfileSampleUseFileDoesNotExist { path });
1174 }
1175 }
1176
1177 if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1179 if sess.target.requires_uwtable && !include_uwtables {
1180 sess.dcx().emit_err(errors::TargetRequiresUnwindTables);
1181 }
1182 }
1183
1184 let supported_sanitizers = sess.target.options.supported_sanitizers;
1186 let mut unsupported_sanitizers = sess.opts.unstable_opts.sanitizer - supported_sanitizers;
1187 if sess.opts.unstable_opts.fixed_x18 && sess.target.arch == Arch::AArch64 {
1190 unsupported_sanitizers -= SanitizerSet::SHADOWCALLSTACK;
1191 }
1192 match unsupported_sanitizers.into_iter().count() {
1193 0 => {}
1194 1 => {
1195 sess.dcx()
1196 .emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() });
1197 }
1198 _ => {
1199 sess.dcx().emit_err(errors::SanitizersNotSupported {
1200 us: unsupported_sanitizers.to_string(),
1201 });
1202 }
1203 }
1204
1205 if let Some((first, second)) = sess.opts.unstable_opts.sanitizer.mutually_exclusive() {
1207 sess.dcx().emit_err(errors::CannotMixAndMatchSanitizers {
1208 first: first.to_string(),
1209 second: second.to_string(),
1210 });
1211 }
1212
1213 if sess.crt_static(None)
1215 && !sess.opts.unstable_opts.sanitizer.is_empty()
1216 && !sess.target.is_like_msvc
1217 {
1218 sess.dcx().emit_err(errors::CannotEnableCrtStaticLinux);
1219 }
1220
1221 if sess.is_sanitizer_cfi_enabled()
1223 && !(sess.lto() == config::Lto::Fat || sess.opts.cg.linker_plugin_lto.enabled())
1224 {
1225 sess.dcx().emit_err(errors::SanitizerCfiRequiresLto);
1226 }
1227
1228 if sess.is_sanitizer_kcfi_enabled() && sess.panic_strategy().unwinds() {
1230 sess.dcx().emit_err(errors::SanitizerKcfiRequiresPanicAbort);
1231 }
1232
1233 if sess.is_sanitizer_cfi_enabled()
1235 && sess.lto() == config::Lto::Fat
1236 && (sess.codegen_units().as_usize() != 1)
1237 {
1238 sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
1239 }
1240
1241 if sess.is_sanitizer_cfi_canonical_jump_tables_disabled() {
1243 if !sess.is_sanitizer_cfi_enabled() {
1244 sess.dcx().emit_err(errors::SanitizerCfiCanonicalJumpTablesRequiresCfi);
1245 }
1246 }
1247
1248 if sess.is_sanitizer_kcfi_arity_enabled() && !sess.is_sanitizer_kcfi_enabled() {
1250 sess.dcx().emit_err(errors::SanitizerKcfiArityRequiresKcfi);
1251 }
1252
1253 if sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1255 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1256 sess.dcx().emit_err(errors::SanitizerCfiGeneralizePointersRequiresCfi);
1257 }
1258 }
1259
1260 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
1262 if !(sess.is_sanitizer_cfi_enabled() || sess.is_sanitizer_kcfi_enabled()) {
1263 sess.dcx().emit_err(errors::SanitizerCfiNormalizeIntegersRequiresCfi);
1264 }
1265 }
1266
1267 if sess.is_split_lto_unit_enabled()
1269 && !(sess.lto() == config::Lto::Fat
1270 || sess.lto() == config::Lto::Thin
1271 || sess.opts.cg.linker_plugin_lto.enabled())
1272 {
1273 sess.dcx().emit_err(errors::SplitLtoUnitRequiresLto);
1274 }
1275
1276 if sess.lto() != config::Lto::Fat {
1278 if sess.opts.unstable_opts.virtual_function_elimination {
1279 sess.dcx().emit_err(errors::UnstableVirtualFunctionElimination);
1280 }
1281 }
1282
1283 if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1284 if !sess.target.options.supports_stack_protector {
1285 sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1286 stack_protector: sess.opts.unstable_opts.stack_protector,
1287 target_triple: &sess.opts.target_triple,
1288 });
1289 }
1290 }
1291
1292 if sess.opts.unstable_opts.small_data_threshold.is_some() {
1293 if sess.target.small_data_threshold_support() == SmallDataThresholdSupport::None {
1294 sess.dcx().emit_warn(errors::SmallDataThresholdNotSupportedForTarget {
1295 target_triple: &sess.opts.target_triple,
1296 })
1297 }
1298 }
1299
1300 if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != Arch::AArch64 {
1301 sess.dcx().emit_err(errors::BranchProtectionRequiresAArch64);
1302 }
1303
1304 if let Some(dwarf_version) =
1305 sess.opts.cg.dwarf_version.or(sess.opts.unstable_opts.dwarf_version)
1306 {
1307 if dwarf_version < 2 || dwarf_version > 5 {
1309 sess.dcx().emit_err(errors::UnsupportedDwarfVersion { dwarf_version });
1310 }
1311 }
1312
1313 if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo())
1314 && !sess.opts.unstable_opts.unstable_options
1315 {
1316 sess.dcx()
1317 .emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() });
1318 }
1319
1320 if sess.opts.unstable_opts.embed_source {
1321 let dwarf_version = sess.dwarf_version();
1322
1323 if dwarf_version < 5 {
1324 sess.dcx().emit_warn(errors::EmbedSourceInsufficientDwarfVersion { dwarf_version });
1325 }
1326
1327 if sess.opts.debuginfo == DebugInfo::None {
1328 sess.dcx().emit_warn(errors::EmbedSourceRequiresDebugInfo);
1329 }
1330 }
1331
1332 if sess.opts.unstable_opts.instrument_xray.is_some() && !sess.target.options.supports_xray {
1333 sess.dcx().emit_err(errors::InstrumentationNotSupported { us: "XRay".to_string() });
1334 }
1335
1336 if let Some(flavor) = sess.opts.cg.linker_flavor
1337 && let Some(compatible_list) = sess.target.linker_flavor.check_compatibility(flavor)
1338 {
1339 let flavor = flavor.desc();
1340 sess.dcx().emit_err(errors::IncompatibleLinkerFlavor { flavor, compatible_list });
1341 }
1342
1343 if sess.opts.unstable_opts.function_return != FunctionReturn::default() {
1344 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) {
1345 sess.dcx().emit_err(errors::FunctionReturnRequiresX86OrX8664);
1346 }
1347 }
1348
1349 if sess.opts.unstable_opts.indirect_branch_cs_prefix {
1350 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) {
1351 sess.dcx().emit_err(errors::IndirectBranchCsPrefixRequiresX86OrX8664);
1352 }
1353 }
1354
1355 if let Some(regparm) = sess.opts.unstable_opts.regparm {
1356 if regparm > 3 {
1357 sess.dcx().emit_err(errors::UnsupportedRegparm { regparm });
1358 }
1359 if sess.target.arch != Arch::X86 {
1360 sess.dcx().emit_err(errors::UnsupportedRegparmArch);
1361 }
1362 }
1363 if sess.opts.unstable_opts.reg_struct_return {
1364 if sess.target.arch != Arch::X86 {
1365 sess.dcx().emit_err(errors::UnsupportedRegStructReturnArch);
1366 }
1367 }
1368
1369 match sess.opts.unstable_opts.function_return {
1373 FunctionReturn::Keep => (),
1374 FunctionReturn::ThunkExtern => {
1375 if let Some(code_model) = sess.code_model()
1378 && code_model == CodeModel::Large
1379 {
1380 sess.dcx().emit_err(errors::FunctionReturnThunkExternRequiresNonLargeCodeModel);
1381 }
1382 }
1383 }
1384
1385 if sess.opts.unstable_opts.packed_stack {
1386 if sess.target.arch != Arch::S390x {
1387 sess.dcx().emit_err(errors::UnsupportedPackedStack);
1388 }
1389 }
1390}
1391
1392#[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)]
1394enum IncrCompSession {
1395 NotInitialized,
1398 Active { session_directory: PathBuf, _lock_file: flock::Lock },
1403 Finalized { session_directory: PathBuf },
1406 InvalidBecauseOfErrors { session_directory: PathBuf },
1410}
1411
1412pub struct EarlyDiagCtxt {
1414 dcx: DiagCtxt,
1415}
1416
1417impl EarlyDiagCtxt {
1418 pub fn new(output: ErrorOutputType) -> Self {
1419 let emitter = mk_emitter(output);
1420 Self { dcx: DiagCtxt::new(emitter) }
1421 }
1422
1423 pub fn set_error_format(&mut self, output: ErrorOutputType) {
1426 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());
1427
1428 let emitter = mk_emitter(output);
1429 self.dcx = DiagCtxt::new(emitter);
1430 }
1431
1432 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1433 self.dcx.handle().note(msg)
1434 }
1435
1436 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1437 self.dcx.handle().struct_help(msg).emit()
1438 }
1439
1440 #[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
1441 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1442 self.dcx.handle().err(msg)
1443 }
1444
1445 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1446 self.dcx.handle().fatal(msg)
1447 }
1448
1449 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1450 self.dcx.handle().struct_fatal(msg)
1451 }
1452
1453 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1454 self.dcx.handle().warn(msg)
1455 }
1456
1457 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1458 self.dcx.handle().struct_warn(msg)
1459 }
1460}
1461
1462fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {
1463 let emitter: Box<DynEmitter> = match output {
1464 config::ErrorOutputType::HumanReadable { kind, color_config } => match kind {
1465 HumanReadableErrorType { short, unicode } => Box::new(
1466 AnnotateSnippetEmitter::new(stderr_destination(color_config))
1467 .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
1468 .short_message(short),
1469 ),
1470 },
1471 config::ErrorOutputType::Json { pretty, json_rendered, color_config } => {
1472 Box::new(JsonEmitter::new(
1473 Box::new(io::BufWriter::new(io::stderr())),
1474 Some(Arc::new(SourceMap::new(FilePathMapping::empty()))),
1475 pretty,
1476 json_rendered,
1477 color_config,
1478 ))
1479 }
1480 };
1481 emitter
1482}