Skip to main content

solar_interface/diagnostics/
context.rs

1//! Diagnostic collection, deduplication, counting, and emission.
2//!
3//! Modified from rustc's [`DiagCtxt`](https://github.com/rust-lang/rust/blob/3b58636b30eb364ac72aeaf03d46347084ed87d1/compiler/rustc_errors/src/lib.rs).
4
5use 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    /// The deferral of the innermost [`DiagCtxt::defer`] running on this thread.
30    ///
31    /// Emission takes it out while the emitter runs, so an emitter can use another context.
32    static DEFERRED: RefCell<Option<Deferral>> = const { RefCell::new(None) };
33}
34
35#[cfg(debug_assertions)]
36thread_local! {
37    /// The contexts that have a [`DiagCtxt::defer`] running on this thread, innermost last.
38    static DEFERRING: RefCell<Vec<*const DiagCtxt>> = const { RefCell::new(Vec::new()) };
39}
40
41/// Contexts that have withheld diagnostics, for [`flush_withheld`].
42static WITHHOLDING: Mutex<Vec<Weak<Mutex<DiagCtxtInner>>>> = Mutex::new(Vec::new());
43
44struct Deferral {
45    dcx: *const DiagCtxt,
46    /// Created by the first diagnostic.
47    batch: Option<Arc<Batch>>,
48}
49
50/// The context that withholds diagnostics, and the batch of the deferral that creates it.
51type Withholding<'a> = (&'a Arc<Mutex<DiagCtxtInner>>, &'a mut Option<Arc<Batch>>);
52
53/// The diagnostics that one [`DiagCtxt::defer`] withheld.
54///
55/// The context also tracks it, so that [`flush_withheld`] can emit it wherever it sits. If it is
56/// dropped with diagnostics left, for example by a panic that unwinds, they are emitted then.
57struct 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/// Diagnostics withheld by [`DiagCtxt::defer`], to be emitted with [`DiagCtxt::emit_deferred`].
75#[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    /// Moves the diagnostics of `other` after these.
87    pub fn append(&mut self, mut other: Self) {
88        self.0.append(&mut other.0);
89    }
90
91    /// Returns whether there are no diagnostics.
92    pub fn is_empty(&self) -> bool {
93        self.0.iter().all(|batch| batch.diagnostics.lock().is_empty())
94    }
95
96    /// Stably sorts the diagnostics by the key `f` computes for each.
97    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
121/// Emits every diagnostic that a [`DiagCtxt::defer`] on any thread still withholds, in the order
122/// that they first withheld one. This is best effort, for a panic that is about to end the
123/// program, where the work that holds them cannot finish: a thread that holds a context's lock
124/// for longer than a moment is skipped.
125pub 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/// Flags that control the behaviour of a [`DiagCtxt`].
135#[derive(Clone, Copy, Debug)]
136pub struct DiagCtxtFlags {
137    /// If false, warning-level lints are suppressed.
138    pub can_emit_warnings: bool,
139    /// If Some, the Nth error-level diagnostic is upgraded to bug-level.
140    pub treat_err_as_bug: Option<NonZeroUsize>,
141    /// If true, identical diagnostics are reported only once.
142    pub deduplicate_diagnostics: bool,
143    /// Track where errors are created. Enabled with `-Ztrack-diagnostics`, and by default in debug
144    /// builds.
145    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    /// Updates the flags from the given options.
161    ///
162    /// Looks at the following options:
163    /// - `unstable.ui_testing`
164    /// - `unstable.track_diagnostics`
165    /// - `no_warnings`
166    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
174/// A handler that deals with errors and other compiler output.
175///
176/// Certain errors (fatal, bug) may cause immediate exit, others log errors for later reporting.
177pub struct DiagCtxt {
178    inner: Arc<Mutex<DiagCtxtInner>>,
179    /// The [`DiagCtxt::defer`] calls in progress.
180    #[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    /// The number of errors that have been emitted, including duplicates.
206    ///
207    /// This is not necessarily the count that's reported to the user once
208    /// compilation ends.
209    err_count: usize,
210    deduplicated_err_count: usize,
211    /// The warning count, used for a recap upon finishing
212    warn_count: usize,
213    deduplicated_warn_count: usize,
214    /// The note count, used for a recap upon finishing
215    note_count: usize,
216    deduplicated_note_count: usize,
217
218    /// This set contains a hash of every diagnostic that has been emitted by this `DiagCtxt`.
219    /// These hashes are used to avoid emitting the same error twice.
220    emitted_diagnostics: FxHashSet<u64>,
221
222    /// The batches of withheld diagnostics, in the order that they first got one.
223    withheld: Vec<Weak<Batch>>,
224    prune_withheld_at: usize,
225    /// Whether the context is in `WITHHOLDING`.
226    registered: bool,
227}
228
229impl DiagCtxt {
230    /// Creates a new `DiagCtxt` with the given diagnostics emitter.
231    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    /// Creates a new `DiagCtxt` with a stderr emitter for emitting one-off/early fatal errors that
254    /// contain no source information.
255    pub fn new_early() -> Self {
256        Self::with_stderr_emitter(None).with_flags(|flags| flags.track_diagnostics = false)
257    }
258
259    /// Creates a new `DiagCtxt` with a test emitter.
260    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    /// Creates a new `DiagCtxt` with a stderr emitter.
265    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    /// Creates a new `DiagCtxt` with a stderr emitter and a color choice.
270    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    /// Creates a new `DiagCtxt` with a silent emitter.
278    ///
279    /// Fatal diagnostics will still be emitted, optionally with the given note.
280    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    /// Creates a new `DiagCtxt` with a human emitter that emits diagnostics to a local buffer.
287    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    /// Creates a new `DiagCtxt` from the given options.
295    ///
296    /// This is the default `DiagCtxt` used by the `Session` if one is not provided manually.
297    /// It looks at the following options:
298    /// - `error_format`
299    /// - `color`
300    /// - `unstable.ui_testing`
301    /// - `unstable.track_diagnostics`
302    /// - `no_warnings`
303    /// - `error_format_human`
304    /// - `diagnostic_width`
305    ///
306    /// The default is human emitter to stderr.
307    ///
308    /// See also [`DiagCtxtFlags::update_from_opts`].
309    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                // `io::Stderr` is not buffered.
323                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    /// Adds diagnostic codes that should be allowed.
340    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    /// Sets the emitter to [`SilentEmitter`].
349    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    /// Sets the inner emitter. Returns the previous emitter.
356    pub fn set_emitter(&self, emitter: Box<DynEmitter>) -> Box<DynEmitter> {
357        std::mem::replace(&mut self.inner.lock().emitter, emitter)
358    }
359
360    /// Wraps the current emitter with the given closure.
361    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    /// Gets the source map associated with this context.
373    pub fn source_map(&self) -> Option<Arc<SourceMap>> {
374        self.inner.lock().emitter.source_map().cloned()
375    }
376
377    /// Sets flags.
378    pub fn with_flags(mut self, f: impl FnOnce(&mut DiagCtxtFlags)) -> Self {
379        self.set_flags_mut(f);
380        self
381    }
382
383    /// Sets flags.
384    pub fn set_flags(&self, f: impl FnOnce(&mut DiagCtxtFlags)) {
385        f(&mut self.inner.lock().flags);
386    }
387
388    /// Sets flags.
389    pub fn set_flags_mut(&mut self, f: impl FnOnce(&mut DiagCtxtFlags)) {
390        f(&mut self.inner.lock().flags);
391    }
392
393    /// Adds diagnostic codes that should be allowed.
394    pub fn set_allowed_diagnostic_codes(&self, codes: impl IntoIterator<Item = String>) {
395        self.inner.lock().allowed_diagnostic_codes.extend(codes);
396    }
397
398    /// Adds diagnostic codes that should be allowed.
399    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    /// Disables emitting warnings.
404    pub fn disable_warnings(self) -> Self {
405        self.with_flags(|f| f.can_emit_warnings = false)
406    }
407
408    /// Returns whether warning diagnostics can be emitted.
409    pub fn can_emit_warnings(&self) -> bool {
410        self.inner.lock().flags.can_emit_warnings
411    }
412
413    /// Resets diagnostic counts and the deduplication cache.
414    ///
415    /// This is intended for tools that reuse a diagnostic context for multiple independent runs.
416    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    /// Returns `true` if diagnostics are being tracked.
428    pub fn track_diagnostics(&self) -> bool {
429        self.inner.lock().flags.track_diagnostics
430    }
431
432    /// Emits the given diagnostic with this context.
433    #[inline]
434    pub fn emit_diagnostic(&self, mut diagnostic: Diag) -> Result<(), ErrorGuaranteed> {
435        self.emit_diagnostic_without_consuming(&mut diagnostic)
436    }
437
438    /// Emits the given diagnostic with this context, without consuming the diagnostic.
439    ///
440    /// **Note:** This function is intended to be used only internally in `DiagBuilder`.
441    /// Use [`emit_diagnostic`](Self::emit_diagnostic) instead.
442    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    /// Takes the deferral of this thread out, if it is this context's.
466    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    /// Runs `f`, withholding the diagnostics that it emits on this thread.
479    ///
480    /// The withheld diagnostics count towards [`err_count`](Self::err_count) and the other counts
481    /// at once, but reach the emitter only through [`emit_deferred`](Self::emit_deferred), which
482    /// also deduplicates them. A bug or a fatal error first emits all that are withheld, and so
483    /// does [`flush_withheld`], which the panic hook calls. Calls nest. Diagnostics emitted by work
484    /// that `f` hands to other threads are not withheld, and a debug build asserts that there are
485    /// none; such work must use [`par_defer`](Self::par_defer) or [`defer`](Self::defer) itself.
486    pub fn defer<R>(&self, f: impl FnOnce() -> R) -> (R, DeferredDiagnostics) {
487        /// Restores the enclosing deferral, also when `f` unwinds. The diagnostics that `f`
488        /// withheld are emitted as the batch drops.
489        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    /// Emits the diagnostics withheld by [`defer`](Self::defer), in the order they were emitted.
522    ///
523    /// Within another [`defer`](Self::defer), they join its diagnostics instead.
524    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    /// Emits the diagnostics that a [`defer`](Self::defer) on any thread still withholds, in the
548    /// order that they first withheld one. See [`flush_withheld`].
549    pub fn flush_withheld(&self) {
550        flush_inner(&self.inner);
551    }
552
553    /// Runs `f` for every item of `iter` in parallel, and returns its results and the diagnostics
554    /// of each call in the order of the items, as a sequential loop would emit them.
555    ///
556    /// `iter` must keep the order of its items when collected, as every Rayon iterator does.
557    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    /// Runs `f` for every item of `iter` in parallel, and emits the diagnostics of each call in the
577    /// order of the items. See [`par_defer`](Self::par_defer).
578    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    /// Returns the number of errors that have been emitted, including duplicates.
586    pub fn err_count(&self) -> usize {
587        self.inner.lock().err_count
588    }
589
590    /// Returns `Err` if any errors have been emitted.
591    pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
592        if self.inner.lock().has_errors() { Err(ErrorGuaranteed::new_unchecked()) } else { Ok(()) }
593    }
594
595    /// Returns the number of warnings that have been emitted, including duplicates.
596    pub fn warn_count(&self) -> usize {
597        self.inner.lock().warn_count
598    }
599
600    /// Returns the number of notes that have been emitted, including duplicates.
601    pub fn note_count(&self) -> usize {
602        self.inner.lock().note_count
603    }
604
605    /// Returns the emitted diagnostics as a result. Can be empty.
606    ///
607    /// Returns `None` if the underlying emitter is not a human buffer emitter created with
608    /// [`with_buffer_emitter`](Self::with_buffer_emitter).
609    ///
610    /// Results `Ok` if there are no errors, `Err` otherwise.
611    ///
612    /// # Examples
613    ///
614    /// Print diagnostics to `stdout` if there are no errors, otherwise propagate with `?`:
615    ///
616    /// ```no_run
617    /// # fn f(dcx: solar_interface::diagnostics::DiagCtxt) -> Result<(), Box<dyn std::error::Error>> {
618    /// println!("{}", dcx.emitted_diagnostics_result().unwrap()?);
619    /// # Ok(())
620    /// # }
621    /// ```
622    #[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    /// Returns the emitted diagnostics. Can be empty.
632    ///
633    /// Returns `None` if the underlying emitter is not a human buffer emitter created with
634    /// [`with_buffer_emitter`](Self::with_buffer_emitter).
635    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    /// Returns `Err` with the printed diagnostics if any errors have been emitted.
641    ///
642    /// Returns `None` if the underlying emitter is not a human buffer emitter created with
643    /// [`with_buffer_emitter`](Self::with_buffer_emitter).
644    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    /// Emits a diagnostic if any warnings or errors have been emitted.
651    pub fn print_error_count(&self) -> Result {
652        self.inner.lock().print_error_count()
653    }
654}
655
656/// Diag constructors.
657///
658/// Note that methods returning a [`DiagBuilder`] must also marked with `#[track_caller]`.
659impl DiagCtxt {
660    /// Creates a builder at the given `level` with the given `msg`.
661    #[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    /// Creates a builder at the `Bug` level with the given `msg`.
671    #[track_caller]
672    #[cold]
673    pub fn bug(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, BugAbort> {
674        self.diag(Level::Bug, msg)
675    }
676
677    /// Creates a builder at the `Fatal` level with the given `msg`.
678    #[track_caller]
679    #[cold]
680    pub fn fatal(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, FatalAbort> {
681        self.diag(Level::Fatal, msg)
682    }
683
684    /// Creates a builder at the `Error` level with the given `msg`.
685    #[track_caller]
686    pub fn err(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ErrorGuaranteed> {
687        self.diag(Level::Error, msg)
688    }
689
690    /// Emits an error at `span` with the given `msg`.
691    #[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    /// Emits an error at `span` with an attached note.
697    #[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    /// Emits an error at `span` with an attached span note.
708    #[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    /// Emits an error at `span` with an attached span label.
720    #[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    /// Creates a builder at the `Warning` level with the given `msg`.
732    ///
733    /// Attempting to `.emit()` the builder will only emit if `can_emit_warnings` is `true`.
734    #[track_caller]
735    pub fn warn(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ()> {
736        self.diag(Level::Warning, msg)
737    }
738
739    /// Creates a builder at the `Help` level with the given `msg`.
740    #[track_caller]
741    pub fn help(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ()> {
742        self.diag(Level::Help, msg)
743    }
744
745    /// Creates a builder at the `Note` level with the given `msg`.
746    #[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    /// Counts the diagnostic, and emits it, or withholds it in the batch of `deferral` if given.
758    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                // A bug panics when counted and a fatal error ends the program, so what is
786                // withheld comes out first.
787                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            // Don't bump any counters for `Help`, `OnceHelp`, or `Allow`
804            Ok(())
805        }
806    }
807
808    /// Returns the batch in `slot`, creating and tracking it first if there is none.
809    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    /// Emits the diagnostics that batches withhold, in the order that the batches got their first.
832    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    /// Emits the diagnostic unless it duplicates one that was emitted.
843    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        // Remove duplicate `Once*` subdiagnostics.
850        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        // Unlike rustc, deduplication is only disabled internally for UI testing, so do not
859        // attach rustc's `-Z deduplicate-diagnostics=no` note.
860
861        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        // self.emit_stashed_diagnostics();
873
874        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                // TODO: Don't emit in tests since it's not handled by `ui_test`: https://github.com/oli-obk/ui_test/issues/324
900                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    /// Inserts the given diagnostic into the set of emitted diagnostics.
913    /// Returns `true` if the diagnostic was already emitted.
914    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    /// Use before incrementing `err_count`.
924    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}