1 use crate::{Diagnostic, DiagnosticId, DiagnosticStyledString, ErrorGuaranteed};
2 use crate::{Handler, Level, StashKey};
3 use rustc_lint_defs::Applicability;
5 use rustc_span::{MultiSpan, Span};
6 use std::fmt::{self, Debug};
7 use std::marker::PhantomData;
8 use std::ops::{Deref, DerefMut};
9 use std::thread::panicking;
12 /// Used for emitting structured error messages and other diagnostic information.
14 /// If there is some state in a downstream crate you would like to
15 /// access in the methods of `DiagnosticBuilder` here, consider
16 /// extending `HandlerFlags`, accessed via `self.handler.flags`.
19 pub struct DiagnosticBuilder<'a, G: EmissionGuarantee> {
20 inner: DiagnosticBuilderInner<'a>,
21 _marker: PhantomData<G>,
24 /// This type exists only for `DiagnosticBuilder::forget_guarantee`, because it:
25 /// 1. lacks the `G` parameter and therefore `DiagnosticBuilder<G1>` can be
26 /// converted into `DiagnosticBuilder<G2>` while reusing the `inner` field
27 /// 2. can implement the `Drop` "bomb" instead of `DiagnosticBuilder`, as it
28 /// contains all of the data (`state` + `diagnostic`) of `DiagnosticBuilder`
30 /// The `diagnostic` field is not `Copy` and can't be moved out of whichever
31 /// type implements the `Drop` "bomb", but because of the above two facts, that
32 /// never needs to happen - instead, the whole `inner: DiagnosticBuilderInner`
33 /// can be moved out of a `DiagnosticBuilder` and into another.
36 struct DiagnosticBuilderInner<'a> {
37 state: DiagnosticBuilderState<'a>,
39 /// `Diagnostic` is a large type, and `DiagnosticBuilder` is often used as a
40 /// return value, especially within the frequently-used `PResult` type.
41 /// In theory, return value optimization (RVO) should avoid unnecessary
42 /// copying. In practice, it does not (at the time of writing).
43 diagnostic: Box<Diagnostic>,
47 enum DiagnosticBuilderState<'a> {
48 /// Initial state of a `DiagnosticBuilder`, before `.emit()` or `.cancel()`.
50 /// The `Diagnostic` will be emitted through this `Handler`.
51 Emittable(&'a Handler),
53 /// State of a `DiagnosticBuilder`, after `.emit()` or *during* `.cancel()`.
55 /// The `Diagnostic` will be ignored when calling `.emit()`, and it can be
56 /// assumed that `.emit()` was previously called, to end up in this state.
58 /// While this is also used by `.cancel()`, this state is only observed by
59 /// the `Drop` `impl` of `DiagnosticBuilderInner`, as `.cancel()` takes
60 /// `self` by-value specifically to prevent any attempts to `.emit()`.
62 // FIXME(eddyb) currently this doesn't prevent extending the `Diagnostic`,
63 // despite that being potentially lossy, if important information is added
64 // *after* the original `.emit()` call.
65 AlreadyEmittedOrDuringCancellation,
68 // `DiagnosticBuilderState` should be pointer-sized.
69 rustc_data_structures::static_assert_size!(
70 DiagnosticBuilderState<'_>,
71 std::mem::size_of::<&Handler>()
74 /// Trait for types that `DiagnosticBuilder::emit` can return as a "guarantee"
75 /// (or "proof") token that the emission happened.
76 pub trait EmissionGuarantee: Sized {
77 /// Implementation of `DiagnosticBuilder::emit`, fully controlled by each
78 /// `impl` of `EmissionGuarantee`, to make it impossible to create a value
79 /// of `Self` without actually performing the emission.
81 fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self;
84 /// Private module for sealing the `IsError` helper trait.
85 mod sealed_level_is_error {
88 /// Sealed helper trait for statically checking that a `Level` is an error.
89 crate trait IsError<const L: Level> {}
91 impl IsError<{ Level::Bug }> for () {}
92 impl IsError<{ Level::DelayedBug }> for () {}
93 impl IsError<{ Level::Fatal }> for () {}
94 // NOTE(eddyb) `Level::Error { lint: true }` is also an error, but lints
95 // don't need error guarantees, as their levels are always dynamic.
96 impl IsError<{ Level::Error { lint: false } }> for () {}
99 impl<'a> DiagnosticBuilder<'a, ErrorGuaranteed> {
100 /// Convenience function for internal use, clients should use one of the
101 /// `struct_*` methods on [`Handler`].
102 crate fn new_guaranteeing_error<const L: Level>(handler: &'a Handler, message: &str) -> Self
104 (): sealed_level_is_error::IsError<L>,
107 inner: DiagnosticBuilderInner {
108 state: DiagnosticBuilderState::Emittable(handler),
109 diagnostic: Box::new(Diagnostic::new_with_code(L, None, message)),
111 _marker: PhantomData,
115 /// Discard the guarantee `.emit()` would return, in favor of having the
116 /// type `DiagnosticBuilder<'a, ()>`. This may be necessary whenever there
117 /// is a common codepath handling both errors and warnings.
118 pub fn forget_guarantee(self) -> DiagnosticBuilder<'a, ()> {
119 DiagnosticBuilder { inner: self.inner, _marker: PhantomData }
123 // FIXME(eddyb) make `ErrorGuaranteed` impossible to create outside `.emit()`.
124 impl EmissionGuarantee for ErrorGuaranteed {
125 fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
126 match db.inner.state {
127 // First `.emit()` call, the `&Handler` is still available.
128 DiagnosticBuilderState::Emittable(handler) => {
129 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
131 handler.emit_diagnostic(&db.inner.diagnostic);
133 // Only allow a guarantee if the `level` wasn't switched to a
134 // non-error - the field isn't `pub`, but the whole `Diagnostic`
135 // can be overwritten with a new one, thanks to `DerefMut`.
137 db.inner.diagnostic.is_error(),
138 "emitted non-error ({:?}) diagnostic \
139 from `DiagnosticBuilder<ErrorGuaranteed>`",
140 db.inner.diagnostic.level,
144 // `.emit()` was previously called, disallowed from repeating it,
145 // but can take advantage of the previous `.emit()`'s guarantee
146 // still being applicable (i.e. as a form of idempotency).
147 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {
148 // Only allow a guarantee if the `level` wasn't switched to a
149 // non-error - the field isn't `pub`, but the whole `Diagnostic`
150 // can be overwritten with a new one, thanks to `DerefMut`.
152 db.inner.diagnostic.is_error(),
153 "`DiagnosticBuilder<ErrorGuaranteed>`'s diagnostic \
154 became non-error ({:?}), after original `.emit()`",
155 db.inner.diagnostic.level,
163 impl<'a> DiagnosticBuilder<'a, ()> {
164 /// Convenience function for internal use, clients should use one of the
165 /// `struct_*` methods on [`Handler`].
166 crate fn new(handler: &'a Handler, level: Level, message: &str) -> Self {
167 let diagnostic = Diagnostic::new_with_code(level, None, message);
168 Self::new_diagnostic(handler, diagnostic)
171 /// Creates a new `DiagnosticBuilder` with an already constructed
173 crate fn new_diagnostic(handler: &'a Handler, diagnostic: Diagnostic) -> Self {
174 debug!("Created new diagnostic");
176 inner: DiagnosticBuilderInner {
177 state: DiagnosticBuilderState::Emittable(handler),
178 diagnostic: Box::new(diagnostic),
180 _marker: PhantomData,
185 // FIXME(eddyb) should there be a `Option<ErrorGuaranteed>` impl as well?
186 impl EmissionGuarantee for () {
187 fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
188 match db.inner.state {
189 // First `.emit()` call, the `&Handler` is still available.
190 DiagnosticBuilderState::Emittable(handler) => {
191 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
193 handler.emit_diagnostic(&db.inner.diagnostic);
195 // `.emit()` was previously called, disallowed from repeating it.
196 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
201 /// In general, the `DiagnosticBuilder` uses deref to allow access to
202 /// the fields and methods of the embedded `diagnostic` in a
203 /// transparent way. *However,* many of the methods are intended to
204 /// be used in a chained way, and hence ought to return `self`. In
205 /// that case, we can't just naively forward to the method on the
206 /// `diagnostic`, because the return type would be a `&Diagnostic`
207 /// instead of a `&DiagnosticBuilder<'a>`. This `forward!` macro makes
208 /// it easy to declare such methods on the builder.
209 macro_rules! forward {
210 // Forward pattern for &self -> &Self
213 pub fn $n:ident(&self, $($name:ident: $ty:ty),* $(,)?) -> &Self
216 #[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")]
217 pub fn $n(&self, $($name: $ty),*) -> &Self {
218 self.diagnostic.$n($($name),*);
223 // Forward pattern for &mut self -> &mut Self
226 pub fn $n:ident(&mut self, $($name:ident: $ty:ty),* $(,)?) -> &mut Self
229 #[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")]
230 pub fn $n(&mut self, $($name: $ty),*) -> &mut Self {
231 self.inner.diagnostic.$n($($name),*);
237 impl<G: EmissionGuarantee> Deref for DiagnosticBuilder<'_, G> {
238 type Target = Diagnostic;
240 fn deref(&self) -> &Diagnostic {
241 &self.inner.diagnostic
245 impl<G: EmissionGuarantee> DerefMut for DiagnosticBuilder<'_, G> {
246 fn deref_mut(&mut self) -> &mut Diagnostic {
247 &mut self.inner.diagnostic
251 impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
252 /// Emit the diagnostic.
254 pub fn emit(&mut self) -> G {
255 G::diagnostic_builder_emit_producing_guarantee(self)
258 /// Emit the diagnostic unless `delay` is true,
259 /// in which case the emission will be delayed as a bug.
261 /// See `emit` and `delay_as_bug` for details.
263 pub fn emit_unless(&mut self, delay: bool) -> G {
265 self.downgrade_to_delayed_bug();
270 /// Cancel the diagnostic (a structured diagnostic must either be emitted or
271 /// cancelled or it will panic when dropped).
273 /// This method takes `self` by-value to disallow calling `.emit()` on it,
274 /// which may be expected to *guarantee* the emission of an error, either
275 /// at the time of the call, or through a prior `.emit()` call.
276 pub fn cancel(mut self) {
277 self.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
281 /// Stashes diagnostic for possible later improvement in a different,
282 /// later stage of the compiler. The diagnostic can be accessed with
283 /// the provided `span` and `key` through [`Handler::steal_diagnostic()`].
285 /// As with `buffer`, this is unless the handler has disabled such buffering.
286 pub fn stash(self, span: Span, key: StashKey) {
287 if let Some((diag, handler)) = self.into_diagnostic() {
288 handler.stash_diagnostic(span, key, diag);
292 /// Converts the builder to a `Diagnostic` for later emission,
293 /// unless handler has disabled such buffering, or `.emit()` was called.
294 pub fn into_diagnostic(mut self) -> Option<(Diagnostic, &'a Handler)> {
295 let handler = match self.inner.state {
296 // No `.emit()` calls, the `&Handler` is still available.
297 DiagnosticBuilderState::Emittable(handler) => handler,
298 // `.emit()` was previously called, nothing we can do.
299 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {
304 if handler.flags.dont_buffer_diagnostics || handler.flags.treat_err_as_bug.is_some() {
309 // Take the `Diagnostic` by replacing it with a dummy.
310 let dummy = Diagnostic::new(Level::Allow, "");
311 let diagnostic = std::mem::replace(&mut *self.inner.diagnostic, dummy);
313 // Disable the ICE on `Drop`.
316 // Logging here is useful to help track down where in logs an error was
318 debug!("buffer: diagnostic={:?}", diagnostic);
320 Some((diagnostic, handler))
323 /// Buffers the diagnostic for later emission,
324 /// unless handler has disabled such buffering.
325 pub fn buffer(self, buffered_diagnostics: &mut Vec<Diagnostic>) {
326 buffered_diagnostics.extend(self.into_diagnostic().map(|(diag, _)| diag));
329 /// Delay emission of this diagnostic as a bug.
331 /// This can be useful in contexts where an error indicates a bug but
332 /// typically this only happens when other compilation errors have already
333 /// happened. In those cases this can be used to defer emission of this
334 /// diagnostic as a bug in the compiler only if no other errors have been
337 /// In the meantime, though, callsites are required to deal with the "bug"
338 /// locally in whichever way makes the most sense.
340 pub fn delay_as_bug(&mut self) {
341 self.downgrade_to_delayed_bug();
347 pub fn downgrade_to_delayed_bug(&mut self,) -> &mut Self
351 /// Appends a labeled span to the diagnostic.
353 /// Labels are used to convey additional context for the diagnostic's primary span. They will
354 /// be shown together with the original diagnostic's span, *not* with spans added by
355 /// `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because
356 /// the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed
359 /// Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when
360 /// the diagnostic was constructed. However, the label span is *not* considered a
361 /// ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is
363 pub fn span_label(&mut self, span: Span, label: impl Into<String>) -> &mut Self);
366 /// Labels all the given spans with the provided label.
367 /// See [`Diagnostic::span_label()`] for more information.
370 spans: impl IntoIterator<Item = Span>,
371 label: impl AsRef<str>,
374 forward!(pub fn note_expected_found(
376 expected_label: &dyn fmt::Display,
377 expected: DiagnosticStyledString,
378 found_label: &dyn fmt::Display,
379 found: DiagnosticStyledString,
382 forward!(pub fn note_expected_found_extra(
384 expected_label: &dyn fmt::Display,
385 expected: DiagnosticStyledString,
386 found_label: &dyn fmt::Display,
387 found: DiagnosticStyledString,
388 expected_extra: &dyn fmt::Display,
389 found_extra: &dyn fmt::Display,
392 forward!(pub fn note_unsuccessful_coercion(
394 expected: DiagnosticStyledString,
395 found: DiagnosticStyledString,
398 forward!(pub fn note(&mut self, msg: &str) -> &mut Self);
399 forward!(pub fn span_note(
401 sp: impl Into<MultiSpan>,
404 forward!(pub fn warn(&mut self, msg: &str) -> &mut Self);
405 forward!(pub fn span_warn(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> &mut Self);
406 forward!(pub fn help(&mut self, msg: &str) -> &mut Self);
407 forward!(pub fn span_help(
409 sp: impl Into<MultiSpan>,
412 forward!(pub fn set_is_lint(&mut self,) -> &mut Self);
414 forward!(pub fn disable_suggestions(&mut self,) -> &mut Self);
416 forward!(pub fn multipart_suggestion(
419 suggestion: Vec<(Span, String)>,
420 applicability: Applicability,
422 forward!(pub fn multipart_suggestion_verbose(
425 suggestion: Vec<(Span, String)>,
426 applicability: Applicability,
428 forward!(pub fn tool_only_multipart_suggestion(
431 suggestion: Vec<(Span, String)>,
432 applicability: Applicability,
434 forward!(pub fn span_suggestion(
439 applicability: Applicability,
441 forward!(pub fn span_suggestions(
445 suggestions: impl Iterator<Item = String>,
446 applicability: Applicability,
448 forward!(pub fn multipart_suggestions(
451 suggestions: impl Iterator<Item = Vec<(Span, String)>>,
452 applicability: Applicability,
454 forward!(pub fn span_suggestion_short(
459 applicability: Applicability,
461 forward!(pub fn span_suggestion_verbose(
466 applicability: Applicability,
468 forward!(pub fn span_suggestion_hidden(
473 applicability: Applicability,
475 forward!(pub fn tool_only_span_suggestion(
480 applicability: Applicability,
483 forward!(pub fn set_primary_message(&mut self, msg: impl Into<String>) -> &mut Self);
484 forward!(pub fn set_span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self);
485 forward!(pub fn code(&mut self, s: DiagnosticId) -> &mut Self);
488 impl<G: EmissionGuarantee> Debug for DiagnosticBuilder<'_, G> {
489 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
490 self.inner.diagnostic.fmt(f)
494 /// Destructor bomb - a `DiagnosticBuilder` must be either emitted or cancelled
495 /// or we emit a bug.
496 impl Drop for DiagnosticBuilderInner<'_> {
499 // No `.emit()` or `.cancel()` calls.
500 DiagnosticBuilderState::Emittable(handler) => {
502 handler.emit_diagnostic(&Diagnostic::new(
504 "the following error was constructed but not emitted",
506 handler.emit_diagnostic(&self.diagnostic);
510 // `.emit()` was previously called, or maybe we're during `.cancel()`.
511 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
517 macro_rules! struct_span_err {
518 ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
519 $session.struct_span_err_with_code(
521 &format!($($message)*),
522 $crate::error_code!($code),
528 macro_rules! error_code {
529 ($code:ident) => {{ $crate::DiagnosticId::Error(stringify!($code).to_owned()) }};