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