solar_interface/diagnostics/
context.rs

1use super::{
2    emitter::HumanEmitter, BugAbort, Diag, DiagBuilder, DiagMsg, DynEmitter, EmissionGuarantee,
3    EmittedDiagnostics, ErrorGuaranteed, FatalAbort, HumanBufferEmitter, Level, SilentEmitter,
4};
5use crate::{Result, SourceMap};
6use anstream::ColorChoice;
7use solar_data_structures::{map::FxHashSet, sync::Lock};
8use std::{borrow::Cow, hash::BuildHasher, num::NonZeroUsize, sync::Arc};
9
10/// Flags that control the behaviour of a [`DiagCtxt`].
11#[derive(Clone, Copy)]
12pub struct DiagCtxtFlags {
13    /// If false, warning-level lints are suppressed.
14    pub can_emit_warnings: bool,
15    /// If Some, the Nth error-level diagnostic is upgraded to bug-level.
16    pub treat_err_as_bug: Option<NonZeroUsize>,
17    /// If true, identical diagnostics are reported only once.
18    pub deduplicate_diagnostics: bool,
19    /// Track where errors are created. Enabled with `-Ztrack-diagnostics`, and by default in debug
20    /// builds.
21    pub track_diagnostics: bool,
22}
23
24impl Default for DiagCtxtFlags {
25    fn default() -> Self {
26        Self {
27            can_emit_warnings: true,
28            treat_err_as_bug: None,
29            deduplicate_diagnostics: true,
30            track_diagnostics: cfg!(debug_assertions),
31        }
32    }
33}
34
35/// A handler deals with errors and other compiler output.
36/// Certain errors (fatal, bug, unimpl) may cause immediate exit,
37/// others log errors for later reporting.
38pub struct DiagCtxt {
39    inner: Lock<DiagCtxtInner>,
40}
41
42struct DiagCtxtInner {
43    emitter: Box<DynEmitter>,
44
45    flags: DiagCtxtFlags,
46
47    /// The number of errors that have been emitted, including duplicates.
48    ///
49    /// This is not necessarily the count that's reported to the user once
50    /// compilation ends.
51    err_count: usize,
52    deduplicated_err_count: usize,
53    warn_count: usize,
54    /// The warning count, used for a recap upon finishing
55    deduplicated_warn_count: usize,
56
57    /// This set contains a hash of every diagnostic that has been emitted by this `DiagCtxt`.
58    /// These hashes are used to avoid emitting the same error twice.
59    emitted_diagnostics: FxHashSet<u64>,
60}
61
62impl DiagCtxt {
63    /// Creates a new `DiagCtxt` with the given diagnostics emitter.
64    pub fn new(emitter: Box<DynEmitter>) -> Self {
65        Self {
66            inner: Lock::new(DiagCtxtInner {
67                emitter,
68                flags: DiagCtxtFlags::default(),
69                err_count: 0,
70                deduplicated_err_count: 0,
71                warn_count: 0,
72                deduplicated_warn_count: 0,
73                emitted_diagnostics: FxHashSet::default(),
74            }),
75        }
76    }
77
78    /// Creates a new `DiagCtxt` with a stderr emitter for emitting one-off/early fatal errors that
79    /// contain no source information.
80    pub fn new_early() -> Self {
81        Self::with_stderr_emitter(None).set_flags(|flags| flags.track_diagnostics = false)
82    }
83
84    /// Creates a new `DiagCtxt` with a test emitter.
85    pub fn with_test_emitter(source_map: Option<Arc<SourceMap>>) -> Self {
86        Self::new(Box::new(HumanEmitter::test().source_map(source_map)))
87    }
88
89    /// Creates a new `DiagCtxt` with a stderr emitter.
90    pub fn with_stderr_emitter(source_map: Option<Arc<SourceMap>>) -> Self {
91        Self::with_stderr_emitter_and_color(source_map, ColorChoice::Auto)
92    }
93
94    /// Creates a new `DiagCtxt` with a stderr emitter and a color choice.
95    pub fn with_stderr_emitter_and_color(
96        source_map: Option<Arc<SourceMap>>,
97        color_choice: ColorChoice,
98    ) -> Self {
99        Self::new(Box::new(HumanEmitter::stderr(color_choice).source_map(source_map)))
100    }
101
102    /// Creates a new `DiagCtxt` with a silent emitter.
103    ///
104    /// Fatal diagnostics will still be emitted, optionally with the given note.
105    pub fn with_silent_emitter(fatal_note: Option<String>) -> Self {
106        let fatal_emitter = HumanEmitter::stderr(Default::default());
107        Self::new(Box::new(SilentEmitter::new(fatal_emitter).with_note(fatal_note)))
108            .disable_warnings()
109    }
110
111    /// Creates a new `DiagCtxt` with a human emitter that emits diagnostics to a local buffer.
112    pub fn with_buffer_emitter(
113        source_map: Option<Arc<SourceMap>>,
114        color_choice: ColorChoice,
115    ) -> Self {
116        Self::new(Box::new(HumanBufferEmitter::new(color_choice).source_map(source_map)))
117    }
118
119    /// Sets the emitter to [`SilentEmitter`].
120    pub fn make_silent(&self, fatal_note: Option<String>, emit_fatal: bool) {
121        self.wrap_emitter(|prev| {
122            Box::new(SilentEmitter::new_boxed(emit_fatal.then_some(prev)).with_note(fatal_note))
123        });
124    }
125
126    fn wrap_emitter(&self, f: impl FnOnce(Box<DynEmitter>) -> Box<DynEmitter>) {
127        struct FakeEmitter;
128        impl crate::diagnostics::Emitter for FakeEmitter {
129            fn emit_diagnostic(&mut self, _diagnostic: &Diag) {}
130        }
131
132        let mut inner = self.inner.lock();
133        let prev = std::mem::replace(&mut inner.emitter, Box::new(FakeEmitter));
134        inner.emitter = f(prev);
135    }
136
137    /// Gets the source map associated with this context.
138    pub fn source_map(&self) -> Option<Arc<SourceMap>> {
139        self.inner.lock().emitter.source_map().cloned()
140    }
141
142    /// Gets the source map associated with this context.
143    pub fn source_map_mut(&mut self) -> Option<&Arc<SourceMap>> {
144        self.inner.get_mut().emitter.source_map()
145    }
146
147    /// Sets whether to include created and emitted locations in diagnostics.
148    pub fn set_flags(mut self, f: impl FnOnce(&mut DiagCtxtFlags)) -> Self {
149        f(&mut self.inner.get_mut().flags);
150        self
151    }
152
153    /// Disables emitting warnings.
154    pub fn disable_warnings(self) -> Self {
155        self.set_flags(|f| f.can_emit_warnings = false)
156    }
157
158    /// Returns `true` if diagnostics are being tracked.
159    pub fn track_diagnostics(&self) -> bool {
160        self.inner.lock().flags.track_diagnostics
161    }
162
163    /// Emits the given diagnostic with this context.
164    #[inline]
165    pub fn emit_diagnostic(&self, mut diagnostic: Diag) -> Result<(), ErrorGuaranteed> {
166        self.emit_diagnostic_without_consuming(&mut diagnostic)
167    }
168
169    /// Emits the given diagnostic with this context, without consuming the diagnostic.
170    ///
171    /// **Note:** This function is intended to be used only internally in `DiagBuilder`.
172    /// Use [`emit_diagnostic`](Self::emit_diagnostic) instead.
173    pub(super) fn emit_diagnostic_without_consuming(
174        &self,
175        diagnostic: &mut Diag,
176    ) -> Result<(), ErrorGuaranteed> {
177        self.inner.lock().emit_diagnostic_without_consuming(diagnostic)
178    }
179
180    /// Returns the number of errors that have been emitted, including duplicates.
181    pub fn err_count(&self) -> usize {
182        self.inner.lock().err_count
183    }
184
185    /// Returns `Err` if any errors have been emitted.
186    pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
187        if self.inner.lock().has_errors() {
188            Err(ErrorGuaranteed::new_unchecked())
189        } else {
190            Ok(())
191        }
192    }
193
194    /// Returns the emitted diagnostics. Can be empty.
195    ///
196    /// Returns `None` if the underlying emitter is not a human buffer emitter created with
197    /// [`with_buffer_emitter`](Self::with_buffer_emitter).
198    pub fn emitted_diagnostics(&self) -> Option<EmittedDiagnostics> {
199        let inner = self.inner.lock();
200        Some(EmittedDiagnostics(inner.emitter.local_buffer()?.to_string()))
201    }
202
203    /// Returns `Err` with the printed diagnostics if any errors have been emitted.
204    ///
205    /// Returns `None` if the underlying emitter is not a human buffer emitter created with
206    /// [`with_buffer_emitter`](Self::with_buffer_emitter).
207    pub fn emitted_errors(&self) -> Option<Result<(), EmittedDiagnostics>> {
208        let inner = self.inner.lock();
209        let buffer = inner.emitter.local_buffer()?;
210        Some(if inner.has_errors() { Err(EmittedDiagnostics(buffer.to_string())) } else { Ok(()) })
211    }
212
213    /// Emits a diagnostic if any warnings or errors have been emitted.
214    pub fn print_error_count(&self) -> Result {
215        self.inner.lock().print_error_count()
216    }
217}
218
219/// Diag constructors.
220///
221/// Note that methods returning a [`DiagBuilder`] must also marked with `#[track_caller]`.
222impl DiagCtxt {
223    /// Creates a builder at the given `level` with the given `msg`.
224    #[track_caller]
225    pub fn diag<G: EmissionGuarantee>(
226        &self,
227        level: Level,
228        msg: impl Into<DiagMsg>,
229    ) -> DiagBuilder<'_, G> {
230        DiagBuilder::new(self, level, msg)
231    }
232
233    /// Creates a builder at the `Bug` level with the given `msg`.
234    #[track_caller]
235    pub fn bug(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, BugAbort> {
236        self.diag(Level::Bug, msg)
237    }
238
239    /// Creates a builder at the `Fatal` level with the given `msg`.
240    #[track_caller]
241    pub fn fatal(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, FatalAbort> {
242        self.diag(Level::Fatal, msg)
243    }
244
245    /// Creates a builder at the `Error` level with the given `msg`.
246    #[track_caller]
247    pub fn err(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ErrorGuaranteed> {
248        self.diag(Level::Error, msg)
249    }
250
251    /// Creates a builder at the `Warning` level with the given `msg`.
252    ///
253    /// Attempting to `.emit()` the builder will only emit if `can_emit_warnings` is `true`.
254    #[track_caller]
255    pub fn warn(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ()> {
256        self.diag(Level::Warning, msg)
257    }
258
259    /// Creates a builder at the `Help` level with the given `msg`.
260    #[track_caller]
261    pub fn help(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ()> {
262        self.diag(Level::Help, msg)
263    }
264
265    /// Creates a builder at the `Note` level with the given `msg`.
266    #[track_caller]
267    pub fn note(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ()> {
268        self.diag(Level::Note, msg)
269    }
270}
271
272impl DiagCtxtInner {
273    fn emit_diagnostic(&mut self, mut diagnostic: Diag) -> Result<(), ErrorGuaranteed> {
274        self.emit_diagnostic_without_consuming(&mut diagnostic)
275    }
276
277    fn emit_diagnostic_without_consuming(
278        &mut self,
279        diagnostic: &mut Diag,
280    ) -> Result<(), ErrorGuaranteed> {
281        if diagnostic.level == Level::Warning && !self.flags.can_emit_warnings {
282            return Ok(());
283        }
284
285        if diagnostic.level == Level::Allow {
286            return Ok(());
287        }
288
289        if matches!(diagnostic.level, Level::Error | Level::Fatal) && self.treat_err_as_bug() {
290            diagnostic.level = Level::Bug;
291        }
292
293        let already_emitted = self.insert_diagnostic(diagnostic);
294        if !(self.flags.deduplicate_diagnostics && already_emitted) {
295            // Remove duplicate `Once*` subdiagnostics.
296            diagnostic.children.retain(|sub| {
297                if !matches!(sub.level, Level::OnceNote | Level::OnceHelp) {
298                    return true;
299                }
300                let sub_already_emitted = self.insert_diagnostic(sub);
301                !sub_already_emitted
302            });
303
304            // if already_emitted {
305            //     diagnostic.note(
306            //         "duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`",
307            //     );
308            // }
309
310            self.emitter.emit_diagnostic(diagnostic);
311            if diagnostic.is_error() {
312                self.deduplicated_err_count += 1;
313            } else if diagnostic.level == Level::Warning {
314                self.deduplicated_warn_count += 1;
315            }
316        }
317
318        if diagnostic.is_error() {
319            self.bump_err_count();
320            Err(ErrorGuaranteed::new_unchecked())
321        } else {
322            self.bump_warn_count();
323            Ok(())
324        }
325    }
326
327    fn print_error_count(&mut self) -> Result {
328        // self.emit_stashed_diagnostics();
329
330        if self.treat_err_as_bug() {
331            return Ok(());
332        }
333
334        let warnings = |count| match count {
335            0 => unreachable!(),
336            1 => Cow::from("1 warning emitted"),
337            count => Cow::from(format!("{count} warnings emitted")),
338        };
339        let errors = |count| match count {
340            0 => unreachable!(),
341            1 => Cow::from("aborting due to 1 previous error"),
342            count => Cow::from(format!("aborting due to {count} previous errors")),
343        };
344
345        match (self.deduplicated_err_count, self.deduplicated_warn_count) {
346            (0, 0) => Ok(()),
347            (0, w) => {
348                // TODO: Don't emit in tests since it's not handled by `ui_test`.
349                if self.flags.track_diagnostics {
350                    self.emitter.emit_diagnostic(&Diag::new(Level::Warning, warnings(w)));
351                }
352                Ok(())
353            }
354            (e, 0) => self.emit_diagnostic(Diag::new(Level::Error, errors(e))),
355            (e, w) => self.emit_diagnostic(Diag::new(
356                Level::Error,
357                format!("{}; {}", errors(e), warnings(w)),
358            )),
359        }
360    }
361
362    /// Inserts the given diagnostic into the set of emitted diagnostics.
363    /// Returns `true` if the diagnostic was already emitted.
364    fn insert_diagnostic<H: std::hash::Hash>(&mut self, diag: &H) -> bool {
365        let hash = solar_data_structures::map::rustc_hash::FxBuildHasher.hash_one(diag);
366        !self.emitted_diagnostics.insert(hash)
367    }
368
369    fn treat_err_as_bug(&self) -> bool {
370        self.flags.treat_err_as_bug.is_some_and(|c| self.err_count >= c.get())
371    }
372
373    fn bump_err_count(&mut self) {
374        self.err_count += 1;
375        self.panic_if_treat_err_as_bug();
376    }
377
378    fn bump_warn_count(&mut self) {
379        self.warn_count += 1;
380    }
381
382    fn has_errors(&self) -> bool {
383        self.err_count > 0
384    }
385
386    fn panic_if_treat_err_as_bug(&self) {
387        if self.treat_err_as_bug() {
388            match (self.err_count, self.flags.treat_err_as_bug.unwrap().get()) {
389                (1, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
390                (count, val) => {
391                    panic!("aborting after {count} errors due to `-Z treat-err-as-bug={val}`")
392                }
393            }
394        }
395    }
396}