solar_interface/diagnostics/
context.rs1use super::{
6 BugAbort, Diag, DiagBuilder, DiagMsg, DynEmitter, EmissionGuarantee, EmittedDiagnostics,
7 ErrorGuaranteed, FatalAbort, HumanBufferEmitter, Level, MultiSpan, SilentEmitter,
8 emitter::HumanEmitter,
9};
10use crate::{Result, SourceMap, Span};
11use anstream::ColorChoice;
12use rayon::prelude::*;
13use solar_config::{CompileOpts, ErrorFormat};
14use solar_data_structures::{map::FxHashSet, sync::Mutex};
15#[cfg(debug_assertions)]
16use std::sync::atomic::{AtomicUsize, Ordering};
17use std::{
18 borrow::Cow,
19 cell::RefCell,
20 fmt,
21 hash::BuildHasher,
22 mem,
23 num::NonZeroUsize,
24 sync::{Arc, Weak},
25 time::Duration,
26};
27
28thread_local! {
29 static DEFERRED: RefCell<Option<Deferral>> = const { RefCell::new(None) };
33}
34
35#[cfg(debug_assertions)]
36thread_local! {
37 static DEFERRING: RefCell<Vec<*const DiagCtxt>> = const { RefCell::new(Vec::new()) };
39}
40
41static WITHHOLDING: Mutex<Vec<Weak<Mutex<DiagCtxtInner>>>> = Mutex::new(Vec::new());
43
44struct Deferral {
45 dcx: *const DiagCtxt,
46 batch: Option<Arc<Batch>>,
48}
49
50type Withholding<'a> = (&'a Arc<Mutex<DiagCtxtInner>>, &'a mut Option<Arc<Batch>>);
52
53struct Batch {
58 dcx: Arc<Mutex<DiagCtxtInner>>,
59 diagnostics: Mutex<Vec<Diag>>,
60}
61
62impl Drop for Batch {
63 fn drop(&mut self) {
64 let diagnostics = mem::take(self.diagnostics.get_mut());
65 if !diagnostics.is_empty() {
66 let mut inner = self.dcx.lock();
67 for mut diagnostic in diagnostics {
68 inner.deliver_diagnostic(&mut diagnostic);
69 }
70 }
71 }
72}
73
74#[derive(Default)]
76#[must_use = "pass deferred diagnostics to `DiagCtxt::emit_deferred`"]
77pub struct DeferredDiagnostics(Vec<Arc<Batch>>);
78
79impl fmt::Debug for DeferredDiagnostics {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 f.debug_tuple("DeferredDiagnostics").field(&self.0.len()).finish()
82 }
83}
84
85impl DeferredDiagnostics {
86 pub fn append(&mut self, mut other: Self) {
88 self.0.append(&mut other.0);
89 }
90
91 pub fn is_empty(&self) -> bool {
93 self.0.iter().all(|batch| batch.diagnostics.lock().is_empty())
94 }
95
96 pub fn sort_by_cached_key<K: Ord>(&mut self, f: impl FnMut(&Diag) -> K) {
98 let mut diagnostics = self.take_diagnostics();
99 diagnostics.sort_by_cached_key(f);
100 if let Some(batch) = self.0.first() {
101 batch.diagnostics.lock().extend(diagnostics);
102 self.0.truncate(1);
103 }
104 }
105
106 fn take_diagnostics(&self) -> Vec<Diag> {
107 let mut diagnostics = Vec::new();
108 for batch in &self.0 {
109 diagnostics.append(&mut batch.diagnostics.lock());
110 }
111 diagnostics
112 }
113}
114
115fn flush_inner(inner: &Mutex<DiagCtxtInner>) {
116 if let Some(mut inner) = inner.try_lock_for(Duration::from_millis(500)) {
117 inner.flush_withheld();
118 }
119}
120
121pub fn flush_withheld() {
126 let contexts = WITHHOLDING.lock().clone();
127 for context in contexts {
128 if let Some(context) = context.upgrade() {
129 flush_inner(&context);
130 }
131 }
132}
133
134#[derive(Clone, Copy, Debug)]
136pub struct DiagCtxtFlags {
137 pub can_emit_warnings: bool,
139 pub treat_err_as_bug: Option<NonZeroUsize>,
141 pub deduplicate_diagnostics: bool,
143 pub track_diagnostics: bool,
146}
147
148impl Default for DiagCtxtFlags {
149 fn default() -> Self {
150 Self {
151 can_emit_warnings: true,
152 treat_err_as_bug: None,
153 deduplicate_diagnostics: true,
154 track_diagnostics: cfg!(debug_assertions),
155 }
156 }
157}
158
159impl DiagCtxtFlags {
160 pub fn update_from_opts(&mut self, opts: &CompileOpts) {
167 self.deduplicate_diagnostics &= !opts.unstable.ui_testing;
168 self.track_diagnostics &= !opts.unstable.ui_testing;
169 self.track_diagnostics |= opts.unstable.track_diagnostics;
170 self.can_emit_warnings &= !opts.no_warnings;
171 }
172}
173
174pub struct DiagCtxt {
178 inner: Arc<Mutex<DiagCtxtInner>>,
179 #[cfg(debug_assertions)]
181 defers: AtomicUsize,
182}
183
184impl fmt::Debug for DiagCtxt {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 let mut s = f.debug_struct("DiagCtxt");
187 if let Some(inner) = self.inner.try_lock() {
188 s.field("flags", &inner.flags)
189 .field("err_count", &inner.err_count)
190 .field("warn_count", &inner.warn_count)
191 .field("note_count", &inner.note_count);
192 } else {
193 s.field("inner", &format_args!("<locked>"));
194 }
195 s.finish_non_exhaustive()
196 }
197}
198
199struct DiagCtxtInner {
200 emitter: Box<DynEmitter>,
201
202 flags: DiagCtxtFlags,
203 allowed_diagnostic_codes: FxHashSet<String>,
204
205 err_count: usize,
210 deduplicated_err_count: usize,
211 warn_count: usize,
213 deduplicated_warn_count: usize,
214 note_count: usize,
216 deduplicated_note_count: usize,
217
218 emitted_diagnostics: FxHashSet<u64>,
221
222 withheld: Vec<Weak<Batch>>,
224 prune_withheld_at: usize,
225 registered: bool,
227}
228
229impl DiagCtxt {
230 pub fn new(emitter: Box<DynEmitter>) -> Self {
232 Self {
233 #[cfg(debug_assertions)]
234 defers: AtomicUsize::new(0),
235 inner: Arc::new(Mutex::new(DiagCtxtInner {
236 emitter,
237 flags: DiagCtxtFlags::default(),
238 allowed_diagnostic_codes: FxHashSet::default(),
239 err_count: 0,
240 deduplicated_err_count: 0,
241 warn_count: 0,
242 deduplicated_warn_count: 0,
243 note_count: 0,
244 deduplicated_note_count: 0,
245 emitted_diagnostics: FxHashSet::default(),
246 withheld: Vec::new(),
247 prune_withheld_at: 64,
248 registered: false,
249 })),
250 }
251 }
252
253 pub fn new_early() -> Self {
256 Self::with_stderr_emitter(None).with_flags(|flags| flags.track_diagnostics = false)
257 }
258
259 pub fn with_test_emitter(source_map: Option<Arc<SourceMap>>) -> Self {
261 Self::new(Box::new(HumanEmitter::test().source_map(source_map)))
262 }
263
264 pub fn with_stderr_emitter(source_map: Option<Arc<SourceMap>>) -> Self {
266 Self::with_stderr_emitter_and_color(source_map, ColorChoice::Auto)
267 }
268
269 pub fn with_stderr_emitter_and_color(
271 source_map: Option<Arc<SourceMap>>,
272 color_choice: ColorChoice,
273 ) -> Self {
274 Self::new(Box::new(HumanEmitter::stderr(color_choice).source_map(source_map)))
275 }
276
277 pub fn with_silent_emitter(fatal_note: Option<String>) -> Self {
281 let fatal_emitter = HumanEmitter::stderr(Default::default());
282 Self::new(Box::new(SilentEmitter::new(fatal_emitter).with_note(fatal_note)))
283 .disable_warnings()
284 }
285
286 pub fn with_buffer_emitter(
288 source_map: Option<Arc<SourceMap>>,
289 color_choice: ColorChoice,
290 ) -> Self {
291 Self::new(Box::new(HumanBufferEmitter::new(color_choice).source_map(source_map)))
292 }
293
294 pub fn from_opts(opts: &solar_config::CompileOpts) -> Self {
310 let source_map = Arc::new(SourceMap::empty());
311 let emitter: Box<DynEmitter> = match opts.error_format {
312 ErrorFormat::Human => {
313 let human = HumanEmitter::stderr(opts.color)
314 .source_map(Some(source_map))
315 .ui_testing(opts.unstable.ui_testing)
316 .human_kind(opts.error_format_human)
317 .terminal_width(opts.diagnostic_width);
318 Box::new(human)
319 }
320 #[cfg(feature = "json")]
321 ErrorFormat::Json | ErrorFormat::RustcJson => {
322 let writer = Box::new(std::io::BufWriter::new(std::io::stderr()));
324 let json = crate::diagnostics::JsonEmitter::new(writer, source_map, opts.color)
325 .pretty(opts.pretty_json_err)
326 .rustc_like(matches!(opts.error_format, ErrorFormat::RustcJson))
327 .ui_testing(opts.unstable.ui_testing)
328 .human_kind(opts.error_format_human)
329 .terminal_width(opts.diagnostic_width);
330 Box::new(json)
331 }
332 format => unimplemented!("{format:?}"),
333 };
334 Self::new(emitter)
335 .with_flags(|flags| flags.update_from_opts(opts))
336 .with_allowed_diagnostic_codes(opts.allow.iter().cloned())
337 }
338
339 pub fn with_allowed_diagnostic_codes(
341 mut self,
342 codes: impl IntoIterator<Item = String>,
343 ) -> Self {
344 self.set_allowed_diagnostic_codes_mut(codes);
345 self
346 }
347
348 pub fn make_silent(&self, fatal_note: Option<String>, emit_fatal: bool) {
350 self.wrap_emitter(|prev| {
351 Box::new(SilentEmitter::new_boxed(emit_fatal.then_some(prev)).with_note(fatal_note))
352 });
353 }
354
355 pub fn set_emitter(&self, emitter: Box<DynEmitter>) -> Box<DynEmitter> {
357 std::mem::replace(&mut self.inner.lock().emitter, emitter)
358 }
359
360 pub fn wrap_emitter(&self, f: impl FnOnce(Box<DynEmitter>) -> Box<DynEmitter>) {
362 struct FakeEmitter;
363 impl crate::diagnostics::Emitter for FakeEmitter {
364 fn emit_diagnostic(&mut self, _diagnostic: &mut Diag) {}
365 }
366
367 let mut inner = self.inner.lock();
368 let prev = std::mem::replace(&mut inner.emitter, Box::new(FakeEmitter));
369 inner.emitter = f(prev);
370 }
371
372 pub fn source_map(&self) -> Option<Arc<SourceMap>> {
374 self.inner.lock().emitter.source_map().cloned()
375 }
376
377 pub fn with_flags(mut self, f: impl FnOnce(&mut DiagCtxtFlags)) -> Self {
379 self.set_flags_mut(f);
380 self
381 }
382
383 pub fn set_flags(&self, f: impl FnOnce(&mut DiagCtxtFlags)) {
385 f(&mut self.inner.lock().flags);
386 }
387
388 pub fn set_flags_mut(&mut self, f: impl FnOnce(&mut DiagCtxtFlags)) {
390 f(&mut self.inner.lock().flags);
391 }
392
393 pub fn set_allowed_diagnostic_codes(&self, codes: impl IntoIterator<Item = String>) {
395 self.inner.lock().allowed_diagnostic_codes.extend(codes);
396 }
397
398 pub fn set_allowed_diagnostic_codes_mut(&mut self, codes: impl IntoIterator<Item = String>) {
400 self.inner.lock().allowed_diagnostic_codes.extend(codes);
401 }
402
403 pub fn disable_warnings(self) -> Self {
405 self.with_flags(|f| f.can_emit_warnings = false)
406 }
407
408 pub fn can_emit_warnings(&self) -> bool {
410 self.inner.lock().flags.can_emit_warnings
411 }
412
413 pub fn reset_err_count(&self) {
417 let mut inner = self.inner.lock();
418 inner.err_count = 0;
419 inner.deduplicated_err_count = 0;
420 inner.warn_count = 0;
421 inner.deduplicated_warn_count = 0;
422 inner.note_count = 0;
423 inner.deduplicated_note_count = 0;
424 inner.emitted_diagnostics.clear();
425 }
426
427 pub fn track_diagnostics(&self) -> bool {
429 self.inner.lock().flags.track_diagnostics
430 }
431
432 #[inline]
434 pub fn emit_diagnostic(&self, mut diagnostic: Diag) -> Result<(), ErrorGuaranteed> {
435 self.emit_diagnostic_without_consuming(&mut diagnostic)
436 }
437
438 pub(super) fn emit_diagnostic_without_consuming(
443 &self,
444 diagnostic: &mut Diag,
445 ) -> Result<(), ErrorGuaranteed> {
446 let mut deferral = self.take_deferral();
447 #[cfg(debug_assertions)]
448 debug_assert!(
449 deferral.is_some()
450 || self.defers.load(Ordering::Relaxed) == 0
451 || DEFERRING
452 .with_borrow(|deferring| deferring.iter().any(|&dcx| std::ptr::eq(dcx, self)))
453 || matches!(diagnostic.level, Level::Bug | Level::Fatal),
454 "diagnostic emitted outside the deferral that its parallel work expects: {:?}",
455 diagnostic.messages.first().map(|(message, _)| message.as_str()),
456 );
457 let result = self.inner.lock().emit_diagnostic_without_consuming(
458 diagnostic,
459 deferral.as_mut().map(|deferral| (&self.inner, &mut deferral.batch)),
460 );
461 self.restore_deferral(deferral);
462 result
463 }
464
465 fn take_deferral(&self) -> Option<Deferral> {
467 DEFERRED.with_borrow_mut(|deferral| {
468 deferral.take_if(|deferral| std::ptr::eq(deferral.dcx, self))
469 })
470 }
471
472 fn restore_deferral(&self, deferral: Option<Deferral>) {
473 if deferral.is_some() {
474 DEFERRED.set(deferral);
475 }
476 }
477
478 pub fn defer<R>(&self, f: impl FnOnce() -> R) -> (R, DeferredDiagnostics) {
487 struct Restore<'a> {
490 #[cfg_attr(not(debug_assertions), allow(dead_code))]
491 dcx: &'a DiagCtxt,
492 outer: Option<Deferral>,
493 }
494 impl Drop for Restore<'_> {
495 fn drop(&mut self) {
496 DEFERRED.set(self.outer.take());
497 #[cfg(debug_assertions)]
498 {
499 self.dcx.defers.fetch_sub(1, Ordering::Relaxed);
500 DEFERRING.with_borrow_mut(|deferring| deferring.pop());
501 }
502 }
503 }
504
505 #[cfg(debug_assertions)]
506 {
507 self.defers.fetch_add(1, Ordering::Relaxed);
508 DEFERRING.with_borrow_mut(|deferring| deferring.push(self));
509 }
510 let outer = DEFERRED.replace(Some(Deferral { dcx: self, batch: None }));
511 let restore = Restore { dcx: self, outer };
512 let result = f();
513 let deferral = DEFERRED.take();
514 drop(restore);
515 (
516 result,
517 DeferredDiagnostics(deferral.and_then(|deferral| deferral.batch).into_iter().collect()),
518 )
519 }
520
521 pub fn emit_deferred(&self, deferred: DeferredDiagnostics) {
525 let diagnostics = deferred.take_diagnostics();
526 if diagnostics.is_empty() {
527 return;
528 }
529 let mut deferral = self.take_deferral();
530 {
531 let mut inner = self.inner.lock();
532 match deferral.as_mut() {
533 Some(deferral) => {
534 let batch = inner.withhold(&self.inner, &mut deferral.batch);
535 batch.diagnostics.lock().extend(diagnostics);
536 }
537 None => {
538 for mut diagnostic in diagnostics {
539 inner.deliver_diagnostic(&mut diagnostic);
540 }
541 }
542 }
543 }
544 self.restore_deferral(deferral);
545 }
546
547 pub fn flush_withheld(&self) {
550 flush_inner(&self.inner);
551 }
552
553 pub fn par_defer<I, R>(
558 &self,
559 iter: I,
560 f: impl Fn(I::Item) -> R + Sync + Send,
561 ) -> (Vec<R>, DeferredDiagnostics)
562 where
563 I: ParallelIterator,
564 R: Send,
565 {
566 let outputs = iter.map(|item| self.defer(|| f(item))).collect::<Vec<_>>();
567 let mut results = Vec::with_capacity(outputs.len());
568 let mut deferred = DeferredDiagnostics::default();
569 for (result, batch) in outputs {
570 results.push(result);
571 deferred.append(batch);
572 }
573 (results, deferred)
574 }
575
576 pub fn par_for_each<I>(&self, iter: I, f: impl Fn(I::Item) + Sync + Send)
579 where
580 I: ParallelIterator,
581 {
582 self.emit_deferred(self.par_defer(iter, f).1);
583 }
584
585 pub fn err_count(&self) -> usize {
587 self.inner.lock().err_count
588 }
589
590 pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
592 if self.inner.lock().has_errors() { Err(ErrorGuaranteed::new_unchecked()) } else { Ok(()) }
593 }
594
595 pub fn warn_count(&self) -> usize {
597 self.inner.lock().warn_count
598 }
599
600 pub fn note_count(&self) -> usize {
602 self.inner.lock().note_count
603 }
604
605 #[inline]
623 pub fn emitted_diagnostics_result(
624 &self,
625 ) -> Option<Result<EmittedDiagnostics, EmittedDiagnostics>> {
626 let inner = self.inner.lock();
627 let diags = EmittedDiagnostics(inner.emitter.local_buffer()?.to_string());
628 Some(if inner.has_errors() { Err(diags) } else { Ok(diags) })
629 }
630
631 pub fn emitted_diagnostics(&self) -> Option<EmittedDiagnostics> {
636 let inner = self.inner.lock();
637 Some(EmittedDiagnostics(inner.emitter.local_buffer()?.to_string()))
638 }
639
640 pub fn emitted_errors(&self) -> Option<Result<(), EmittedDiagnostics>> {
645 let inner = self.inner.lock();
646 let buffer = inner.emitter.local_buffer()?;
647 Some(if inner.has_errors() { Err(EmittedDiagnostics(buffer.to_string())) } else { Ok(()) })
648 }
649
650 pub fn print_error_count(&self) -> Result {
652 self.inner.lock().print_error_count()
653 }
654}
655
656impl DiagCtxt {
660 #[track_caller]
662 pub fn diag<G: EmissionGuarantee>(
663 &self,
664 level: Level,
665 msg: impl Into<DiagMsg>,
666 ) -> DiagBuilder<'_, G> {
667 DiagBuilder::new(self, level, msg)
668 }
669
670 #[track_caller]
672 #[cold]
673 pub fn bug(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, BugAbort> {
674 self.diag(Level::Bug, msg)
675 }
676
677 #[track_caller]
679 #[cold]
680 pub fn fatal(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, FatalAbort> {
681 self.diag(Level::Fatal, msg)
682 }
683
684 #[track_caller]
686 pub fn err(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ErrorGuaranteed> {
687 self.diag(Level::Error, msg)
688 }
689
690 #[track_caller]
692 pub fn emit_err(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagMsg>) -> ErrorGuaranteed {
693 self.err(msg).span(span).emit()
694 }
695
696 #[track_caller]
698 pub fn emit_err_note(
699 &self,
700 span: impl Into<MultiSpan>,
701 msg: impl Into<DiagMsg>,
702 note: impl Into<DiagMsg>,
703 ) -> ErrorGuaranteed {
704 self.err(msg).span(span).note(note).emit()
705 }
706
707 #[track_caller]
709 pub fn emit_err_span_note(
710 &self,
711 span: impl Into<MultiSpan>,
712 msg: impl Into<DiagMsg>,
713 note_span: impl Into<MultiSpan>,
714 note: impl Into<DiagMsg>,
715 ) -> ErrorGuaranteed {
716 self.err(msg).span(span).span_note(note_span, note).emit()
717 }
718
719 #[track_caller]
721 pub fn emit_err_label(
722 &self,
723 span: impl Into<MultiSpan>,
724 msg: impl Into<DiagMsg>,
725 label_span: Span,
726 label: impl Into<DiagMsg>,
727 ) -> ErrorGuaranteed {
728 self.err(msg).span(span).span_label(label_span, label).emit()
729 }
730
731 #[track_caller]
735 pub fn warn(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ()> {
736 self.diag(Level::Warning, msg)
737 }
738
739 #[track_caller]
741 pub fn help(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ()> {
742 self.diag(Level::Help, msg)
743 }
744
745 #[track_caller]
747 pub fn note(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ()> {
748 self.diag(Level::Note, msg)
749 }
750}
751
752impl DiagCtxtInner {
753 fn emit_diagnostic(&mut self, mut diagnostic: Diag) -> Result<(), ErrorGuaranteed> {
754 self.emit_diagnostic_without_consuming(&mut diagnostic, None)
755 }
756
757 fn emit_diagnostic_without_consuming(
759 &mut self,
760 diagnostic: &mut Diag,
761 deferral: Option<Withholding<'_>>,
762 ) -> Result<(), ErrorGuaranteed> {
763 if self.is_allowed_diagnostic(diagnostic) {
764 return Ok(());
765 }
766
767 if diagnostic.level == Level::Warning && !self.flags.can_emit_warnings {
768 return Ok(());
769 }
770
771 if diagnostic.level == Level::Allow {
772 return Ok(());
773 }
774
775 if matches!(diagnostic.level, Level::Error | Level::Fatal) && self.treat_next_err_as_bug() {
776 diagnostic.level = Level::Bug;
777 }
778
779 match deferral {
780 Some((handle, batch)) if !matches!(diagnostic.level, Level::Bug | Level::Fatal) => {
781 let batch = self.withhold(handle, batch);
782 batch.diagnostics.lock().push(diagnostic.clone());
783 }
784 _ => {
785 if matches!(diagnostic.level, Level::Bug | Level::Fatal) {
788 self.flush_withheld();
789 }
790 self.deliver_diagnostic(diagnostic);
791 }
792 }
793
794 if diagnostic.is_error() {
795 self.bump_err_count();
796 Err(ErrorGuaranteed::new_unchecked())
797 } else {
798 if diagnostic.level == Level::Warning {
799 self.bump_warn_count();
800 } else if diagnostic.is_note() {
801 self.bump_note_count();
802 }
803 Ok(())
805 }
806 }
807
808 fn withhold<'a>(
810 &mut self,
811 handle: &Arc<Mutex<Self>>,
812 slot: &'a mut Option<Arc<Batch>>,
813 ) -> &'a Arc<Batch> {
814 slot.get_or_insert_with(|| {
815 let batch =
816 Arc::new(Batch { dcx: Arc::clone(handle), diagnostics: Mutex::new(Vec::new()) });
817 if self.withheld.len() >= self.prune_withheld_at {
818 self.withheld.retain(|batch| batch.strong_count() > 0);
819 self.prune_withheld_at = (2 * self.withheld.len()).max(64);
820 }
821 self.withheld.push(Arc::downgrade(&batch));
822 if !mem::replace(&mut self.registered, true) {
823 let mut contexts = WITHHOLDING.lock();
824 contexts.retain(|context| context.strong_count() > 0);
825 contexts.push(Arc::downgrade(handle));
826 }
827 batch
828 })
829 }
830
831 fn flush_withheld(&mut self) {
833 let batches = self.withheld.iter().filter_map(Weak::upgrade).collect::<Vec<_>>();
834 for batch in batches {
835 let diagnostics = mem::take(&mut *batch.diagnostics.lock());
836 for mut diagnostic in diagnostics {
837 self.deliver_diagnostic(&mut diagnostic);
838 }
839 }
840 }
841
842 fn deliver_diagnostic(&mut self, diagnostic: &mut Diag) {
844 let already_emitted = self.insert_diagnostic(diagnostic);
845 if self.flags.deduplicate_diagnostics && already_emitted {
846 return;
847 }
848
849 diagnostic.children.retain(|sub| {
851 if !matches!(sub.level, Level::OnceNote | Level::OnceHelp) {
852 return true;
853 }
854 let sub_already_emitted = self.insert_diagnostic(sub);
855 !sub_already_emitted
856 });
857
858 self.emitter.emit_diagnostic(diagnostic);
862 if diagnostic.is_error() {
863 self.deduplicated_err_count += 1;
864 } else if diagnostic.level == Level::Warning {
865 self.deduplicated_warn_count += 1;
866 } else if diagnostic.is_note() {
867 self.deduplicated_note_count += 1;
868 }
869 }
870
871 fn print_error_count(&mut self) -> Result {
872 if self.treat_err_as_bug() {
875 return Ok(());
876 }
877
878 let errors = match self.deduplicated_err_count {
879 0 => None,
880 1 => Some(Cow::from("aborting due to 1 previous error")),
881 count => Some(Cow::from(format!("aborting due to {count} previous errors"))),
882 };
883
884 let mut others = Vec::with_capacity(2);
885 match self.deduplicated_warn_count {
886 1 => others.push(Cow::from("1 warning emitted")),
887 count if count > 1 => others.push(Cow::from(format!("{count} warnings emitted"))),
888 _ => {}
889 }
890 match self.deduplicated_note_count {
891 1 => others.push(Cow::from("1 note emitted")),
892 count if count > 1 => others.push(Cow::from(format!("{count} notes emitted"))),
893 _ => {}
894 }
895
896 match (errors, others.is_empty()) {
897 (None, true) => Ok(()),
898 (None, false) => {
899 if self.flags.track_diagnostics {
901 let msg = others.join(", ");
902 self.emitter.emit_diagnostic(&mut Diag::new(Level::Warning, msg));
903 }
904 Ok(())
905 }
906 (Some(e), true) => self.emit_diagnostic(Diag::new(Level::Error, e)),
907 (Some(e), false) => self
908 .emit_diagnostic(Diag::new(Level::Error, format!("{}; {}", e, others.join(", ")))),
909 }
910 }
911
912 fn insert_diagnostic<H: std::hash::Hash>(&mut self, diag: &H) -> bool {
915 let hash = solar_data_structures::map::rustc_hash::FxBuildHasher.hash_one(diag);
916 !self.emitted_diagnostics.insert(hash)
917 }
918
919 fn treat_err_as_bug(&self) -> bool {
920 self.flags.treat_err_as_bug.is_some_and(|c| self.err_count >= c.get())
921 }
922
923 fn treat_next_err_as_bug(&self) -> bool {
925 self.flags.treat_err_as_bug.is_some_and(|c| self.err_count + 1 >= c.get())
926 }
927
928 fn is_allowed_diagnostic(&self, diagnostic: &Diag) -> bool {
929 diagnostic.level == Level::Warning
930 && diagnostic.id().is_some_and(|id| self.allowed_diagnostic_codes.contains(id))
931 }
932
933 fn bump_err_count(&mut self) {
934 self.err_count += 1;
935 self.panic_if_treat_err_as_bug();
936 }
937
938 fn bump_warn_count(&mut self) {
939 self.warn_count += 1;
940 }
941
942 fn bump_note_count(&mut self) {
943 self.note_count += 1;
944 }
945
946 fn has_errors(&self) -> bool {
947 self.err_count > 0
948 }
949
950 fn panic_if_treat_err_as_bug(&self) {
951 if self.treat_err_as_bug() {
952 match (self.err_count, self.flags.treat_err_as_bug.unwrap().get()) {
953 (1, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
954 (count, val) => {
955 panic!("aborting after {count} errors due to `-Z treat-err-as-bug={val}`")
956 }
957 }
958 }
959 }
960}