1 use crate::{Diagnostic, DiagnosticId, DiagnosticStyledString}
;
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
::ops
::{Deref, DerefMut}
;
8 use std
::thread
::panicking
;
11 /// Used for emitting structured error messages and other diagnostic information.
13 /// If there is some state in a downstream crate you would like to
14 /// access in the methods of `DiagnosticBuilder` here, consider
15 /// extending `HandlerFlags`, accessed via `self.handler.flags`.
18 pub struct DiagnosticBuilder
<'a
> {
21 /// `Diagnostic` is a large type, and `DiagnosticBuilder` is often used as a
22 /// return value, especially within the frequently-used `PResult` type.
23 /// In theory, return value optimization (RVO) should avoid unnecessary
24 /// copying. In practice, it does not (at the time of writing).
25 diagnostic
: Box
<Diagnostic
>,
28 /// In general, the `DiagnosticBuilder` uses deref to allow access to
29 /// the fields and methods of the embedded `diagnostic` in a
30 /// transparent way. *However,* many of the methods are intended to
31 /// be used in a chained way, and hence ought to return `self`. In
32 /// that case, we can't just naively forward to the method on the
33 /// `diagnostic`, because the return type would be a `&Diagnostic`
34 /// instead of a `&DiagnosticBuilder<'a>`. This `forward!` macro makes
35 /// it easy to declare such methods on the builder.
36 macro_rules
! forward
{
37 // Forward pattern for &self -> &Self
40 pub fn $n
:ident(&self, $
($name
:ident
: $ty
:ty
),* $
(,)?
) -> &Self
43 #[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")]
44 pub fn $
n(&self, $
($name
: $ty
),*) -> &Self {
45 self.diagnostic
.$
n($
($name
),*);
50 // Forward pattern for &mut self -> &mut Self
53 pub fn $n
:ident(&mut self, $
($name
:ident
: $ty
:ty
),* $
(,)?
) -> &mut Self
56 #[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")]
57 pub fn $
n(&mut self, $
($name
: $ty
),*) -> &mut Self {
58 self.diagnostic
.$
n($
($name
),*);
63 // Forward pattern for &mut self -> &mut Self, with generic parameters.
66 pub fn $n
:ident
<$
($generic
:ident
: $bound
:path
),*>(
68 $
($name
:ident
: $ty
:ty
),*
73 #[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")]
74 pub fn $n
<$
($generic
: $bound
),*>(&mut self, $
($name
: $ty
),*) -> &mut Self {
75 self.diagnostic
.$
n($
($name
),*);
81 impl<'a
> Deref
for DiagnosticBuilder
<'a
> {
82 type Target
= Diagnostic
;
84 fn deref(&self) -> &Diagnostic
{
89 impl<'a
> DerefMut
for DiagnosticBuilder
<'a
> {
90 fn deref_mut(&mut self) -> &mut Diagnostic
{
95 impl<'a
> DiagnosticBuilder
<'a
> {
96 /// Emit the diagnostic.
97 pub fn emit(&mut self) {
98 self.handler
.emit_diagnostic(&self);
102 /// Emit the diagnostic unless `delay` is true,
103 /// in which case the emission will be delayed as a bug.
105 /// See `emit` and `delay_as_bug` for details.
106 pub fn emit_unless(&mut self, delay
: bool
) {
114 /// Stashes diagnostic for possible later improvement in a different,
115 /// later stage of the compiler. The diagnostic can be accessed with
116 /// the provided `span` and `key` through [`Handler::steal_diagnostic()`].
118 /// As with `buffer`, this is unless the handler has disabled such buffering.
119 pub fn stash(self, span
: Span
, key
: StashKey
) {
120 if let Some((diag
, handler
)) = self.into_diagnostic() {
121 handler
.stash_diagnostic(span
, key
, diag
);
125 /// Converts the builder to a `Diagnostic` for later emission,
126 /// unless handler has disabled such buffering.
127 pub fn into_diagnostic(mut self) -> Option
<(Diagnostic
, &'a Handler
)> {
128 if self.handler
.flags
.dont_buffer_diagnostics
129 || self.handler
.flags
.treat_err_as_bug
.is_some()
135 let handler
= self.handler
;
137 // We must use `Level::Cancelled` for `dummy` to avoid an ICE about an
138 // unused diagnostic.
139 let dummy
= Diagnostic
::new(Level
::Cancelled
, "");
140 let diagnostic
= std
::mem
::replace(&mut *self.diagnostic
, dummy
);
142 // Logging here is useful to help track down where in logs an error was
144 debug
!("buffer: diagnostic={:?}", diagnostic
);
146 Some((diagnostic
, handler
))
149 /// Buffers the diagnostic for later emission,
150 /// unless handler has disabled such buffering.
151 pub fn buffer(self, buffered_diagnostics
: &mut Vec
<Diagnostic
>) {
152 buffered_diagnostics
.extend(self.into_diagnostic().map(|(diag
, _
)| diag
));
155 /// Delay emission of this diagnostic as a bug.
157 /// This can be useful in contexts where an error indicates a bug but
158 /// typically this only happens when other compilation errors have already
159 /// happened. In those cases this can be used to defer emission of this
160 /// diagnostic as a bug in the compiler only if no other errors have been
163 /// In the meantime, though, callsites are required to deal with the "bug"
164 /// locally in whichever way makes the most sense.
165 pub fn delay_as_bug(&mut self) {
166 self.level
= Level
::Bug
;
167 self.handler
.delay_as_bug((*self.diagnostic
).clone());
171 /// Appends a labeled span to the diagnostic.
173 /// Labels are used to convey additional context for the diagnostic's primary span. They will
174 /// be shown together with the original diagnostic's span, *not* with spans added by
175 /// `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because
176 /// the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed
179 /// Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when
180 /// the diagnostic was constructed. However, the label span is *not* considered a
181 /// ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is
183 pub fn span_label(&mut self, span
: Span
, label
: impl Into
<String
>) -> &mut Self {
184 self.diagnostic
.span_label(span
, label
);
188 /// Labels all the given spans with the provided label.
189 /// See [`Diagnostic::span_label()`] for more information.
192 spans
: impl IntoIterator
<Item
= Span
>,
193 label
: impl AsRef
<str>,
195 let label
= label
.as_ref();
197 self.diagnostic
.span_label(span
, label
);
202 forward
!(pub fn note_expected_found(
204 expected_label
: &dyn fmt
::Display
,
205 expected
: DiagnosticStyledString
,
206 found_label
: &dyn fmt
::Display
,
207 found
: DiagnosticStyledString
,
210 forward
!(pub fn note_expected_found_extra(
212 expected_label
: &dyn fmt
::Display
,
213 expected
: DiagnosticStyledString
,
214 found_label
: &dyn fmt
::Display
,
215 found
: DiagnosticStyledString
,
216 expected_extra
: &dyn fmt
::Display
,
217 found_extra
: &dyn fmt
::Display
,
220 forward
!(pub fn note_unsuccessful_coercion(
222 expected
: DiagnosticStyledString
,
223 found
: DiagnosticStyledString
,
226 forward
!(pub fn note(&mut self, msg
: &str) -> &mut Self);
227 forward
!(pub fn span_note
<S
: Into
<MultiSpan
>>(
232 forward
!(pub fn warn(&mut self, msg
: &str) -> &mut Self);
233 forward
!(pub fn span_warn
<S
: Into
<MultiSpan
>>(&mut self, sp
: S
, msg
: &str) -> &mut Self);
234 forward
!(pub fn help(&mut self, msg
: &str) -> &mut Self);
235 forward
!(pub fn span_help
<S
: Into
<MultiSpan
>>(
240 forward
!(pub fn set_is_lint(&mut self,) -> &mut Self);
242 forward
!(pub fn disable_suggestions(&mut self,) -> &mut Self);
244 forward
!(pub fn multipart_suggestion(
247 suggestion
: Vec
<(Span
, String
)>,
248 applicability
: Applicability
,
250 forward
!(pub fn multipart_suggestion_verbose(
253 suggestion
: Vec
<(Span
, String
)>,
254 applicability
: Applicability
,
256 forward
!(pub fn tool_only_multipart_suggestion(
259 suggestion
: Vec
<(Span
, String
)>,
260 applicability
: Applicability
,
262 forward
!(pub fn span_suggestion(
267 applicability
: Applicability
,
269 forward
!(pub fn span_suggestions(
273 suggestions
: impl Iterator
<Item
= String
>,
274 applicability
: Applicability
,
276 forward
!(pub fn multipart_suggestions(
279 suggestions
: impl Iterator
<Item
= Vec
<(Span
, String
)>>,
280 applicability
: Applicability
,
282 forward
!(pub fn span_suggestion_short(
287 applicability
: Applicability
,
289 forward
!(pub fn span_suggestion_verbose(
294 applicability
: Applicability
,
296 forward
!(pub fn span_suggestion_hidden(
301 applicability
: Applicability
,
303 forward
!(pub fn tool_only_span_suggestion(
308 applicability
: Applicability
,
311 forward
!(pub fn set_primary_message
<M
: Into
<String
>>(&mut self, msg
: M
) -> &mut Self);
312 forward
!(pub fn set_span
<S
: Into
<MultiSpan
>>(&mut self, sp
: S
) -> &mut Self);
313 forward
!(pub fn code(&mut self, s
: DiagnosticId
) -> &mut Self);
315 /// Convenience function for internal use, clients should use one of the
316 /// `struct_*` methods on [`Handler`].
317 crate fn new(handler
: &'a Handler
, level
: Level
, message
: &str) -> DiagnosticBuilder
<'a
> {
318 DiagnosticBuilder
::new_with_code(handler
, level
, None
, message
)
321 /// Convenience function for internal use, clients should use one of the
322 /// `struct_*` methods on [`Handler`].
323 crate fn new_with_code(
324 handler
: &'a Handler
,
326 code
: Option
<DiagnosticId
>,
328 ) -> DiagnosticBuilder
<'a
> {
329 let diagnostic
= Diagnostic
::new_with_code(level
, code
, message
);
330 DiagnosticBuilder
::new_diagnostic(handler
, diagnostic
)
333 /// Creates a new `DiagnosticBuilder` with an already constructed
335 crate fn new_diagnostic(handler
: &'a Handler
, diagnostic
: Diagnostic
) -> DiagnosticBuilder
<'a
> {
336 debug
!("Created new diagnostic");
337 DiagnosticBuilder { handler, diagnostic: Box::new(diagnostic) }
341 impl<'a
> Debug
for DiagnosticBuilder
<'a
> {
342 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
343 self.diagnostic
.fmt(f
)
347 /// Destructor bomb - a `DiagnosticBuilder` must be either emitted or canceled
348 /// or we emit a bug.
349 impl<'a
> Drop
for DiagnosticBuilder
<'a
> {
351 if !panicking() && !self.cancelled() {
352 let mut db
= DiagnosticBuilder
::new(
355 "the following error was constructed but not emitted",
365 macro_rules
! struct_span_err
{
366 ($session
:expr
, $span
:expr
, $code
:ident
, $
($message
:tt
)*) => ({
367 $session
.struct_span_err_with_code(
369 &format
!($
($message
)*),
370 $
crate::error_code
!($code
),
376 macro_rules
! error_code
{
377 ($code
:ident
) => {{ $crate::DiagnosticId::Error(stringify!($code).to_owned()) }
};