solar_interface/diagnostics/
context.rs1use 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#[derive(Clone, Copy)]
12pub struct DiagCtxtFlags {
13 pub can_emit_warnings: bool,
15 pub treat_err_as_bug: Option<NonZeroUsize>,
17 pub deduplicate_diagnostics: bool,
19 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
35pub struct DiagCtxt {
39 inner: Lock<DiagCtxtInner>,
40}
41
42struct DiagCtxtInner {
43 emitter: Box<DynEmitter>,
44
45 flags: DiagCtxtFlags,
46
47 err_count: usize,
52 deduplicated_err_count: usize,
53 warn_count: usize,
54 deduplicated_warn_count: usize,
56
57 emitted_diagnostics: FxHashSet<u64>,
60}
61
62impl DiagCtxt {
63 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 pub fn new_early() -> Self {
81 Self::with_stderr_emitter(None).set_flags(|flags| flags.track_diagnostics = false)
82 }
83
84 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 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 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 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 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 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 pub fn source_map(&self) -> Option<Arc<SourceMap>> {
139 self.inner.lock().emitter.source_map().cloned()
140 }
141
142 pub fn source_map_mut(&mut self) -> Option<&Arc<SourceMap>> {
144 self.inner.get_mut().emitter.source_map()
145 }
146
147 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 pub fn disable_warnings(self) -> Self {
155 self.set_flags(|f| f.can_emit_warnings = false)
156 }
157
158 pub fn track_diagnostics(&self) -> bool {
160 self.inner.lock().flags.track_diagnostics
161 }
162
163 #[inline]
165 pub fn emit_diagnostic(&self, mut diagnostic: Diag) -> Result<(), ErrorGuaranteed> {
166 self.emit_diagnostic_without_consuming(&mut diagnostic)
167 }
168
169 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 pub fn err_count(&self) -> usize {
182 self.inner.lock().err_count
183 }
184
185 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 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 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 pub fn print_error_count(&self) -> Result {
215 self.inner.lock().print_error_count()
216 }
217}
218
219impl DiagCtxt {
223 #[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 #[track_caller]
235 pub fn bug(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, BugAbort> {
236 self.diag(Level::Bug, msg)
237 }
238
239 #[track_caller]
241 pub fn fatal(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, FatalAbort> {
242 self.diag(Level::Fatal, msg)
243 }
244
245 #[track_caller]
247 pub fn err(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ErrorGuaranteed> {
248 self.diag(Level::Error, msg)
249 }
250
251 #[track_caller]
255 pub fn warn(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ()> {
256 self.diag(Level::Warning, msg)
257 }
258
259 #[track_caller]
261 pub fn help(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ()> {
262 self.diag(Level::Help, msg)
263 }
264
265 #[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 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 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 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 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 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}