1 use crate::diagnostic::IntoDiagnosticArg;
3 Diagnostic, DiagnosticId, DiagnosticMessage, DiagnosticStyledString, ErrorGuaranteed,
6 use crate::{Handler, Level, MultiSpan, StashKey};
7 use rustc_lint_defs::Applicability;
11 use std::fmt::{self, Debug};
12 use std::marker::PhantomData;
13 use std::ops::{Deref, DerefMut};
14 use std::thread::panicking;
17 /// Used for emitting structured error messages and other diagnostic information.
19 /// If there is some state in a downstream crate you would like to
20 /// access in the methods of `DiagnosticBuilder` here, consider
21 /// extending `HandlerFlags`, accessed via `self.handler.flags`.
24 pub struct DiagnosticBuilder<'a, G: EmissionGuarantee> {
25 inner: DiagnosticBuilderInner<'a>,
26 _marker: PhantomData<G>,
29 /// This type exists only for `DiagnosticBuilder::forget_guarantee`, because it:
30 /// 1. lacks the `G` parameter and therefore `DiagnosticBuilder<G1>` can be
31 /// converted into `DiagnosticBuilder<G2>` while reusing the `inner` field
32 /// 2. can implement the `Drop` "bomb" instead of `DiagnosticBuilder`, as it
33 /// contains all of the data (`state` + `diagnostic`) of `DiagnosticBuilder`
35 /// The `diagnostic` field is not `Copy` and can't be moved out of whichever
36 /// type implements the `Drop` "bomb", but because of the above two facts, that
37 /// never needs to happen - instead, the whole `inner: DiagnosticBuilderInner`
38 /// can be moved out of a `DiagnosticBuilder` and into another.
41 struct DiagnosticBuilderInner<'a> {
42 state: DiagnosticBuilderState<'a>,
44 /// `Diagnostic` is a large type, and `DiagnosticBuilder` is often used as a
45 /// return value, especially within the frequently-used `PResult` type.
46 /// In theory, return value optimization (RVO) should avoid unnecessary
47 /// copying. In practice, it does not (at the time of writing).
48 diagnostic: Box<Diagnostic>,
52 enum DiagnosticBuilderState<'a> {
53 /// Initial state of a `DiagnosticBuilder`, before `.emit()` or `.cancel()`.
55 /// The `Diagnostic` will be emitted through this `Handler`.
56 Emittable(&'a Handler),
58 /// State of a `DiagnosticBuilder`, after `.emit()` or *during* `.cancel()`.
60 /// The `Diagnostic` will be ignored when calling `.emit()`, and it can be
61 /// assumed that `.emit()` was previously called, to end up in this state.
63 /// While this is also used by `.cancel()`, this state is only observed by
64 /// the `Drop` `impl` of `DiagnosticBuilderInner`, as `.cancel()` takes
65 /// `self` by-value specifically to prevent any attempts to `.emit()`.
67 // FIXME(eddyb) currently this doesn't prevent extending the `Diagnostic`,
68 // despite that being potentially lossy, if important information is added
69 // *after* the original `.emit()` call.
70 AlreadyEmittedOrDuringCancellation,
73 // `DiagnosticBuilderState` should be pointer-sized.
74 rustc_data_structures::static_assert_size!(
75 DiagnosticBuilderState<'_>,
76 std::mem::size_of::<&Handler>()
79 /// Trait for types that `DiagnosticBuilder::emit` can return as a "guarantee"
80 /// (or "proof") token that the emission happened.
81 pub trait EmissionGuarantee: Sized {
82 /// Implementation of `DiagnosticBuilder::emit`, fully controlled by each
83 /// `impl` of `EmissionGuarantee`, to make it impossible to create a value
84 /// of `Self` without actually performing the emission.
86 fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self;
89 /// Private module for sealing the `IsError` helper trait.
90 mod sealed_level_is_error {
93 /// Sealed helper trait for statically checking that a `Level` is an error.
94 pub(crate) trait IsError<const L: Level> {}
96 impl IsError<{ Level::Bug }> for () {}
97 impl IsError<{ Level::DelayedBug }> for () {}
98 impl IsError<{ Level::Fatal }> for () {}
99 // NOTE(eddyb) `Level::Error { lint: true }` is also an error, but lints
100 // don't need error guarantees, as their levels are always dynamic.
101 impl IsError<{ Level::Error { lint: false } }> for () {}
104 impl<'a> DiagnosticBuilder<'a, ErrorGuaranteed> {
105 /// Convenience function for internal use, clients should use one of the
106 /// `struct_*` methods on [`Handler`].
107 pub(crate) fn new_guaranteeing_error<M: Into<DiagnosticMessage>, const L: Level>(
108 handler: &'a Handler,
112 (): sealed_level_is_error::IsError<L>,
115 inner: DiagnosticBuilderInner {
116 state: DiagnosticBuilderState::Emittable(handler),
117 diagnostic: Box::new(Diagnostic::new_with_code(L, None, message)),
119 _marker: PhantomData,
123 /// Discard the guarantee `.emit()` would return, in favor of having the
124 /// type `DiagnosticBuilder<'a, ()>`. This may be necessary whenever there
125 /// is a common codepath handling both errors and warnings.
126 pub fn forget_guarantee(self) -> DiagnosticBuilder<'a, ()> {
127 DiagnosticBuilder { inner: self.inner, _marker: PhantomData }
131 // FIXME(eddyb) make `ErrorGuaranteed` impossible to create outside `.emit()`.
132 impl EmissionGuarantee for ErrorGuaranteed {
133 fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
134 match db.inner.state {
135 // First `.emit()` call, the `&Handler` is still available.
136 DiagnosticBuilderState::Emittable(handler) => {
137 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
139 let guar = handler.emit_diagnostic(&mut db.inner.diagnostic);
141 // Only allow a guarantee if the `level` wasn't switched to a
142 // non-error - the field isn't `pub`, but the whole `Diagnostic`
143 // can be overwritten with a new one, thanks to `DerefMut`.
145 db.inner.diagnostic.is_error(),
146 "emitted non-error ({:?}) diagnostic \
147 from `DiagnosticBuilder<ErrorGuaranteed>`",
148 db.inner.diagnostic.level,
152 // `.emit()` was previously called, disallowed from repeating it,
153 // but can take advantage of the previous `.emit()`'s guarantee
154 // still being applicable (i.e. as a form of idempotency).
155 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {
156 // Only allow a guarantee if the `level` wasn't switched to a
157 // non-error - the field isn't `pub`, but the whole `Diagnostic`
158 // can be overwritten with a new one, thanks to `DerefMut`.
160 db.inner.diagnostic.is_error(),
161 "`DiagnosticBuilder<ErrorGuaranteed>`'s diagnostic \
162 became non-error ({:?}), after original `.emit()`",
163 db.inner.diagnostic.level,
165 ErrorGuaranteed::unchecked_claim_error_was_emitted()
171 impl<'a> DiagnosticBuilder<'a, ()> {
172 /// Convenience function for internal use, clients should use one of the
173 /// `struct_*` methods on [`Handler`].
174 pub(crate) fn new<M: Into<DiagnosticMessage>>(
175 handler: &'a Handler,
179 let diagnostic = Diagnostic::new_with_code(level, None, message);
180 Self::new_diagnostic(handler, diagnostic)
183 /// Creates a new `DiagnosticBuilder` with an already constructed
185 pub(crate) fn new_diagnostic(handler: &'a Handler, diagnostic: Diagnostic) -> Self {
186 debug!("Created new diagnostic");
188 inner: DiagnosticBuilderInner {
189 state: DiagnosticBuilderState::Emittable(handler),
190 diagnostic: Box::new(diagnostic),
192 _marker: PhantomData,
197 // FIXME(eddyb) should there be a `Option<ErrorGuaranteed>` impl as well?
198 impl EmissionGuarantee for () {
199 fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
200 match db.inner.state {
201 // First `.emit()` call, the `&Handler` is still available.
202 DiagnosticBuilderState::Emittable(handler) => {
203 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
205 handler.emit_diagnostic(&mut db.inner.diagnostic);
207 // `.emit()` was previously called, disallowed from repeating it.
208 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
213 impl<'a> DiagnosticBuilder<'a, !> {
214 /// Convenience function for internal use, clients should use one of the
215 /// `struct_*` methods on [`Handler`].
216 pub(crate) fn new_fatal(handler: &'a Handler, message: impl Into<DiagnosticMessage>) -> Self {
217 let diagnostic = Diagnostic::new_with_code(Level::Fatal, None, message);
218 Self::new_diagnostic_fatal(handler, diagnostic)
221 /// Creates a new `DiagnosticBuilder` with an already constructed
223 pub(crate) fn new_diagnostic_fatal(handler: &'a Handler, diagnostic: Diagnostic) -> Self {
224 debug!("Created new diagnostic");
226 inner: DiagnosticBuilderInner {
227 state: DiagnosticBuilderState::Emittable(handler),
228 diagnostic: Box::new(diagnostic),
230 _marker: PhantomData,
235 impl EmissionGuarantee for ! {
236 fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
237 match db.inner.state {
238 // First `.emit()` call, the `&Handler` is still available.
239 DiagnosticBuilderState::Emittable(handler) => {
240 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
242 handler.emit_diagnostic(&mut db.inner.diagnostic);
244 // `.emit()` was previously called, disallowed from repeating it.
245 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
247 // Then fatally error, returning `!`
248 crate::FatalError.raise()
252 /// In general, the `DiagnosticBuilder` uses deref to allow access to
253 /// the fields and methods of the embedded `diagnostic` in a
254 /// transparent way. *However,* many of the methods are intended to
255 /// be used in a chained way, and hence ought to return `self`. In
256 /// that case, we can't just naively forward to the method on the
257 /// `diagnostic`, because the return type would be a `&Diagnostic`
258 /// instead of a `&DiagnosticBuilder<'a>`. This `forward!` macro makes
259 /// it easy to declare such methods on the builder.
260 macro_rules! forward {
261 // Forward pattern for &mut self -> &mut Self
264 pub fn $n:ident(&mut self, $($name:ident: $ty:ty),* $(,)?) -> &mut Self
267 #[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")]
268 pub fn $n(&mut self, $($name: $ty),*) -> &mut Self {
269 self.inner.diagnostic.$n($($name),*);
275 impl<G: EmissionGuarantee> Deref for DiagnosticBuilder<'_, G> {
276 type Target = Diagnostic;
278 fn deref(&self) -> &Diagnostic {
279 &self.inner.diagnostic
283 impl<G: EmissionGuarantee> DerefMut for DiagnosticBuilder<'_, G> {
284 fn deref_mut(&mut self) -> &mut Diagnostic {
285 &mut self.inner.diagnostic
289 impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
290 /// Emit the diagnostic.
292 pub fn emit(&mut self) -> G {
293 G::diagnostic_builder_emit_producing_guarantee(self)
296 /// Emit the diagnostic unless `delay` is true,
297 /// in which case the emission will be delayed as a bug.
299 /// See `emit` and `delay_as_bug` for details.
301 pub fn emit_unless(&mut self, delay: bool) -> G {
303 self.downgrade_to_delayed_bug();
308 /// Cancel the diagnostic (a structured diagnostic must either be emitted or
309 /// cancelled or it will panic when dropped).
311 /// This method takes `self` by-value to disallow calling `.emit()` on it,
312 /// which may be expected to *guarantee* the emission of an error, either
313 /// at the time of the call, or through a prior `.emit()` call.
314 pub fn cancel(mut self) {
315 self.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
319 /// Stashes diagnostic for possible later improvement in a different,
320 /// later stage of the compiler. The diagnostic can be accessed with
321 /// the provided `span` and `key` through [`Handler::steal_diagnostic()`].
323 /// As with `buffer`, this is unless the handler has disabled such buffering.
324 pub fn stash(self, span: Span, key: StashKey) {
325 if let Some((diag, handler)) = self.into_diagnostic() {
326 handler.stash_diagnostic(span, key, diag);
330 /// Converts the builder to a `Diagnostic` for later emission,
331 /// unless handler has disabled such buffering, or `.emit()` was called.
332 pub fn into_diagnostic(mut self) -> Option<(Diagnostic, &'a Handler)> {
333 let handler = match self.inner.state {
334 // No `.emit()` calls, the `&Handler` is still available.
335 DiagnosticBuilderState::Emittable(handler) => handler,
336 // `.emit()` was previously called, nothing we can do.
337 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {
342 if handler.flags.dont_buffer_diagnostics || handler.flags.treat_err_as_bug.is_some() {
347 // Take the `Diagnostic` by replacing it with a dummy.
348 let dummy = Diagnostic::new(Level::Allow, DiagnosticMessage::Str("".to_string()));
349 let diagnostic = std::mem::replace(&mut *self.inner.diagnostic, dummy);
351 // Disable the ICE on `Drop`.
354 // Logging here is useful to help track down where in logs an error was
356 debug!("buffer: diagnostic={:?}", diagnostic);
358 Some((diagnostic, handler))
361 /// Buffers the diagnostic for later emission,
362 /// unless handler has disabled such buffering.
363 pub fn buffer(self, buffered_diagnostics: &mut Vec<Diagnostic>) {
364 buffered_diagnostics.extend(self.into_diagnostic().map(|(diag, _)| diag));
367 /// Delay emission of this diagnostic as a bug.
369 /// This can be useful in contexts where an error indicates a bug but
370 /// typically this only happens when other compilation errors have already
371 /// happened. In those cases this can be used to defer emission of this
372 /// diagnostic as a bug in the compiler only if no other errors have been
375 /// In the meantime, though, callsites are required to deal with the "bug"
376 /// locally in whichever way makes the most sense.
378 pub fn delay_as_bug(&mut self) {
379 self.downgrade_to_delayed_bug();
385 pub fn downgrade_to_delayed_bug(&mut self,) -> &mut Self
389 /// Appends a labeled span to the diagnostic.
391 /// Labels are used to convey additional context for the diagnostic's primary span. They will
392 /// be shown together with the original diagnostic's span, *not* with spans added by
393 /// `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because
394 /// the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed
397 /// Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when
398 /// the diagnostic was constructed. However, the label span is *not* considered a
399 /// ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is
401 pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self);
404 /// Labels all the given spans with the provided label.
405 /// See [`Diagnostic::span_label()`] for more information.
408 spans: impl IntoIterator<Item = Span>,
409 label: impl AsRef<str>,
412 forward!(pub fn note_expected_found(
414 expected_label: &dyn fmt::Display,
415 expected: DiagnosticStyledString,
416 found_label: &dyn fmt::Display,
417 found: DiagnosticStyledString,
420 forward!(pub fn note_expected_found_extra(
422 expected_label: &dyn fmt::Display,
423 expected: DiagnosticStyledString,
424 found_label: &dyn fmt::Display,
425 found: DiagnosticStyledString,
426 expected_extra: &dyn fmt::Display,
427 found_extra: &dyn fmt::Display,
430 forward!(pub fn note_unsuccessful_coercion(
432 expected: DiagnosticStyledString,
433 found: DiagnosticStyledString,
436 forward!(pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
437 forward!(pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
438 forward!(pub fn span_note(
440 sp: impl Into<MultiSpan>,
441 msg: impl Into<SubdiagnosticMessage>,
443 forward!(pub fn span_note_once(
445 sp: impl Into<MultiSpan>,
446 msg: impl Into<SubdiagnosticMessage>,
448 forward!(pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
449 forward!(pub fn span_warn(
451 sp: impl Into<MultiSpan>,
452 msg: impl Into<SubdiagnosticMessage>,
454 forward!(pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
455 forward!(pub fn span_help(
457 sp: impl Into<MultiSpan>,
458 msg: impl Into<SubdiagnosticMessage>,
460 forward!(pub fn help_use_latest_edition(&mut self,) -> &mut Self);
461 forward!(pub fn set_is_lint(&mut self,) -> &mut Self);
463 forward!(pub fn disable_suggestions(&mut self,) -> &mut Self);
465 forward!(pub fn multipart_suggestion(
467 msg: impl Into<SubdiagnosticMessage>,
468 suggestion: Vec<(Span, String)>,
469 applicability: Applicability,
471 forward!(pub fn multipart_suggestion_verbose(
473 msg: impl Into<SubdiagnosticMessage>,
474 suggestion: Vec<(Span, String)>,
475 applicability: Applicability,
477 forward!(pub fn tool_only_multipart_suggestion(
479 msg: impl Into<SubdiagnosticMessage>,
480 suggestion: Vec<(Span, String)>,
481 applicability: Applicability,
483 forward!(pub fn span_suggestion(
486 msg: impl Into<SubdiagnosticMessage>,
487 suggestion: impl ToString,
488 applicability: Applicability,
490 forward!(pub fn span_suggestions(
493 msg: impl Into<SubdiagnosticMessage>,
494 suggestions: impl Iterator<Item = String>,
495 applicability: Applicability,
497 forward!(pub fn multipart_suggestions(
499 msg: impl Into<SubdiagnosticMessage>,
500 suggestions: impl Iterator<Item = Vec<(Span, String)>>,
501 applicability: Applicability,
503 forward!(pub fn span_suggestion_short(
506 msg: impl Into<SubdiagnosticMessage>,
507 suggestion: impl ToString,
508 applicability: Applicability,
510 forward!(pub fn span_suggestion_verbose(
513 msg: impl Into<SubdiagnosticMessage>,
514 suggestion: impl ToString,
515 applicability: Applicability,
517 forward!(pub fn span_suggestion_hidden(
520 msg: impl Into<SubdiagnosticMessage>,
521 suggestion: impl ToString,
522 applicability: Applicability,
524 forward!(pub fn tool_only_span_suggestion(
527 msg: impl Into<SubdiagnosticMessage>,
528 suggestion: impl ToString,
529 applicability: Applicability,
532 forward!(pub fn set_primary_message(&mut self, msg: impl Into<String>) -> &mut Self);
533 forward!(pub fn set_span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self);
534 forward!(pub fn code(&mut self, s: DiagnosticId) -> &mut Self);
535 forward!(pub fn set_arg(
537 name: impl Into<Cow<'static, str>>,
538 arg: impl IntoDiagnosticArg,
541 forward!(pub fn subdiagnostic(
543 subdiagnostic: impl crate::AddSubdiagnostic
547 impl<G: EmissionGuarantee> Debug for DiagnosticBuilder<'_, G> {
548 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
549 self.inner.diagnostic.fmt(f)
553 /// Destructor bomb - a `DiagnosticBuilder` must be either emitted or cancelled
554 /// or we emit a bug.
555 impl Drop for DiagnosticBuilderInner<'_> {
558 // No `.emit()` or `.cancel()` calls.
559 DiagnosticBuilderState::Emittable(handler) => {
561 handler.emit_diagnostic(&mut Diagnostic::new(
563 DiagnosticMessage::Str(
564 "the following error was constructed but not emitted".to_string(),
567 handler.emit_diagnostic(&mut self.diagnostic);
571 // `.emit()` was previously called, or maybe we're during `.cancel()`.
572 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
578 macro_rules! struct_span_err {
579 ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
580 $session.struct_span_err_with_code(
582 &format!($($message)*),
583 $crate::error_code!($code),
589 macro_rules! error_code {
590 ($code:ident) => {{ $crate::DiagnosticId::Error(stringify!($code).to_owned()) }};