solar_interface/diagnostics/
context.rs1use 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#[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() { Err(ErrorGuaranteed::new_unchecked()) } else { Ok(()) }
188 }
189
190 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 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 pub fn print_error_count(&self) -> Result {
211 self.inner.lock().print_error_count()
212 }
213}
214
215impl DiagCtxt {
219 #[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 #[track_caller]
231 pub fn bug(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, BugAbort> {
232 self.diag(Level::Bug, msg)
233 }
234
235 #[track_caller]
237 pub fn fatal(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, FatalAbort> {
238 self.diag(Level::Fatal, msg)
239 }
240
241 #[track_caller]
243 pub fn err(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ErrorGuaranteed> {
244 self.diag(Level::Error, msg)
245 }
246
247 #[track_caller]
251 pub fn warn(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ()> {
252 self.diag(Level::Warning, msg)
253 }
254
255 #[track_caller]
257 pub fn help(&self, msg: impl Into<DiagMsg>) -> DiagBuilder<'_, ()> {
258 self.diag(Level::Help, msg)
259 }
260
261 #[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 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 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 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 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 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}