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 /// This is a helper macro for [`forward!`] that allows automatically adding documentation
34 /// that uses tokens from [`forward!`]'s input.
35 macro_rules
! forward_inner_docs
{
36 ($e
:expr
=> $i
:item
) => {
42 /// In general, the `DiagnosticBuilder` uses deref to allow access to
43 /// the fields and methods of the embedded `diagnostic` in a
44 /// transparent way. *However,* many of the methods are intended to
45 /// be used in a chained way, and hence ought to return `self`. In
46 /// that case, we can't just naively forward to the method on the
47 /// `diagnostic`, because the return type would be a `&Diagnostic`
48 /// instead of a `&DiagnosticBuilder<'a>`. This `forward!` macro makes
49 /// it easy to declare such methods on the builder.
50 macro_rules
! forward
{
51 // Forward pattern for &self -> &Self
54 pub fn $n
:ident(&self, $
($name
:ident
: $ty
:ty
),* $
(,)?
) -> &Self
57 forward_inner_docs
!(concat
!("See [`Diagnostic::", stringify
!($n
), "()`].") =>
58 pub fn $
n(&self, $
($name
: $ty
),*) -> &Self {
59 self.diagnostic
.$
n($
($name
),*);
64 // Forward pattern for &mut self -> &mut Self
67 pub fn $n
:ident(&mut self, $
($name
:ident
: $ty
:ty
),* $
(,)?
) -> &mut Self
70 forward_inner_docs
!(concat
!("See [`Diagnostic::", stringify
!($n
), "()`].") =>
71 pub fn $
n(&mut self, $
($name
: $ty
),*) -> &mut Self {
72 self.0.diagnostic
.$
n($
($name
),*);
77 // Forward pattern for &mut self -> &mut Self, with generic parameters.
80 pub fn $n
:ident
<$
($generic
:ident
: $bound
:path
),*>(
82 $
($name
:ident
: $ty
:ty
),*
87 forward_inner_docs
!(concat
!("See [`Diagnostic::", stringify
!($n
), "()`].") =>
88 pub fn $n
<$
($generic
: $bound
),*>(&mut self, $
($name
: $ty
),*) -> &mut Self {
89 self.0.diagnostic
.$
n($
($name
),*);
95 impl<'a
> Deref
for DiagnosticBuilder
<'a
> {
96 type Target
= Diagnostic
;
98 fn deref(&self) -> &Diagnostic
{
103 impl<'a
> DerefMut
for DiagnosticBuilder
<'a
> {
104 fn deref_mut(&mut self) -> &mut Diagnostic
{
105 &mut self.0.diagnostic
109 impl<'a
> DiagnosticBuilder
<'a
> {
110 /// Emit the diagnostic.
111 pub fn emit(&mut self) {
112 self.0.handler
.emit_diagnostic(&self);
116 /// Emit the diagnostic unless `delay` is true,
117 /// in which case the emission will be delayed as a bug.
119 /// See `emit` and `delay_as_bug` for details.
120 pub fn emit_unless(&mut self, delay
: bool
) {
128 /// Stashes diagnostic for possible later improvement in a different,
129 /// later stage of the compiler. The diagnostic can be accessed with
130 /// the provided `span` and `key` through [`Handler::steal_diagnostic()`].
132 /// As with `buffer`, this is unless the handler has disabled such buffering.
133 pub fn stash(self, span
: Span
, key
: StashKey
) {
134 if let Some((diag
, handler
)) = self.into_diagnostic() {
135 handler
.stash_diagnostic(span
, key
, diag
);
139 /// Converts the builder to a `Diagnostic` for later emission,
140 /// unless handler has disabled such buffering.
141 pub fn into_diagnostic(mut self) -> Option
<(Diagnostic
, &'a Handler
)> {
142 if self.0.handler
.flags
.dont_buffer_diagnostics
143 || self.0.handler
.flags
.treat_err_as_bug
.is_some()
149 let handler
= self.0.handler
;
151 // We must use `Level::Cancelled` for `dummy` to avoid an ICE about an
152 // unused diagnostic.
153 let dummy
= Diagnostic
::new(Level
::Cancelled
, "");
154 let diagnostic
= std
::mem
::replace(&mut self.0.diagnostic
, dummy
);
156 // Logging here is useful to help track down where in logs an error was
158 debug
!("buffer: diagnostic={:?}", diagnostic
);
160 Some((diagnostic
, handler
))
163 /// Buffers the diagnostic for later emission,
164 /// unless handler has disabled such buffering.
165 pub fn buffer(self, buffered_diagnostics
: &mut Vec
<Diagnostic
>) {
166 buffered_diagnostics
.extend(self.into_diagnostic().map(|(diag
, _
)| diag
));
169 /// Convenience function for internal use, clients should use one of the
170 /// span_* methods instead.
171 pub fn sub
<S
: Into
<MultiSpan
>>(
177 let span
= span
.map(|s
| s
.into()).unwrap_or_else(MultiSpan
::new
);
178 self.0.diagnostic
.sub(level
, message
, span
, None
);
182 /// Delay emission of this diagnostic as a bug.
184 /// This can be useful in contexts where an error indicates a bug but
185 /// typically this only happens when other compilation errors have already
186 /// happened. In those cases this can be used to defer emission of this
187 /// diagnostic as a bug in the compiler only if no other errors have been
190 /// In the meantime, though, callsites are required to deal with the "bug"
191 /// locally in whichever way makes the most sense.
192 pub fn delay_as_bug(&mut self) {
193 self.level
= Level
::Bug
;
194 self.0.handler
.delay_as_bug(self.0.diagnostic
.clone());
198 /// Appends a labeled span to the diagnostic.
200 /// Labels are used to convey additional context for the diagnostic's primary span. They will
201 /// be shown together with the original diagnostic's span, *not* with spans added by
202 /// `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because
203 /// the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed
206 /// Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when
207 /// the diagnostic was constructed. However, the label span is *not* considered a
208 /// ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is
210 pub fn span_label(&mut self, span
: Span
, label
: impl Into
<String
>) -> &mut Self {
211 self.0.diagnostic
.span_label(span
, label
);
215 /// Labels all the given spans with the provided label.
216 /// See [`Diagnostic::span_label()`] for more information.
219 spans
: impl IntoIterator
<Item
= Span
>,
220 label
: impl AsRef
<str>,
222 let label
= label
.as_ref();
224 self.0.diagnostic
.span_label(span
, label
);
229 forward
!(pub fn note_expected_found(
231 expected_label
: &dyn fmt
::Display
,
232 expected
: DiagnosticStyledString
,
233 found_label
: &dyn fmt
::Display
,
234 found
: DiagnosticStyledString
,
237 forward
!(pub fn note_expected_found_extra(
239 expected_label
: &dyn fmt
::Display
,
240 expected
: DiagnosticStyledString
,
241 found_label
: &dyn fmt
::Display
,
242 found
: DiagnosticStyledString
,
243 expected_extra
: &dyn fmt
::Display
,
244 found_extra
: &dyn fmt
::Display
,
247 forward
!(pub fn note_unsuccessful_coercion(
249 expected
: DiagnosticStyledString
,
250 found
: DiagnosticStyledString
,
253 forward
!(pub fn note(&mut self, msg
: &str) -> &mut Self);
254 forward
!(pub fn span_note
<S
: Into
<MultiSpan
>>(
259 forward
!(pub fn warn(&mut self, msg
: &str) -> &mut Self);
260 forward
!(pub fn span_warn
<S
: Into
<MultiSpan
>>(&mut self, sp
: S
, msg
: &str) -> &mut Self);
261 forward
!(pub fn help(&mut self, msg
: &str) -> &mut Self);
262 forward
!(pub fn span_help
<S
: Into
<MultiSpan
>>(
268 /// See [`Diagnostic::multipart_suggestion()`].
269 pub fn multipart_suggestion(
272 suggestion
: Vec
<(Span
, String
)>,
273 applicability
: Applicability
,
275 if !self.0.allow_suggestions
{
278 self.0.diagnostic
.multipart_suggestion(msg
, suggestion
, applicability
);
282 /// See [`Diagnostic::multipart_suggestions()`].
283 pub fn multipart_suggestions(
286 suggestions
: Vec
<Vec
<(Span
, String
)>>,
287 applicability
: Applicability
,
289 if !self.0.allow_suggestions
{
292 self.0.diagnostic
.multipart_suggestions(msg
, suggestions
, applicability
);
296 /// See [`Diagnostic::tool_only_multipart_suggestion()`].
297 pub fn tool_only_multipart_suggestion(
300 suggestion
: Vec
<(Span
, String
)>,
301 applicability
: Applicability
,
303 if !self.0.allow_suggestions
{
306 self.0.diagnostic
.tool_only_multipart_suggestion(msg
, suggestion
, applicability
);
310 /// See [`Diagnostic::span_suggestion()`].
311 pub fn span_suggestion(
316 applicability
: Applicability
,
318 if !self.0.allow_suggestions
{
321 self.0.diagnostic
.span_suggestion(sp
, msg
, suggestion
, applicability
);
325 /// See [`Diagnostic::span_suggestions()`].
326 pub fn span_suggestions(
330 suggestions
: impl Iterator
<Item
= String
>,
331 applicability
: Applicability
,
333 if !self.0.allow_suggestions
{
336 self.0.diagnostic
.span_suggestions(sp
, msg
, suggestions
, applicability
);
340 /// See [`Diagnostic::span_suggestion_short()`].
341 pub fn span_suggestion_short(
346 applicability
: Applicability
,
348 if !self.0.allow_suggestions
{
351 self.0.diagnostic
.span_suggestion_short(sp
, msg
, suggestion
, applicability
);
355 /// See [`Diagnostic::span_suggestion_verbose()`].
356 pub fn span_suggestion_verbose(
361 applicability
: Applicability
,
363 if !self.0.allow_suggestions
{
366 self.0.diagnostic
.span_suggestion_verbose(sp
, msg
, suggestion
, applicability
);
370 /// See [`Diagnostic::span_suggestion_hidden()`].
371 pub fn span_suggestion_hidden(
376 applicability
: Applicability
,
378 if !self.0.allow_suggestions
{
381 self.0.diagnostic
.span_suggestion_hidden(sp
, msg
, suggestion
, applicability
);
385 /// See [`Diagnostic::tool_only_span_suggestion()`] for more information.
386 pub fn tool_only_span_suggestion(
391 applicability
: Applicability
,
393 if !self.0.allow_suggestions
{
396 self.0.diagnostic
.tool_only_span_suggestion(sp
, msg
, suggestion
, applicability
);
400 forward
!(pub fn set_primary_message
<M
: Into
<String
>>(&mut self, msg
: M
) -> &mut Self);
401 forward
!(pub fn set_span
<S
: Into
<MultiSpan
>>(&mut self, sp
: S
) -> &mut Self);
402 forward
!(pub fn code(&mut self, s
: DiagnosticId
) -> &mut Self);
404 /// Allow attaching suggestions this diagnostic.
405 /// If this is set to `false`, then any suggestions attached with the `span_suggestion_*`
406 /// methods after this is set to `false` will be ignored.
407 pub fn allow_suggestions(&mut self, allow
: bool
) -> &mut Self {
408 self.0.allow_suggestions
= allow
;
412 /// Convenience function for internal use, clients should use one of the
413 /// `struct_*` methods on [`Handler`].
414 crate fn new(handler
: &'a Handler
, level
: Level
, message
: &str) -> DiagnosticBuilder
<'a
> {
415 DiagnosticBuilder
::new_with_code(handler
, level
, None
, message
)
418 /// Convenience function for internal use, clients should use one of the
419 /// `struct_*` methods on [`Handler`].
420 crate fn new_with_code(
421 handler
: &'a Handler
,
423 code
: Option
<DiagnosticId
>,
425 ) -> DiagnosticBuilder
<'a
> {
426 let diagnostic
= Diagnostic
::new_with_code(level
, code
, message
);
427 DiagnosticBuilder
::new_diagnostic(handler
, diagnostic
)
430 /// Creates a new `DiagnosticBuilder` with an already constructed
432 crate fn new_diagnostic(handler
: &'a Handler
, diagnostic
: Diagnostic
) -> DiagnosticBuilder
<'a
> {
433 debug
!("Created new diagnostic");
434 DiagnosticBuilder(Box
::new(DiagnosticBuilderInner
{
437 allow_suggestions
: true,
442 impl<'a
> Debug
for DiagnosticBuilder
<'a
> {
443 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
444 self.0.diagnostic
.fmt(f
)
448 /// Destructor bomb - a `DiagnosticBuilder` must be either emitted or canceled
449 /// or we emit a bug.
450 impl<'a
> Drop
for DiagnosticBuilder
<'a
> {
452 if !panicking() && !self.cancelled() {
453 let mut db
= DiagnosticBuilder
::new(
456 "the following error was constructed but not emitted",
466 macro_rules
! struct_span_err
{
467 ($session
:expr
, $span
:expr
, $code
:ident
, $
($message
:tt
)*) => ({
468 $session
.struct_span_err_with_code(
470 &format
!($
($message
)*),
471 $
crate::error_code
!($code
),
477 macro_rules
! error_code
{
478 ($code
:ident
) => {{ $crate::DiagnosticId::Error(stringify!($code).to_owned()) }
};