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);
464 forward
!(pub fn clear_suggestions(&mut self,) -> &mut Self);
466 forward
!(pub fn multipart_suggestion(
468 msg
: impl Into
<SubdiagnosticMessage
>,
469 suggestion
: Vec
<(Span
, String
)>,
470 applicability
: Applicability
,
472 forward
!(pub fn multipart_suggestion_verbose(
474 msg
: impl Into
<SubdiagnosticMessage
>,
475 suggestion
: Vec
<(Span
, String
)>,
476 applicability
: Applicability
,
478 forward
!(pub fn tool_only_multipart_suggestion(
480 msg
: impl Into
<SubdiagnosticMessage
>,
481 suggestion
: Vec
<(Span
, String
)>,
482 applicability
: Applicability
,
484 forward
!(pub fn span_suggestion(
487 msg
: impl Into
<SubdiagnosticMessage
>,
488 suggestion
: impl ToString
,
489 applicability
: Applicability
,
491 forward
!(pub fn span_suggestions(
494 msg
: impl Into
<SubdiagnosticMessage
>,
495 suggestions
: impl Iterator
<Item
= String
>,
496 applicability
: Applicability
,
498 forward
!(pub fn multipart_suggestions(
500 msg
: impl Into
<SubdiagnosticMessage
>,
501 suggestions
: impl Iterator
<Item
= Vec
<(Span
, String
)>>,
502 applicability
: Applicability
,
504 forward
!(pub fn span_suggestion_short(
507 msg
: impl Into
<SubdiagnosticMessage
>,
508 suggestion
: impl ToString
,
509 applicability
: Applicability
,
511 forward
!(pub fn span_suggestion_verbose(
514 msg
: impl Into
<SubdiagnosticMessage
>,
515 suggestion
: impl ToString
,
516 applicability
: Applicability
,
518 forward
!(pub fn span_suggestion_hidden(
521 msg
: impl Into
<SubdiagnosticMessage
>,
522 suggestion
: impl ToString
,
523 applicability
: Applicability
,
525 forward
!(pub fn tool_only_span_suggestion(
528 msg
: impl Into
<SubdiagnosticMessage
>,
529 suggestion
: impl ToString
,
530 applicability
: Applicability
,
533 forward
!(pub fn set_primary_message(&mut self, msg
: impl Into
<DiagnosticMessage
>) -> &mut Self);
534 forward
!(pub fn set_span(&mut self, sp
: impl Into
<MultiSpan
>) -> &mut Self);
535 forward
!(pub fn code(&mut self, s
: DiagnosticId
) -> &mut Self);
536 forward
!(pub fn set_arg(
538 name
: impl Into
<Cow
<'
static, str>>,
539 arg
: impl IntoDiagnosticArg
,
542 forward
!(pub fn subdiagnostic(
544 subdiagnostic
: impl crate::AddSubdiagnostic
548 impl<G
: EmissionGuarantee
> Debug
for DiagnosticBuilder
<'_
, G
> {
549 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
550 self.inner
.diagnostic
.fmt(f
)
554 /// Destructor bomb - a `DiagnosticBuilder` must be either emitted or cancelled
555 /// or we emit a bug.
556 impl Drop
for DiagnosticBuilderInner
<'_
> {
559 // No `.emit()` or `.cancel()` calls.
560 DiagnosticBuilderState
::Emittable(handler
) => {
562 handler
.emit_diagnostic(&mut Diagnostic
::new(
564 DiagnosticMessage
::Str(
565 "the following error was constructed but not emitted".to_string(),
568 handler
.emit_diagnostic(&mut self.diagnostic
);
572 // `.emit()` was previously called, or maybe we're during `.cancel()`.
573 DiagnosticBuilderState
::AlreadyEmittedOrDuringCancellation
=> {}
579 macro_rules
! struct_span_err
{
580 ($session
:expr
, $span
:expr
, $code
:ident
, $
($message
:tt
)*) => ({
581 $session
.struct_span_err_with_code(
583 &format
!($
($message
)*),
584 $
crate::error_code
!($code
),
590 macro_rules
! error_code
{
591 ($code
:ident
) => {{ $crate::DiagnosticId::Error(stringify!($code).to_owned()) }
};
594 /// Wrapper around a `DiagnosticBuilder` for creating lints.
595 pub struct LintDiagnosticBuilder
<'a
, G
: EmissionGuarantee
>(DiagnosticBuilder
<'a
, G
>);
597 impl<'a
, G
: EmissionGuarantee
> LintDiagnosticBuilder
<'a
, G
> {
598 #[rustc_lint_diagnostics]
599 /// Return the inner `DiagnosticBuilder`, first setting the primary message to `msg`.
600 pub fn build(mut self, msg
: impl Into
<DiagnosticMessage
>) -> DiagnosticBuilder
<'a
, G
> {
601 self.0.set_primary_message(msg
);
602 self.0.set_is_lint();
606 /// Create a `LintDiagnosticBuilder` from some existing `DiagnosticBuilder`.
607 pub fn new(err
: DiagnosticBuilder
<'a
, G
>) -> LintDiagnosticBuilder
<'a
, G
> {
608 LintDiagnosticBuilder(err
)
612 impl<'a
> LintDiagnosticBuilder
<'a
, ErrorGuaranteed
> {
613 pub fn forget_guarantee(self) -> LintDiagnosticBuilder
<'a
, ()> {
614 LintDiagnosticBuilder(self.0.forget_guarantee
())