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
>(Box
<DiagnosticBuilderInner
<'a
>>);
20 /// This is a large type, and often used as a return value, especially within
21 /// the frequently-used `PResult` type. In theory, return value optimization
22 /// (RVO) should avoid unnecessary copying. In practice, it does not (at the
23 /// time of writing). The split between `DiagnosticBuilder` and
24 /// `DiagnosticBuilderInner` exists to avoid many `memcpy` calls.
27 struct DiagnosticBuilderInner
<'a
> {
29 diagnostic
: Diagnostic
,
30 allow_suggestions
: bool
,
33 /// In general, the `DiagnosticBuilder` uses deref to allow access to
34 /// the fields and methods of the embedded `diagnostic` in a
35 /// transparent way. *However,* many of the methods are intended to
36 /// be used in a chained way, and hence ought to return `self`. In
37 /// that case, we can't just naively forward to the method on the
38 /// `diagnostic`, because the return type would be a `&Diagnostic`
39 /// instead of a `&DiagnosticBuilder<'a>`. This `forward!` macro makes
40 /// it easy to declare such methods on the builder.
41 macro_rules
! forward
{
42 // Forward pattern for &self -> &Self
45 pub fn $n
:ident(&self, $
($name
:ident
: $ty
:ty
),* $
(,)?
) -> &Self
48 #[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")]
49 pub fn $
n(&self, $
($name
: $ty
),*) -> &Self {
50 self.diagnostic
.$
n($
($name
),*);
55 // Forward pattern for &mut self -> &mut Self
58 pub fn $n
:ident(&mut self, $
($name
:ident
: $ty
:ty
),* $
(,)?
) -> &mut Self
61 #[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")]
62 pub fn $
n(&mut self, $
($name
: $ty
),*) -> &mut Self {
63 self.0.diagnostic
.$
n($
($name
),*);
68 // Forward pattern for &mut self -> &mut Self, with generic parameters.
71 pub fn $n
:ident
<$
($generic
:ident
: $bound
:path
),*>(
73 $
($name
:ident
: $ty
:ty
),*
78 #[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")]
79 pub fn $n
<$
($generic
: $bound
),*>(&mut self, $
($name
: $ty
),*) -> &mut Self {
80 self.0.diagnostic
.$
n($
($name
),*);
86 impl<'a
> Deref
for DiagnosticBuilder
<'a
> {
87 type Target
= Diagnostic
;
89 fn deref(&self) -> &Diagnostic
{
94 impl<'a
> DerefMut
for DiagnosticBuilder
<'a
> {
95 fn deref_mut(&mut self) -> &mut Diagnostic
{
96 &mut self.0.diagnostic
100 impl<'a
> DiagnosticBuilder
<'a
> {
101 /// Emit the diagnostic.
102 pub fn emit(&mut self) {
103 self.0.handler
.emit_diagnostic(&self);
107 /// Emit the diagnostic unless `delay` is true,
108 /// in which case the emission will be delayed as a bug.
110 /// See `emit` and `delay_as_bug` for details.
111 pub fn emit_unless(&mut self, delay
: bool
) {
119 /// Stashes diagnostic for possible later improvement in a different,
120 /// later stage of the compiler. The diagnostic can be accessed with
121 /// the provided `span` and `key` through [`Handler::steal_diagnostic()`].
123 /// As with `buffer`, this is unless the handler has disabled such buffering.
124 pub fn stash(self, span
: Span
, key
: StashKey
) {
125 if let Some((diag
, handler
)) = self.into_diagnostic() {
126 handler
.stash_diagnostic(span
, key
, diag
);
130 /// Converts the builder to a `Diagnostic` for later emission,
131 /// unless handler has disabled such buffering.
132 pub fn into_diagnostic(mut self) -> Option
<(Diagnostic
, &'a Handler
)> {
133 if self.0.handler
.flags
.dont_buffer_diagnostics
134 || self.0.handler
.flags
.treat_err_as_bug
.is_some()
140 let handler
= self.0.handler
;
142 // We must use `Level::Cancelled` for `dummy` to avoid an ICE about an
143 // unused diagnostic.
144 let dummy
= Diagnostic
::new(Level
::Cancelled
, "");
145 let diagnostic
= std
::mem
::replace(&mut self.0.diagnostic
, dummy
);
147 // Logging here is useful to help track down where in logs an error was
149 debug
!("buffer: diagnostic={:?}", diagnostic
);
151 Some((diagnostic
, handler
))
154 /// Buffers the diagnostic for later emission,
155 /// unless handler has disabled such buffering.
156 pub fn buffer(self, buffered_diagnostics
: &mut Vec
<Diagnostic
>) {
157 buffered_diagnostics
.extend(self.into_diagnostic().map(|(diag
, _
)| diag
));
160 /// Delay emission of this diagnostic as a bug.
162 /// This can be useful in contexts where an error indicates a bug but
163 /// typically this only happens when other compilation errors have already
164 /// happened. In those cases this can be used to defer emission of this
165 /// diagnostic as a bug in the compiler only if no other errors have been
168 /// In the meantime, though, callsites are required to deal with the "bug"
169 /// locally in whichever way makes the most sense.
170 pub fn delay_as_bug(&mut self) {
171 self.level
= Level
::Bug
;
172 self.0.handler
.delay_as_bug(self.0.diagnostic
.clone());
176 /// Appends a labeled span to the diagnostic.
178 /// Labels are used to convey additional context for the diagnostic's primary span. They will
179 /// be shown together with the original diagnostic's span, *not* with spans added by
180 /// `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because
181 /// the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed
184 /// Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when
185 /// the diagnostic was constructed. However, the label span is *not* considered a
186 /// ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is
188 pub fn span_label(&mut self, span
: Span
, label
: impl Into
<String
>) -> &mut Self {
189 self.0.diagnostic
.span_label(span
, label
);
193 /// Labels all the given spans with the provided label.
194 /// See [`Diagnostic::span_label()`] for more information.
197 spans
: impl IntoIterator
<Item
= Span
>,
198 label
: impl AsRef
<str>,
200 let label
= label
.as_ref();
202 self.0.diagnostic
.span_label(span
, label
);
207 forward
!(pub fn note_expected_found(
209 expected_label
: &dyn fmt
::Display
,
210 expected
: DiagnosticStyledString
,
211 found_label
: &dyn fmt
::Display
,
212 found
: DiagnosticStyledString
,
215 forward
!(pub fn note_expected_found_extra(
217 expected_label
: &dyn fmt
::Display
,
218 expected
: DiagnosticStyledString
,
219 found_label
: &dyn fmt
::Display
,
220 found
: DiagnosticStyledString
,
221 expected_extra
: &dyn fmt
::Display
,
222 found_extra
: &dyn fmt
::Display
,
225 forward
!(pub fn note_unsuccessful_coercion(
227 expected
: DiagnosticStyledString
,
228 found
: DiagnosticStyledString
,
231 forward
!(pub fn note(&mut self, msg
: &str) -> &mut Self);
232 forward
!(pub fn span_note
<S
: Into
<MultiSpan
>>(
237 forward
!(pub fn warn(&mut self, msg
: &str) -> &mut Self);
238 forward
!(pub fn span_warn
<S
: Into
<MultiSpan
>>(&mut self, sp
: S
, msg
: &str) -> &mut Self);
239 forward
!(pub fn help(&mut self, msg
: &str) -> &mut Self);
240 forward
!(pub fn span_help
<S
: Into
<MultiSpan
>>(
246 /// See [`Diagnostic::multipart_suggestion()`].
247 pub fn multipart_suggestion(
250 suggestion
: Vec
<(Span
, String
)>,
251 applicability
: Applicability
,
253 if !self.0.allow_suggestions
{
256 self.0.diagnostic
.multipart_suggestion(msg
, suggestion
, applicability
);
260 /// See [`Diagnostic::tool_only_multipart_suggestion()`].
261 pub fn tool_only_multipart_suggestion(
264 suggestion
: Vec
<(Span
, String
)>,
265 applicability
: Applicability
,
267 if !self.0.allow_suggestions
{
270 self.0.diagnostic
.tool_only_multipart_suggestion(msg
, suggestion
, applicability
);
274 /// See [`Diagnostic::span_suggestion()`].
275 pub fn span_suggestion(
280 applicability
: Applicability
,
282 if !self.0.allow_suggestions
{
285 self.0.diagnostic
.span_suggestion(sp
, msg
, suggestion
, applicability
);
289 /// See [`Diagnostic::span_suggestions()`].
290 pub fn span_suggestions(
294 suggestions
: impl Iterator
<Item
= String
>,
295 applicability
: Applicability
,
297 if !self.0.allow_suggestions
{
300 self.0.diagnostic
.span_suggestions(sp
, msg
, suggestions
, applicability
);
304 /// See [`Diagnostic::multipart_suggestions()`].
305 pub fn multipart_suggestions(
308 suggestions
: impl Iterator
<Item
= Vec
<(Span
, String
)>>,
309 applicability
: Applicability
,
311 if !self.0.allow_suggestions
{
314 self.0.diagnostic
.multipart_suggestions(msg
, suggestions
, applicability
);
318 /// See [`Diagnostic::span_suggestion_short()`].
319 pub fn span_suggestion_short(
324 applicability
: Applicability
,
326 if !self.0.allow_suggestions
{
329 self.0.diagnostic
.span_suggestion_short(sp
, msg
, suggestion
, applicability
);
333 /// See [`Diagnostic::span_suggestion_verbose()`].
334 pub fn span_suggestion_verbose(
339 applicability
: Applicability
,
341 if !self.0.allow_suggestions
{
344 self.0.diagnostic
.span_suggestion_verbose(sp
, msg
, suggestion
, applicability
);
348 /// See [`Diagnostic::span_suggestion_hidden()`].
349 pub fn span_suggestion_hidden(
354 applicability
: Applicability
,
356 if !self.0.allow_suggestions
{
359 self.0.diagnostic
.span_suggestion_hidden(sp
, msg
, suggestion
, applicability
);
363 /// See [`Diagnostic::tool_only_span_suggestion()`] for more information.
364 pub fn tool_only_span_suggestion(
369 applicability
: Applicability
,
371 if !self.0.allow_suggestions
{
374 self.0.diagnostic
.tool_only_span_suggestion(sp
, msg
, suggestion
, applicability
);
378 forward
!(pub fn set_primary_message
<M
: Into
<String
>>(&mut self, msg
: M
) -> &mut Self);
379 forward
!(pub fn set_span
<S
: Into
<MultiSpan
>>(&mut self, sp
: S
) -> &mut Self);
380 forward
!(pub fn code(&mut self, s
: DiagnosticId
) -> &mut Self);
382 /// Allow attaching suggestions this diagnostic.
383 /// If this is set to `false`, then any suggestions attached with the `span_suggestion_*`
384 /// methods after this is set to `false` will be ignored.
385 pub fn allow_suggestions(&mut self, allow
: bool
) -> &mut Self {
386 self.0.allow_suggestions
= allow
;
390 /// Convenience function for internal use, clients should use one of the
391 /// `struct_*` methods on [`Handler`].
392 crate fn new(handler
: &'a Handler
, level
: Level
, message
: &str) -> DiagnosticBuilder
<'a
> {
393 DiagnosticBuilder
::new_with_code(handler
, level
, None
, message
)
396 /// Convenience function for internal use, clients should use one of the
397 /// `struct_*` methods on [`Handler`].
398 crate fn new_with_code(
399 handler
: &'a Handler
,
401 code
: Option
<DiagnosticId
>,
403 ) -> DiagnosticBuilder
<'a
> {
404 let diagnostic
= Diagnostic
::new_with_code(level
, code
, message
);
405 DiagnosticBuilder
::new_diagnostic(handler
, diagnostic
)
408 /// Creates a new `DiagnosticBuilder` with an already constructed
410 crate fn new_diagnostic(handler
: &'a Handler
, diagnostic
: Diagnostic
) -> DiagnosticBuilder
<'a
> {
411 debug
!("Created new diagnostic");
412 DiagnosticBuilder(Box
::new(DiagnosticBuilderInner
{
415 allow_suggestions
: true,
420 impl<'a
> Debug
for DiagnosticBuilder
<'a
> {
421 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
422 self.0.diagnostic
.fmt(f
)
426 /// Destructor bomb - a `DiagnosticBuilder` must be either emitted or canceled
427 /// or we emit a bug.
428 impl<'a
> Drop
for DiagnosticBuilder
<'a
> {
430 if !panicking() && !self.cancelled() {
431 let mut db
= DiagnosticBuilder
::new(
434 "the following error was constructed but not emitted",
444 macro_rules
! struct_span_err
{
445 ($session
:expr
, $span
:expr
, $code
:ident
, $
($message
:tt
)*) => ({
446 $session
.struct_span_err_with_code(
448 &format
!($
($message
)*),
449 $
crate::error_code
!($code
),
455 macro_rules
! error_code
{
456 ($code
:ident
) => {{ $crate::DiagnosticId::Error(stringify!($code).to_owned()) }
};