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;
16 /// Used for emitting structured error messages and other diagnostic information.
18 /// If there is some state in a downstream crate you would like to
19 /// access in the methods of `DiagnosticBuilder` here, consider
20 /// extending `HandlerFlags`, accessed via `self.handler.flags`.
23 pub struct DiagnosticBuilder<'a, G: EmissionGuarantee> {
24 inner: DiagnosticBuilderInner<'a>,
25 _marker: PhantomData<G>,
28 /// This type exists only for `DiagnosticBuilder::forget_guarantee`, because it:
29 /// 1. lacks the `G` parameter and therefore `DiagnosticBuilder<G1>` can be
30 /// converted into `DiagnosticBuilder<G2>` while reusing the `inner` field
31 /// 2. can implement the `Drop` "bomb" instead of `DiagnosticBuilder`, as it
32 /// contains all of the data (`state` + `diagnostic`) of `DiagnosticBuilder`
34 /// The `diagnostic` field is not `Copy` and can't be moved out of whichever
35 /// type implements the `Drop` "bomb", but because of the above two facts, that
36 /// never needs to happen - instead, the whole `inner: DiagnosticBuilderInner`
37 /// can be moved out of a `DiagnosticBuilder` and into another.
40 struct DiagnosticBuilderInner<'a> {
41 state: DiagnosticBuilderState<'a>,
43 /// `Diagnostic` is a large type, and `DiagnosticBuilder` is often used as a
44 /// return value, especially within the frequently-used `PResult` type.
45 /// In theory, return value optimization (RVO) should avoid unnecessary
46 /// copying. In practice, it does not (at the time of writing).
47 diagnostic: Box<Diagnostic>,
51 enum DiagnosticBuilderState<'a> {
52 /// Initial state of a `DiagnosticBuilder`, before `.emit()` or `.cancel()`.
54 /// The `Diagnostic` will be emitted through this `Handler`.
55 Emittable(&'a Handler),
57 /// State of a `DiagnosticBuilder`, after `.emit()` or *during* `.cancel()`.
59 /// The `Diagnostic` will be ignored when calling `.emit()`, and it can be
60 /// assumed that `.emit()` was previously called, to end up in this state.
62 /// While this is also used by `.cancel()`, this state is only observed by
63 /// the `Drop` `impl` of `DiagnosticBuilderInner`, as `.cancel()` takes
64 /// `self` by-value specifically to prevent any attempts to `.emit()`.
66 // FIXME(eddyb) currently this doesn't prevent extending the `Diagnostic`,
67 // despite that being potentially lossy, if important information is added
68 // *after* the original `.emit()` call.
69 AlreadyEmittedOrDuringCancellation,
72 // `DiagnosticBuilderState` should be pointer-sized.
73 rustc_data_structures::static_assert_size!(
74 DiagnosticBuilderState<'_>,
75 std::mem::size_of::<&Handler>()
78 /// Trait for types that `DiagnosticBuilder::emit` can return as a "guarantee"
79 /// (or "proof") token that the emission happened.
80 pub trait EmissionGuarantee: Sized {
81 /// Implementation of `DiagnosticBuilder::emit`, fully controlled by each
82 /// `impl` of `EmissionGuarantee`, to make it impossible to create a value
83 /// of `Self` without actually performing the emission.
85 fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self;
87 /// Creates a new `DiagnosticBuilder` that will return this type of guarantee.
89 fn make_diagnostic_builder(
91 msg: impl Into<DiagnosticMessage>,
92 ) -> DiagnosticBuilder<'_, Self>;
95 /// Private module for sealing the `IsError` helper trait.
96 mod sealed_level_is_error {
99 /// Sealed helper trait for statically checking that a `Level` is an error.
100 pub(crate) trait IsError<const L: Level> {}
102 impl IsError<{ Level::Bug }> for () {}
103 impl IsError<{ Level::DelayedBug }> for () {}
104 impl IsError<{ Level::Fatal }> for () {}
105 // NOTE(eddyb) `Level::Error { lint: true }` is also an error, but lints
106 // don't need error guarantees, as their levels are always dynamic.
107 impl IsError<{ Level::Error { lint: false } }> for () {}
110 impl<'a> DiagnosticBuilder<'a, ErrorGuaranteed> {
111 /// Convenience function for internal use, clients should use one of the
112 /// `struct_*` methods on [`Handler`].
113 pub(crate) fn new_guaranteeing_error<M: Into<DiagnosticMessage>, const L: Level>(
114 handler: &'a Handler,
118 (): sealed_level_is_error::IsError<L>,
121 inner: DiagnosticBuilderInner {
122 state: DiagnosticBuilderState::Emittable(handler),
123 diagnostic: Box::new(Diagnostic::new_with_code(L, None, message)),
125 _marker: PhantomData,
129 /// Discard the guarantee `.emit()` would return, in favor of having the
130 /// type `DiagnosticBuilder<'a, ()>`. This may be necessary whenever there
131 /// is a common codepath handling both errors and warnings.
132 pub fn forget_guarantee(self) -> DiagnosticBuilder<'a, ()> {
133 DiagnosticBuilder { inner: self.inner, _marker: PhantomData }
137 // FIXME(eddyb) make `ErrorGuaranteed` impossible to create outside `.emit()`.
138 impl EmissionGuarantee for ErrorGuaranteed {
139 fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
140 match db.inner.state {
141 // First `.emit()` call, the `&Handler` is still available.
142 DiagnosticBuilderState::Emittable(handler) => {
143 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
145 let guar = handler.emit_diagnostic(&mut db.inner.diagnostic);
147 // Only allow a guarantee if the `level` wasn't switched to a
148 // non-error - the field isn't `pub`, but the whole `Diagnostic`
149 // can be overwritten with a new one, thanks to `DerefMut`.
151 db.inner.diagnostic.is_error(),
152 "emitted non-error ({:?}) diagnostic \
153 from `DiagnosticBuilder<ErrorGuaranteed>`",
154 db.inner.diagnostic.level,
158 // `.emit()` was previously called, disallowed from repeating it,
159 // but can take advantage of the previous `.emit()`'s guarantee
160 // still being applicable (i.e. as a form of idempotency).
161 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {
162 // Only allow a guarantee if the `level` wasn't switched to a
163 // non-error - the field isn't `pub`, but the whole `Diagnostic`
164 // can be overwritten with a new one, thanks to `DerefMut`.
166 db.inner.diagnostic.is_error(),
167 "`DiagnosticBuilder<ErrorGuaranteed>`'s diagnostic \
168 became non-error ({:?}), after original `.emit()`",
169 db.inner.diagnostic.level,
171 ErrorGuaranteed::unchecked_claim_error_was_emitted()
176 fn make_diagnostic_builder(
178 msg: impl Into<DiagnosticMessage>,
179 ) -> DiagnosticBuilder<'_, Self> {
180 DiagnosticBuilder::new_guaranteeing_error::<_, { Level::Error { lint: false } }>(
186 impl<'a> DiagnosticBuilder<'a, ()> {
187 /// Convenience function for internal use, clients should use one of the
188 /// `struct_*` methods on [`Handler`].
189 pub(crate) fn new<M: Into<DiagnosticMessage>>(
190 handler: &'a Handler,
194 let diagnostic = Diagnostic::new_with_code(level, None, message);
195 Self::new_diagnostic(handler, diagnostic)
198 /// Creates a new `DiagnosticBuilder` with an already constructed
200 pub(crate) fn new_diagnostic(handler: &'a Handler, diagnostic: Diagnostic) -> Self {
201 debug!("Created new diagnostic");
203 inner: DiagnosticBuilderInner {
204 state: DiagnosticBuilderState::Emittable(handler),
205 diagnostic: Box::new(diagnostic),
207 _marker: PhantomData,
212 // FIXME(eddyb) should there be a `Option<ErrorGuaranteed>` impl as well?
213 impl EmissionGuarantee for () {
214 fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
215 match db.inner.state {
216 // First `.emit()` call, the `&Handler` is still available.
217 DiagnosticBuilderState::Emittable(handler) => {
218 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
220 handler.emit_diagnostic(&mut db.inner.diagnostic);
222 // `.emit()` was previously called, disallowed from repeating it.
223 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
227 fn make_diagnostic_builder(
229 msg: impl Into<DiagnosticMessage>,
230 ) -> DiagnosticBuilder<'_, Self> {
231 DiagnosticBuilder::new(handler, Level::Warning(None), msg)
235 impl<'a> DiagnosticBuilder<'a, !> {
236 /// Convenience function for internal use, clients should use one of the
237 /// `struct_*` methods on [`Handler`].
238 pub(crate) fn new_fatal(handler: &'a Handler, message: impl Into<DiagnosticMessage>) -> Self {
239 let diagnostic = Diagnostic::new_with_code(Level::Fatal, None, message);
240 Self::new_diagnostic_fatal(handler, diagnostic)
243 /// Creates a new `DiagnosticBuilder` with an already constructed
245 pub(crate) fn new_diagnostic_fatal(handler: &'a Handler, diagnostic: Diagnostic) -> Self {
246 debug!("Created new diagnostic");
248 inner: DiagnosticBuilderInner {
249 state: DiagnosticBuilderState::Emittable(handler),
250 diagnostic: Box::new(diagnostic),
252 _marker: PhantomData,
257 impl EmissionGuarantee for ! {
258 fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
259 match db.inner.state {
260 // First `.emit()` call, the `&Handler` is still available.
261 DiagnosticBuilderState::Emittable(handler) => {
262 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
264 handler.emit_diagnostic(&mut db.inner.diagnostic);
266 // `.emit()` was previously called, disallowed from repeating it.
267 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
269 // Then fatally error, returning `!`
270 crate::FatalError.raise()
273 fn make_diagnostic_builder(
275 msg: impl Into<DiagnosticMessage>,
276 ) -> DiagnosticBuilder<'_, Self> {
277 DiagnosticBuilder::new_fatal(handler, msg)
281 /// In general, the `DiagnosticBuilder` uses deref to allow access to
282 /// the fields and methods of the embedded `diagnostic` in a
283 /// transparent way. *However,* many of the methods are intended to
284 /// be used in a chained way, and hence ought to return `self`. In
285 /// that case, we can't just naively forward to the method on the
286 /// `diagnostic`, because the return type would be a `&Diagnostic`
287 /// instead of a `&DiagnosticBuilder<'a>`. This `forward!` macro makes
288 /// it easy to declare such methods on the builder.
289 macro_rules! forward {
290 // Forward pattern for &mut self -> &mut Self
293 pub fn $n:ident(&mut self, $($name:ident: $ty:ty),* $(,)?) -> &mut Self
296 #[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")]
297 pub fn $n(&mut self, $($name: $ty),*) -> &mut Self {
298 self.inner.diagnostic.$n($($name),*);
304 impl<G: EmissionGuarantee> Deref for DiagnosticBuilder<'_, G> {
305 type Target = Diagnostic;
307 fn deref(&self) -> &Diagnostic {
308 &self.inner.diagnostic
312 impl<G: EmissionGuarantee> DerefMut for DiagnosticBuilder<'_, G> {
313 fn deref_mut(&mut self) -> &mut Diagnostic {
314 &mut self.inner.diagnostic
318 impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
319 /// Emit the diagnostic.
321 pub fn emit(&mut self) -> G {
322 G::diagnostic_builder_emit_producing_guarantee(self)
325 /// Emit the diagnostic unless `delay` is true,
326 /// in which case the emission will be delayed as a bug.
328 /// See `emit` and `delay_as_bug` for details.
330 pub fn emit_unless(&mut self, delay: bool) -> G {
332 self.downgrade_to_delayed_bug();
337 /// Cancel the diagnostic (a structured diagnostic must either be emitted or
338 /// cancelled or it will panic when dropped).
340 /// This method takes `self` by-value to disallow calling `.emit()` on it,
341 /// which may be expected to *guarantee* the emission of an error, either
342 /// at the time of the call, or through a prior `.emit()` call.
343 pub fn cancel(mut self) {
344 self.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
348 /// Stashes diagnostic for possible later improvement in a different,
349 /// later stage of the compiler. The diagnostic can be accessed with
350 /// the provided `span` and `key` through [`Handler::steal_diagnostic()`].
352 /// As with `buffer`, this is unless the handler has disabled such buffering.
353 pub fn stash(self, span: Span, key: StashKey) {
354 if let Some((diag, handler)) = self.into_diagnostic() {
355 handler.stash_diagnostic(span, key, diag);
359 /// Converts the builder to a `Diagnostic` for later emission,
360 /// unless handler has disabled such buffering, or `.emit()` was called.
361 pub fn into_diagnostic(mut self) -> Option<(Diagnostic, &'a Handler)> {
362 let handler = match self.inner.state {
363 // No `.emit()` calls, the `&Handler` is still available.
364 DiagnosticBuilderState::Emittable(handler) => handler,
365 // `.emit()` was previously called, nothing we can do.
366 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {
371 if handler.flags.dont_buffer_diagnostics || handler.flags.treat_err_as_bug.is_some() {
376 // Take the `Diagnostic` by replacing it with a dummy.
377 let dummy = Diagnostic::new(Level::Allow, DiagnosticMessage::Str("".to_string()));
378 let diagnostic = std::mem::replace(&mut *self.inner.diagnostic, dummy);
380 // Disable the ICE on `Drop`.
383 // Logging here is useful to help track down where in logs an error was
385 debug!("buffer: diagnostic={:?}", diagnostic);
387 Some((diagnostic, handler))
390 /// Buffers the diagnostic for later emission,
391 /// unless handler has disabled such buffering.
392 pub fn buffer(self, buffered_diagnostics: &mut Vec<Diagnostic>) {
393 buffered_diagnostics.extend(self.into_diagnostic().map(|(diag, _)| diag));
396 /// Delay emission of this diagnostic as a bug.
398 /// This can be useful in contexts where an error indicates a bug but
399 /// typically this only happens when other compilation errors have already
400 /// happened. In those cases this can be used to defer emission of this
401 /// diagnostic as a bug in the compiler only if no other errors have been
404 /// In the meantime, though, callsites are required to deal with the "bug"
405 /// locally in whichever way makes the most sense.
407 pub fn delay_as_bug(&mut self) {
408 self.downgrade_to_delayed_bug();
414 pub fn downgrade_to_delayed_bug(&mut self,) -> &mut Self
418 /// Appends a labeled span to the diagnostic.
420 /// Labels are used to convey additional context for the diagnostic's primary span. They will
421 /// be shown together with the original diagnostic's span, *not* with spans added by
422 /// `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because
423 /// the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed
426 /// Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when
427 /// the diagnostic was constructed. However, the label span is *not* considered a
428 /// ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is
430 pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self);
433 /// Labels all the given spans with the provided label.
434 /// See [`Diagnostic::span_label()`] for more information.
437 spans: impl IntoIterator<Item = Span>,
438 label: impl AsRef<str>,
441 forward!(pub fn note_expected_found(
443 expected_label: &dyn fmt::Display,
444 expected: DiagnosticStyledString,
445 found_label: &dyn fmt::Display,
446 found: DiagnosticStyledString,
449 forward!(pub fn note_expected_found_extra(
451 expected_label: &dyn fmt::Display,
452 expected: DiagnosticStyledString,
453 found_label: &dyn fmt::Display,
454 found: DiagnosticStyledString,
455 expected_extra: &dyn fmt::Display,
456 found_extra: &dyn fmt::Display,
459 forward!(pub fn note_unsuccessful_coercion(
461 expected: DiagnosticStyledString,
462 found: DiagnosticStyledString,
465 forward!(pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
466 forward!(pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
467 forward!(pub fn span_note(
469 sp: impl Into<MultiSpan>,
470 msg: impl Into<SubdiagnosticMessage>,
472 forward!(pub fn span_note_once(
474 sp: impl Into<MultiSpan>,
475 msg: impl Into<SubdiagnosticMessage>,
477 forward!(pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
478 forward!(pub fn span_warn(
480 sp: impl Into<MultiSpan>,
481 msg: impl Into<SubdiagnosticMessage>,
483 forward!(pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
484 forward!(pub fn span_help(
486 sp: impl Into<MultiSpan>,
487 msg: impl Into<SubdiagnosticMessage>,
489 forward!(pub fn help_use_latest_edition(&mut self,) -> &mut Self);
490 forward!(pub fn set_is_lint(&mut self,) -> &mut Self);
492 forward!(pub fn disable_suggestions(&mut self,) -> &mut Self);
493 forward!(pub fn clear_suggestions(&mut self,) -> &mut Self);
495 forward!(pub fn multipart_suggestion(
497 msg: impl Into<SubdiagnosticMessage>,
498 suggestion: Vec<(Span, String)>,
499 applicability: Applicability,
501 forward!(pub fn multipart_suggestion_verbose(
503 msg: impl Into<SubdiagnosticMessage>,
504 suggestion: Vec<(Span, String)>,
505 applicability: Applicability,
507 forward!(pub fn tool_only_multipart_suggestion(
509 msg: impl Into<SubdiagnosticMessage>,
510 suggestion: Vec<(Span, String)>,
511 applicability: Applicability,
513 forward!(pub fn span_suggestion(
516 msg: impl Into<SubdiagnosticMessage>,
517 suggestion: impl ToString,
518 applicability: Applicability,
520 forward!(pub fn span_suggestions(
523 msg: impl Into<SubdiagnosticMessage>,
524 suggestions: impl Iterator<Item = String>,
525 applicability: Applicability,
527 forward!(pub fn multipart_suggestions(
529 msg: impl Into<SubdiagnosticMessage>,
530 suggestions: impl Iterator<Item = Vec<(Span, String)>>,
531 applicability: Applicability,
533 forward!(pub fn span_suggestion_short(
536 msg: impl Into<SubdiagnosticMessage>,
537 suggestion: impl ToString,
538 applicability: Applicability,
540 forward!(pub fn span_suggestion_verbose(
543 msg: impl Into<SubdiagnosticMessage>,
544 suggestion: impl ToString,
545 applicability: Applicability,
547 forward!(pub fn span_suggestion_hidden(
550 msg: impl Into<SubdiagnosticMessage>,
551 suggestion: impl ToString,
552 applicability: Applicability,
554 forward!(pub fn tool_only_span_suggestion(
557 msg: impl Into<SubdiagnosticMessage>,
558 suggestion: impl ToString,
559 applicability: Applicability,
562 forward!(pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self);
563 forward!(pub fn set_span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self);
564 forward!(pub fn code(&mut self, s: DiagnosticId) -> &mut Self);
565 forward!(pub fn set_arg(
567 name: impl Into<Cow<'static, str>>,
568 arg: impl IntoDiagnosticArg,
571 forward!(pub fn subdiagnostic(
573 subdiagnostic: impl crate::AddSubdiagnostic
577 impl<G: EmissionGuarantee> Debug for DiagnosticBuilder<'_, G> {
578 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
579 self.inner.diagnostic.fmt(f)
583 /// Destructor bomb - a `DiagnosticBuilder` must be either emitted or cancelled
584 /// or we emit a bug.
585 impl Drop for DiagnosticBuilderInner<'_> {
588 // No `.emit()` or `.cancel()` calls.
589 DiagnosticBuilderState::Emittable(handler) => {
591 handler.emit_diagnostic(&mut Diagnostic::new(
593 DiagnosticMessage::Str(
594 "the following error was constructed but not emitted".to_string(),
597 handler.emit_diagnostic(&mut self.diagnostic);
598 panic!("error was constructed but not emitted");
601 // `.emit()` was previously called, or maybe we're during `.cancel()`.
602 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
608 macro_rules! struct_span_err {
609 ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
610 $session.struct_span_err_with_code(
612 &format!($($message)*),
613 $crate::error_code!($code),
619 macro_rules! error_code {
620 ($code:ident) => {{ $crate::DiagnosticId::Error(stringify!($code).to_owned()) }};
623 /// Wrapper around a `DiagnosticBuilder` for creating lints.
624 pub struct LintDiagnosticBuilder<'a, G: EmissionGuarantee>(DiagnosticBuilder<'a, G>);
626 impl<'a, G: EmissionGuarantee> LintDiagnosticBuilder<'a, G> {
627 #[rustc_lint_diagnostics]
628 /// Return the inner `DiagnosticBuilder`, first setting the primary message to `msg`.
629 pub fn build(mut self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'a, G> {
630 self.0.set_primary_message(msg);
631 self.0.set_is_lint();
635 /// Create a `LintDiagnosticBuilder` from some existing `DiagnosticBuilder`.
636 pub fn new(err: DiagnosticBuilder<'a, G>) -> LintDiagnosticBuilder<'a, G> {
637 LintDiagnosticBuilder(err)
641 impl<'a> LintDiagnosticBuilder<'a, ErrorGuaranteed> {
642 pub fn forget_guarantee(self) -> LintDiagnosticBuilder<'a, ()> {
643 LintDiagnosticBuilder(self.0.forget_guarantee())