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 /// Trait implemented by error types. This should not be implemented manually. Instead, use
17 /// `#[derive(Diagnostic)]` -- see [rustc_macros::Diagnostic].
18 #[cfg_attr(bootstrap, rustc_diagnostic_item = "SessionDiagnostic")]
19 #[cfg_attr(not(bootstrap), rustc_diagnostic_item = "IntoDiagnostic")]
20 pub trait IntoDiagnostic<'a, T: EmissionGuarantee = ErrorGuaranteed> {
21 /// Write out as a diagnostic out of `Handler`.
23 fn into_diagnostic(self, handler: &'a Handler) -> DiagnosticBuilder<'a, T>;
26 /// Used for emitting structured error messages and other diagnostic information.
28 /// If there is some state in a downstream crate you would like to
29 /// access in the methods of `DiagnosticBuilder` here, consider
30 /// extending `HandlerFlags`, accessed via `self.handler.flags`.
33 pub struct DiagnosticBuilder<'a, G: EmissionGuarantee> {
34 inner: DiagnosticBuilderInner<'a>,
35 _marker: PhantomData<G>,
38 /// This type exists only for `DiagnosticBuilder::forget_guarantee`, because it:
39 /// 1. lacks the `G` parameter and therefore `DiagnosticBuilder<G1>` can be
40 /// converted into `DiagnosticBuilder<G2>` while reusing the `inner` field
41 /// 2. can implement the `Drop` "bomb" instead of `DiagnosticBuilder`, as it
42 /// contains all of the data (`state` + `diagnostic`) of `DiagnosticBuilder`
44 /// The `diagnostic` field is not `Copy` and can't be moved out of whichever
45 /// type implements the `Drop` "bomb", but because of the above two facts, that
46 /// never needs to happen - instead, the whole `inner: DiagnosticBuilderInner`
47 /// can be moved out of a `DiagnosticBuilder` and into another.
50 struct DiagnosticBuilderInner<'a> {
51 state: DiagnosticBuilderState<'a>,
53 /// `Diagnostic` is a large type, and `DiagnosticBuilder` is often used as a
54 /// return value, especially within the frequently-used `PResult` type.
55 /// In theory, return value optimization (RVO) should avoid unnecessary
56 /// copying. In practice, it does not (at the time of writing).
57 diagnostic: Box<Diagnostic>,
61 enum DiagnosticBuilderState<'a> {
62 /// Initial state of a `DiagnosticBuilder`, before `.emit()` or `.cancel()`.
64 /// The `Diagnostic` will be emitted through this `Handler`.
65 Emittable(&'a Handler),
67 /// State of a `DiagnosticBuilder`, after `.emit()` or *during* `.cancel()`.
69 /// The `Diagnostic` will be ignored when calling `.emit()`, and it can be
70 /// assumed that `.emit()` was previously called, to end up in this state.
72 /// While this is also used by `.cancel()`, this state is only observed by
73 /// the `Drop` `impl` of `DiagnosticBuilderInner`, as `.cancel()` takes
74 /// `self` by-value specifically to prevent any attempts to `.emit()`.
76 // FIXME(eddyb) currently this doesn't prevent extending the `Diagnostic`,
77 // despite that being potentially lossy, if important information is added
78 // *after* the original `.emit()` call.
79 AlreadyEmittedOrDuringCancellation,
82 // `DiagnosticBuilderState` should be pointer-sized.
83 rustc_data_structures::static_assert_size!(
84 DiagnosticBuilderState<'_>,
85 std::mem::size_of::<&Handler>()
88 /// Trait for types that `DiagnosticBuilder::emit` can return as a "guarantee"
89 /// (or "proof") token that the emission happened.
90 pub trait EmissionGuarantee: Sized {
91 /// Implementation of `DiagnosticBuilder::emit`, fully controlled by each
92 /// `impl` of `EmissionGuarantee`, to make it impossible to create a value
93 /// of `Self` without actually performing the emission.
95 fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self;
97 /// Creates a new `DiagnosticBuilder` that will return this type of guarantee.
99 fn make_diagnostic_builder(
101 msg: impl Into<DiagnosticMessage>,
102 ) -> DiagnosticBuilder<'_, Self>;
105 /// Private module for sealing the `IsError` helper trait.
106 mod sealed_level_is_error {
109 /// Sealed helper trait for statically checking that a `Level` is an error.
110 pub(crate) trait IsError<const L: Level> {}
112 impl IsError<{ Level::Bug }> for () {}
113 impl IsError<{ Level::DelayedBug }> for () {}
114 impl IsError<{ Level::Fatal }> for () {}
115 // NOTE(eddyb) `Level::Error { lint: true }` is also an error, but lints
116 // don't need error guarantees, as their levels are always dynamic.
117 impl IsError<{ Level::Error { lint: false } }> for () {}
120 impl<'a> DiagnosticBuilder<'a, ErrorGuaranteed> {
121 /// Convenience function for internal use, clients should use one of the
122 /// `struct_*` methods on [`Handler`].
123 pub(crate) fn new_guaranteeing_error<M: Into<DiagnosticMessage>, const L: Level>(
124 handler: &'a Handler,
128 (): sealed_level_is_error::IsError<L>,
131 inner: DiagnosticBuilderInner {
132 state: DiagnosticBuilderState::Emittable(handler),
133 diagnostic: Box::new(Diagnostic::new_with_code(L, None, message)),
135 _marker: PhantomData,
139 /// Discard the guarantee `.emit()` would return, in favor of having the
140 /// type `DiagnosticBuilder<'a, ()>`. This may be necessary whenever there
141 /// is a common codepath handling both errors and warnings.
142 pub fn forget_guarantee(self) -> DiagnosticBuilder<'a, ()> {
143 DiagnosticBuilder { inner: self.inner, _marker: PhantomData }
147 // FIXME(eddyb) make `ErrorGuaranteed` impossible to create outside `.emit()`.
148 impl EmissionGuarantee for ErrorGuaranteed {
149 fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
150 match db.inner.state {
151 // First `.emit()` call, the `&Handler` is still available.
152 DiagnosticBuilderState::Emittable(handler) => {
153 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
155 let guar = handler.emit_diagnostic(&mut db.inner.diagnostic);
157 // Only allow a guarantee if the `level` wasn't switched to a
158 // non-error - the field isn't `pub`, but the whole `Diagnostic`
159 // can be overwritten with a new one, thanks to `DerefMut`.
161 db.inner.diagnostic.is_error(),
162 "emitted non-error ({:?}) diagnostic \
163 from `DiagnosticBuilder<ErrorGuaranteed>`",
164 db.inner.diagnostic.level,
168 // `.emit()` was previously called, disallowed from repeating it,
169 // but can take advantage of the previous `.emit()`'s guarantee
170 // still being applicable (i.e. as a form of idempotency).
171 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {
172 // Only allow a guarantee if the `level` wasn't switched to a
173 // non-error - the field isn't `pub`, but the whole `Diagnostic`
174 // can be overwritten with a new one, thanks to `DerefMut`.
176 db.inner.diagnostic.is_error(),
177 "`DiagnosticBuilder<ErrorGuaranteed>`'s diagnostic \
178 became non-error ({:?}), after original `.emit()`",
179 db.inner.diagnostic.level,
181 ErrorGuaranteed::unchecked_claim_error_was_emitted()
186 fn make_diagnostic_builder(
188 msg: impl Into<DiagnosticMessage>,
189 ) -> DiagnosticBuilder<'_, Self> {
190 DiagnosticBuilder::new_guaranteeing_error::<_, { Level::Error { lint: false } }>(
196 impl<'a> DiagnosticBuilder<'a, ()> {
197 /// Convenience function for internal use, clients should use one of the
198 /// `struct_*` methods on [`Handler`].
199 pub(crate) fn new<M: Into<DiagnosticMessage>>(
200 handler: &'a Handler,
204 let diagnostic = Diagnostic::new_with_code(level, None, message);
205 Self::new_diagnostic(handler, diagnostic)
208 /// Creates a new `DiagnosticBuilder` with an already constructed
210 pub(crate) fn new_diagnostic(handler: &'a Handler, diagnostic: Diagnostic) -> Self {
211 debug!("Created new diagnostic");
213 inner: DiagnosticBuilderInner {
214 state: DiagnosticBuilderState::Emittable(handler),
215 diagnostic: Box::new(diagnostic),
217 _marker: PhantomData,
222 // FIXME(eddyb) should there be a `Option<ErrorGuaranteed>` impl as well?
223 impl EmissionGuarantee for () {
224 fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
225 match db.inner.state {
226 // First `.emit()` call, the `&Handler` is still available.
227 DiagnosticBuilderState::Emittable(handler) => {
228 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
230 handler.emit_diagnostic(&mut db.inner.diagnostic);
232 // `.emit()` was previously called, disallowed from repeating it.
233 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
237 fn make_diagnostic_builder(
239 msg: impl Into<DiagnosticMessage>,
240 ) -> DiagnosticBuilder<'_, Self> {
241 DiagnosticBuilder::new(handler, Level::Warning(None), msg)
245 impl<'a> DiagnosticBuilder<'a, !> {
246 /// Convenience function for internal use, clients should use one of the
247 /// `struct_*` methods on [`Handler`].
248 pub(crate) fn new_fatal(handler: &'a Handler, message: impl Into<DiagnosticMessage>) -> Self {
249 let diagnostic = Diagnostic::new_with_code(Level::Fatal, None, message);
250 Self::new_diagnostic_fatal(handler, diagnostic)
253 /// Creates a new `DiagnosticBuilder` with an already constructed
255 pub(crate) fn new_diagnostic_fatal(handler: &'a Handler, diagnostic: Diagnostic) -> Self {
256 debug!("Created new diagnostic");
258 inner: DiagnosticBuilderInner {
259 state: DiagnosticBuilderState::Emittable(handler),
260 diagnostic: Box::new(diagnostic),
262 _marker: PhantomData,
267 impl EmissionGuarantee for ! {
268 fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
269 match db.inner.state {
270 // First `.emit()` call, the `&Handler` is still available.
271 DiagnosticBuilderState::Emittable(handler) => {
272 db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
274 handler.emit_diagnostic(&mut db.inner.diagnostic);
276 // `.emit()` was previously called, disallowed from repeating it.
277 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
279 // Then fatally error, returning `!`
280 crate::FatalError.raise()
283 fn make_diagnostic_builder(
285 msg: impl Into<DiagnosticMessage>,
286 ) -> DiagnosticBuilder<'_, Self> {
287 DiagnosticBuilder::new_fatal(handler, msg)
291 /// In general, the `DiagnosticBuilder` uses deref to allow access to
292 /// the fields and methods of the embedded `diagnostic` in a
293 /// transparent way. *However,* many of the methods are intended to
294 /// be used in a chained way, and hence ought to return `self`. In
295 /// that case, we can't just naively forward to the method on the
296 /// `diagnostic`, because the return type would be a `&Diagnostic`
297 /// instead of a `&DiagnosticBuilder<'a>`. This `forward!` macro makes
298 /// it easy to declare such methods on the builder.
299 macro_rules! forward {
300 // Forward pattern for &mut self -> &mut Self
303 pub fn $n:ident(&mut self, $($name:ident: $ty:ty),* $(,)?) -> &mut Self
306 #[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")]
307 pub fn $n(&mut self, $($name: $ty),*) -> &mut Self {
308 self.inner.diagnostic.$n($($name),*);
314 impl<G: EmissionGuarantee> Deref for DiagnosticBuilder<'_, G> {
315 type Target = Diagnostic;
317 fn deref(&self) -> &Diagnostic {
318 &self.inner.diagnostic
322 impl<G: EmissionGuarantee> DerefMut for DiagnosticBuilder<'_, G> {
323 fn deref_mut(&mut self) -> &mut Diagnostic {
324 &mut self.inner.diagnostic
328 impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
329 /// Emit the diagnostic.
331 pub fn emit(&mut self) -> G {
332 G::diagnostic_builder_emit_producing_guarantee(self)
335 /// Emit the diagnostic unless `delay` is true,
336 /// in which case the emission will be delayed as a bug.
338 /// See `emit` and `delay_as_bug` for details.
340 pub fn emit_unless(&mut self, delay: bool) -> G {
342 self.downgrade_to_delayed_bug();
347 /// Cancel the diagnostic (a structured diagnostic must either be emitted or
348 /// cancelled or it will panic when dropped).
350 /// This method takes `self` by-value to disallow calling `.emit()` on it,
351 /// which may be expected to *guarantee* the emission of an error, either
352 /// at the time of the call, or through a prior `.emit()` call.
353 pub fn cancel(mut self) {
354 self.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
358 /// Stashes diagnostic for possible later improvement in a different,
359 /// later stage of the compiler. The diagnostic can be accessed with
360 /// the provided `span` and `key` through [`Handler::steal_diagnostic()`].
362 /// As with `buffer`, this is unless the handler has disabled such buffering.
363 pub fn stash(self, span: Span, key: StashKey) {
364 if let Some((diag, handler)) = self.into_diagnostic() {
365 handler.stash_diagnostic(span, key, diag);
369 /// Converts the builder to a `Diagnostic` for later emission,
370 /// unless handler has disabled such buffering, or `.emit()` was called.
371 pub fn into_diagnostic(mut self) -> Option<(Diagnostic, &'a Handler)> {
372 let handler = match self.inner.state {
373 // No `.emit()` calls, the `&Handler` is still available.
374 DiagnosticBuilderState::Emittable(handler) => handler,
375 // `.emit()` was previously called, nothing we can do.
376 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {
381 if handler.flags.dont_buffer_diagnostics || handler.flags.treat_err_as_bug.is_some() {
386 // Take the `Diagnostic` by replacing it with a dummy.
387 let dummy = Diagnostic::new(Level::Allow, DiagnosticMessage::Str("".to_string()));
388 let diagnostic = std::mem::replace(&mut *self.inner.diagnostic, dummy);
390 // Disable the ICE on `Drop`.
393 // Logging here is useful to help track down where in logs an error was
395 debug!("buffer: diagnostic={:?}", diagnostic);
397 Some((diagnostic, handler))
400 /// Buffers the diagnostic for later emission,
401 /// unless handler has disabled such buffering.
402 pub fn buffer(self, buffered_diagnostics: &mut Vec<Diagnostic>) {
403 buffered_diagnostics.extend(self.into_diagnostic().map(|(diag, _)| diag));
406 /// Delay emission of this diagnostic as a bug.
408 /// This can be useful in contexts where an error indicates a bug but
409 /// typically this only happens when other compilation errors have already
410 /// happened. In those cases this can be used to defer emission of this
411 /// diagnostic as a bug in the compiler only if no other errors have been
414 /// In the meantime, though, callsites are required to deal with the "bug"
415 /// locally in whichever way makes the most sense.
417 pub fn delay_as_bug(&mut self) {
418 self.downgrade_to_delayed_bug();
424 pub fn downgrade_to_delayed_bug(&mut self,) -> &mut Self
428 /// Appends a labeled span to the diagnostic.
430 /// Labels are used to convey additional context for the diagnostic's primary span. They will
431 /// be shown together with the original diagnostic's span, *not* with spans added by
432 /// `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because
433 /// the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed
436 /// Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when
437 /// the diagnostic was constructed. However, the label span is *not* considered a
438 /// ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is
440 pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self);
443 /// Labels all the given spans with the provided label.
444 /// See [`Diagnostic::span_label()`] for more information.
447 spans: impl IntoIterator<Item = Span>,
448 label: impl AsRef<str>,
451 forward!(pub fn note_expected_found(
453 expected_label: &dyn fmt::Display,
454 expected: DiagnosticStyledString,
455 found_label: &dyn fmt::Display,
456 found: DiagnosticStyledString,
459 forward!(pub fn note_expected_found_extra(
461 expected_label: &dyn fmt::Display,
462 expected: DiagnosticStyledString,
463 found_label: &dyn fmt::Display,
464 found: DiagnosticStyledString,
465 expected_extra: &dyn fmt::Display,
466 found_extra: &dyn fmt::Display,
469 forward!(pub fn note_unsuccessful_coercion(
471 expected: DiagnosticStyledString,
472 found: DiagnosticStyledString,
475 forward!(pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
476 forward!(pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
477 forward!(pub fn span_note(
479 sp: impl Into<MultiSpan>,
480 msg: impl Into<SubdiagnosticMessage>,
482 forward!(pub fn span_note_once(
484 sp: impl Into<MultiSpan>,
485 msg: impl Into<SubdiagnosticMessage>,
487 forward!(pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
488 forward!(pub fn span_warn(
490 sp: impl Into<MultiSpan>,
491 msg: impl Into<SubdiagnosticMessage>,
493 forward!(pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
494 forward!(pub fn span_help(
496 sp: impl Into<MultiSpan>,
497 msg: impl Into<SubdiagnosticMessage>,
499 forward!(pub fn help_use_latest_edition(&mut self,) -> &mut Self);
500 forward!(pub fn set_is_lint(&mut self,) -> &mut Self);
502 forward!(pub fn disable_suggestions(&mut self,) -> &mut Self);
503 forward!(pub fn clear_suggestions(&mut self,) -> &mut Self);
505 forward!(pub fn multipart_suggestion(
507 msg: impl Into<SubdiagnosticMessage>,
508 suggestion: Vec<(Span, String)>,
509 applicability: Applicability,
511 forward!(pub fn multipart_suggestion_verbose(
513 msg: impl Into<SubdiagnosticMessage>,
514 suggestion: Vec<(Span, String)>,
515 applicability: Applicability,
517 forward!(pub fn tool_only_multipart_suggestion(
519 msg: impl Into<SubdiagnosticMessage>,
520 suggestion: Vec<(Span, String)>,
521 applicability: Applicability,
523 forward!(pub fn span_suggestion(
526 msg: impl Into<SubdiagnosticMessage>,
527 suggestion: impl ToString,
528 applicability: Applicability,
530 forward!(pub fn span_suggestions(
533 msg: impl Into<SubdiagnosticMessage>,
534 suggestions: impl Iterator<Item = String>,
535 applicability: Applicability,
537 forward!(pub fn multipart_suggestions(
539 msg: impl Into<SubdiagnosticMessage>,
540 suggestions: impl Iterator<Item = Vec<(Span, String)>>,
541 applicability: Applicability,
543 forward!(pub fn span_suggestion_short(
546 msg: impl Into<SubdiagnosticMessage>,
547 suggestion: impl ToString,
548 applicability: Applicability,
550 forward!(pub fn span_suggestion_verbose(
553 msg: impl Into<SubdiagnosticMessage>,
554 suggestion: impl ToString,
555 applicability: Applicability,
557 forward!(pub fn span_suggestion_hidden(
560 msg: impl Into<SubdiagnosticMessage>,
561 suggestion: impl ToString,
562 applicability: Applicability,
564 forward!(pub fn tool_only_span_suggestion(
567 msg: impl Into<SubdiagnosticMessage>,
568 suggestion: impl ToString,
569 applicability: Applicability,
572 forward!(pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self);
573 forward!(pub fn set_span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self);
574 forward!(pub fn code(&mut self, s: DiagnosticId) -> &mut Self);
575 forward!(pub fn set_arg(
577 name: impl Into<Cow<'static, str>>,
578 arg: impl IntoDiagnosticArg,
581 forward!(pub fn subdiagnostic(
583 subdiagnostic: impl crate::AddToDiagnostic
587 impl<G: EmissionGuarantee> Debug for DiagnosticBuilder<'_, G> {
588 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
589 self.inner.diagnostic.fmt(f)
593 /// Destructor bomb - a `DiagnosticBuilder` must be either emitted or cancelled
594 /// or we emit a bug.
595 impl Drop for DiagnosticBuilderInner<'_> {
598 // No `.emit()` or `.cancel()` calls.
599 DiagnosticBuilderState::Emittable(handler) => {
601 handler.emit_diagnostic(&mut Diagnostic::new(
603 DiagnosticMessage::Str(
604 "the following error was constructed but not emitted".to_string(),
607 handler.emit_diagnostic(&mut self.diagnostic);
608 panic!("error was constructed but not emitted");
611 // `.emit()` was previously called, or maybe we're during `.cancel()`.
612 DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
618 macro_rules! struct_span_err {
619 ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
620 $session.struct_span_err_with_code(
622 &format!($($message)*),
623 $crate::error_code!($code),
629 macro_rules! error_code {
630 ($code:ident) => {{ $crate::DiagnosticId::Error(stringify!($code).to_owned()) }};
633 /// Wrapper around a `DiagnosticBuilder` for creating lints.
634 pub struct LintDiagnosticBuilder<'a, G: EmissionGuarantee>(DiagnosticBuilder<'a, G>);
636 impl<'a, G: EmissionGuarantee> LintDiagnosticBuilder<'a, G> {
637 #[rustc_lint_diagnostics]
638 /// Return the inner `DiagnosticBuilder`, first setting the primary message to `msg`.
639 pub fn build(mut self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'a, G> {
640 self.0.set_primary_message(msg);
641 self.0.set_is_lint();
645 /// Create a `LintDiagnosticBuilder` from some existing `DiagnosticBuilder`.
646 pub fn new(err: DiagnosticBuilder<'a, G>) -> LintDiagnosticBuilder<'a, G> {
647 LintDiagnosticBuilder(err)
651 impl<'a> LintDiagnosticBuilder<'a, ErrorGuaranteed> {
652 pub fn forget_guarantee(self) -> LintDiagnosticBuilder<'a, ()> {
653 LintDiagnosticBuilder(self.0.forget_guarantee())