solar_interface/diagnostics/
context.rs

1use super::{
2    BugAbort, Diag, DiagBuilder, DiagMsg, DynEmitter, EmissionGuarantee, EmittedDiagnostics,
3    ErrorGuaranteed, FatalAbort, HumanBufferEmitter, Level, SilentEmitter, emitter::HumanEmitter,
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() { Err(ErrorGuaranteed::new_unchecked()) } else { Ok(()) }
188    }
189
190    /// Returns the emitted diagnostics. Can be empty.
191    ///
192    /// Returns `None` if the underlying emitter is not a human buffer emitter created with
193    /// [`with_buffer_emitter`](Self::with_buffer_emitter).
194    pub fn emitted_diagnostics(&self) -> Option<EmittedDiagnostics> {
195        let inner = self.inner.lock();
196        Some(EmittedDiagnostics(inner.emitter.local_buffer()?.to_string()))
197    }
198
199    /// Returns `Err` with the printed diagnostics if any errors have been emitted.
200    ///
201    /// Returns `None` if the underlying emitter is not a human buffer emitter created with
202    /// [`with_buffer_emitter`](Self::with_buffer_emitter).
203    pub fn emitted_errors(&self) -> Option<Result<(), EmittedDiagnostics>> {
204        let inner = self.inner.lock();
205        let buffer = inner.emitter.local_buffer()?;
206        Some(if inner.has_errors() { Err(EmittedDiagnostics(buffer.to_string())) } else { Ok(()) })
207    }
208
209    /// Emits a diagnostic if any warnings or errors have been emitted.
210    pub fn print_error_count(&self) -> Result {
211        self.inner.lock().print_error_count()
212    }
213}
214
215/// Diag constructors.
216///
217/// Note that methods returning a [`DiagBuilder`] must also marked with `#[track_caller]`.
218impl DiagCtxt {
219    /// Creates a builder at the given `level` with the given `msg`.
220    #[track_caller]
221    pub fn diag<G: EmissionGuarantee>(
222        &self,
223        level: Level,
224        msg: impl Into<DiagMsg>,
225    ) -> DiagBuilder<'_, G> {
226        DiagBuilder::new(self, level, msg)
227    }
228
229    /// Creates a builder at the `Bug` level with the given `msg`.
230    #[track_caller]
231    pub fn bug(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, BugAbort> {
232        self.diag(Level::Bug, msg)
233    }
234
235    /// Creates a builder at the `Fatal` level with the given `msg`.
236    #[track_caller]
237    pub fn fatal(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, FatalAbort> {
238        self.diag(Level::Fatal, msg)
239    }
240
241    /// Creates a builder at the `Error` level with the given `msg`.
242    #[track_caller]
243    pub fn err(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ErrorGuaranteed> {
244        self.diag(Level::Error, msg)
245    }
246
247    /// Creates a builder at the `Warning` level with the given `msg`.
248    ///
249    /// Attempting to `.emit()` the builder will only emit if `can_emit_warnings` is `true`.
250    #[track_caller]
251    pub fn warn(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ()> {
252        self.diag(Level::Warning, msg)
253    }
254
255    /// Creates a builder at the `Help` level with the given `msg`.
256    #[track_caller]
257    pub fn help(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ()> {
258        self.diag(Level::Help, msg)
259    }
260
261    /// Creates a builder at the `Note` level with the given `msg`.
262    #[track_caller]
263    pub fn note(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ()> {
264        self.diag(Level::Note, msg)
265    }
266}
267
268impl DiagCtxtInner {
269    fn emit_diagnostic(&mut self, mut diagnostic: Diag) -> Result<(), ErrorGuaranteed> {
270        self.emit_diagnostic_without_consuming(&mut diagnostic)
271    }
272
273    fn emit_diagnostic_without_consuming(
274        &mut self,
275        diagnostic: &mut Diag,
276    ) -> Result<(), ErrorGuaranteed> {
277        if diagnostic.level == Level::Warning && !self.flags.can_emit_warnings {
278            return Ok(());
279        }
280
281        if diagnostic.level == Level::Allow {
282            return Ok(());
283        }
284
285        if matches!(diagnostic.level, Level::Error | Level::Fatal) && self.treat_err_as_bug() {
286            diagnostic.level = Level::Bug;
287        }
288
289        let already_emitted = self.insert_diagnostic(diagnostic);
290        if !(self.flags.deduplicate_diagnostics && already_emitted) {
291            // Remove duplicate `Once*` subdiagnostics.
292            diagnostic.children.retain(|sub| {
293                if !matches!(sub.level, Level::OnceNote | Level::OnceHelp) {
294                    return true;
295                }
296                let sub_already_emitted = self.insert_diagnostic(sub);
297                !sub_already_emitted
298            });
299
300            // if already_emitted {
301            //     diagnostic.note(
302            //         "duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`",
303            //     );
304            // }
305
306            self.emitter.emit_diagnostic(diagnostic);
307            if diagnostic.is_error() {
308                self.deduplicated_err_count += 1;
309            } else if diagnostic.level == Level::Warning {
310                self.deduplicated_warn_count += 1;
311            }
312        }
313
314        if diagnostic.is_error() {
315            self.bump_err_count();
316            Err(ErrorGuaranteed::new_unchecked())
317        } else {
318            self.bump_warn_count();
319            Ok(())
320        }
321    }
322
323    fn print_error_count(&mut self) -> Result {
324        // self.emit_stashed_diagnostics();
325
326        if self.treat_err_as_bug() {
327            return Ok(());
328        }
329
330        let warnings = |count| match count {
331            0 => unreachable!(),
332            1 => Cow::from("1 warning emitted"),
333            count => Cow::from(format!("{count} warnings emitted")),
334        };
335        let errors = |count| match count {
336            0 => unreachable!(),
337            1 => Cow::from("aborting due to 1 previous error"),
338            count => Cow::from(format!("aborting due to {count} previous errors")),
339        };
340
341        match (self.deduplicated_err_count, self.deduplicated_warn_count) {
342            (0, 0) => Ok(()),
343            (0, w) => {
344                // TODO: Don't emit in tests since it's not handled by `ui_test`.
345                if self.flags.track_diagnostics {
346                    self.emitter.emit_diagnostic(&Diag::new(Level::Warning, warnings(w)));
347                }
348                Ok(())
349            }
350            (e, 0) => self.emit_diagnostic(Diag::new(Level::Error, errors(e))),
351            (e, w) => self.emit_diagnostic(Diag::new(
352                Level::Error,
353                format!("{}; {}", errors(e), warnings(w)),
354            )),
355        }
356    }
357
358    /// Inserts the given diagnostic into the set of emitted diagnostics.
359    /// Returns `true` if the diagnostic was already emitted.
360    fn insert_diagnostic<H: std::hash::Hash>(&mut self, diag: &H) -> bool {
361        let hash = solar_data_structures::map::rustc_hash::FxBuildHasher.hash_one(diag);
362        !self.emitted_diagnostics.insert(hash)
363    }
364
365    fn treat_err_as_bug(&self) -> bool {
366        self.flags.treat_err_as_bug.is_some_and(|c| self.err_count >= c.get())
367    }
368
369    fn bump_err_count(&mut self) {
370        self.err_count += 1;
371        self.panic_if_treat_err_as_bug();
372    }
373
374    fn bump_warn_count(&mut self) {
375        self.warn_count += 1;
376    }
377
378    fn has_errors(&self) -> bool {
379        self.err_count > 0
380    }
381
382    fn panic_if_treat_err_as_bug(&self) {
383        if self.treat_err_as_bug() {
384            match (self.err_count, self.flags.treat_err_as_bug.unwrap().get()) {
385                (1, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
386                (count, val) => {
387                    panic!("aborting after {count} errors due to `-Z treat-err-as-bug={val}`")
388                }
389            }
390        }
391    }
392}