]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_errors/src/diagnostic_builder.rs
Auto merge of #78429 - casey:doctest-attribute-splitting, r=jyn514
[rust.git] / compiler / rustc_errors / src / diagnostic_builder.rs
1 use crate::{Diagnostic, DiagnosticId, DiagnosticStyledString};
2 use crate::{Handler, Level, StashKey};
3 use rustc_lint_defs::Applicability;
4
5 use rustc_span::{MultiSpan, Span};
6 use std::fmt::{self, Debug};
7 use std::ops::{Deref, DerefMut};
8 use std::thread::panicking;
9 use tracing::debug;
10
11 /// Used for emitting structured error messages and other diagnostic information.
12 ///
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`.
16 #[must_use]
17 #[derive(Clone)]
18 pub struct DiagnosticBuilder<'a>(Box<DiagnosticBuilderInner<'a>>);
19
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.
25 #[must_use]
26 #[derive(Clone)]
27 struct DiagnosticBuilderInner<'a> {
28     handler: &'a Handler,
29     diagnostic: Diagnostic,
30     allow_suggestions: bool,
31 }
32
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) => {
37         #[doc = $e]
38         $i
39     };
40 }
41
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
52     (
53         $(#[$attrs:meta])*
54         pub fn $n:ident(&self, $($name:ident: $ty:ty),* $(,)?) -> &Self
55     ) => {
56         $(#[$attrs])*
57         forward_inner_docs!(concat!("See [`Diagnostic::", stringify!($n), "()`].") =>
58         pub fn $n(&self, $($name: $ty),*) -> &Self {
59             self.diagnostic.$n($($name),*);
60             self
61         });
62     };
63
64     // Forward pattern for &mut self -> &mut Self
65     (
66         $(#[$attrs:meta])*
67         pub fn $n:ident(&mut self, $($name:ident: $ty:ty),* $(,)?) -> &mut Self
68     ) => {
69         $(#[$attrs])*
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),*);
73             self
74         });
75     };
76
77     // Forward pattern for &mut self -> &mut Self, with generic parameters.
78     (
79         $(#[$attrs:meta])*
80         pub fn $n:ident<$($generic:ident: $bound:path),*>(
81             &mut self,
82             $($name:ident: $ty:ty),*
83             $(,)?
84         ) -> &mut Self
85     ) => {
86         $(#[$attrs])*
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),*);
90             self
91         });
92     };
93 }
94
95 impl<'a> Deref for DiagnosticBuilder<'a> {
96     type Target = Diagnostic;
97
98     fn deref(&self) -> &Diagnostic {
99         &self.0.diagnostic
100     }
101 }
102
103 impl<'a> DerefMut for DiagnosticBuilder<'a> {
104     fn deref_mut(&mut self) -> &mut Diagnostic {
105         &mut self.0.diagnostic
106     }
107 }
108
109 impl<'a> DiagnosticBuilder<'a> {
110     /// Emit the diagnostic.
111     pub fn emit(&mut self) {
112         self.0.handler.emit_diagnostic(&self);
113         self.cancel();
114     }
115
116     /// Emit the diagnostic unless `delay` is true,
117     /// in which case the emission will be delayed as a bug.
118     ///
119     /// See `emit` and `delay_as_bug` for details.
120     pub fn emit_unless(&mut self, delay: bool) {
121         if delay {
122             self.delay_as_bug();
123         } else {
124             self.emit();
125         }
126     }
127
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()`].
131     ///
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);
136         }
137     }
138
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()
144         {
145             self.emit();
146             return None;
147         }
148
149         let handler = self.0.handler;
150
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);
155
156         // Logging here is useful to help track down where in logs an error was
157         // actually emitted.
158         debug!("buffer: diagnostic={:?}", diagnostic);
159
160         Some((diagnostic, handler))
161     }
162
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));
167     }
168
169     /// Convenience function for internal use, clients should use one of the
170     /// span_* methods instead.
171     pub fn sub<S: Into<MultiSpan>>(
172         &mut self,
173         level: Level,
174         message: &str,
175         span: Option<S>,
176     ) -> &mut Self {
177         let span = span.map(|s| s.into()).unwrap_or_else(MultiSpan::new);
178         self.0.diagnostic.sub(level, message, span, None);
179         self
180     }
181
182     /// Delay emission of this diagnostic as a bug.
183     ///
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
188     /// emitted.
189     ///
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());
195         self.cancel();
196     }
197
198     /// Appends a labeled span to the diagnostic.
199     ///
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
204     /// either.
205     ///
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
209     /// primary.
210     pub fn span_label(&mut self, span: Span, label: impl Into<String>) -> &mut Self {
211         self.0.diagnostic.span_label(span, label);
212         self
213     }
214
215     /// Labels all the given spans with the provided label.
216     /// See [`Diagnostic::span_label()`] for more information.
217     pub fn span_labels(
218         &mut self,
219         spans: impl IntoIterator<Item = Span>,
220         label: impl AsRef<str>,
221     ) -> &mut Self {
222         let label = label.as_ref();
223         for span in spans {
224             self.0.diagnostic.span_label(span, label);
225         }
226         self
227     }
228
229     forward!(pub fn note_expected_found(
230         &mut self,
231         expected_label: &dyn fmt::Display,
232         expected: DiagnosticStyledString,
233         found_label: &dyn fmt::Display,
234         found: DiagnosticStyledString,
235     ) -> &mut Self);
236
237     forward!(pub fn note_expected_found_extra(
238         &mut self,
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,
245     ) -> &mut Self);
246
247     forward!(pub fn note_unsuccessful_coercion(
248         &mut self,
249         expected: DiagnosticStyledString,
250         found: DiagnosticStyledString,
251     ) -> &mut Self);
252
253     forward!(pub fn note(&mut self, msg: &str) -> &mut Self);
254     forward!(pub fn span_note<S: Into<MultiSpan>>(
255         &mut self,
256         sp: S,
257         msg: &str,
258     ) -> &mut Self);
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>>(
263         &mut self,
264         sp: S,
265         msg: &str,
266     ) -> &mut Self);
267
268     /// See [`Diagnostic::multipart_suggestion()`].
269     pub fn multipart_suggestion(
270         &mut self,
271         msg: &str,
272         suggestion: Vec<(Span, String)>,
273         applicability: Applicability,
274     ) -> &mut Self {
275         if !self.0.allow_suggestions {
276             return self;
277         }
278         self.0.diagnostic.multipart_suggestion(msg, suggestion, applicability);
279         self
280     }
281
282     /// See [`Diagnostic::multipart_suggestions()`].
283     pub fn multipart_suggestions(
284         &mut self,
285         msg: &str,
286         suggestions: Vec<Vec<(Span, String)>>,
287         applicability: Applicability,
288     ) -> &mut Self {
289         if !self.0.allow_suggestions {
290             return self;
291         }
292         self.0.diagnostic.multipart_suggestions(msg, suggestions, applicability);
293         self
294     }
295
296     /// See [`Diagnostic::tool_only_multipart_suggestion()`].
297     pub fn tool_only_multipart_suggestion(
298         &mut self,
299         msg: &str,
300         suggestion: Vec<(Span, String)>,
301         applicability: Applicability,
302     ) -> &mut Self {
303         if !self.0.allow_suggestions {
304             return self;
305         }
306         self.0.diagnostic.tool_only_multipart_suggestion(msg, suggestion, applicability);
307         self
308     }
309
310     /// See [`Diagnostic::span_suggestion()`].
311     pub fn span_suggestion(
312         &mut self,
313         sp: Span,
314         msg: &str,
315         suggestion: String,
316         applicability: Applicability,
317     ) -> &mut Self {
318         if !self.0.allow_suggestions {
319             return self;
320         }
321         self.0.diagnostic.span_suggestion(sp, msg, suggestion, applicability);
322         self
323     }
324
325     /// See [`Diagnostic::span_suggestions()`].
326     pub fn span_suggestions(
327         &mut self,
328         sp: Span,
329         msg: &str,
330         suggestions: impl Iterator<Item = String>,
331         applicability: Applicability,
332     ) -> &mut Self {
333         if !self.0.allow_suggestions {
334             return self;
335         }
336         self.0.diagnostic.span_suggestions(sp, msg, suggestions, applicability);
337         self
338     }
339
340     /// See [`Diagnostic::span_suggestion_short()`].
341     pub fn span_suggestion_short(
342         &mut self,
343         sp: Span,
344         msg: &str,
345         suggestion: String,
346         applicability: Applicability,
347     ) -> &mut Self {
348         if !self.0.allow_suggestions {
349             return self;
350         }
351         self.0.diagnostic.span_suggestion_short(sp, msg, suggestion, applicability);
352         self
353     }
354
355     /// See [`Diagnostic::span_suggestion_verbose()`].
356     pub fn span_suggestion_verbose(
357         &mut self,
358         sp: Span,
359         msg: &str,
360         suggestion: String,
361         applicability: Applicability,
362     ) -> &mut Self {
363         if !self.0.allow_suggestions {
364             return self;
365         }
366         self.0.diagnostic.span_suggestion_verbose(sp, msg, suggestion, applicability);
367         self
368     }
369
370     /// See [`Diagnostic::span_suggestion_hidden()`].
371     pub fn span_suggestion_hidden(
372         &mut self,
373         sp: Span,
374         msg: &str,
375         suggestion: String,
376         applicability: Applicability,
377     ) -> &mut Self {
378         if !self.0.allow_suggestions {
379             return self;
380         }
381         self.0.diagnostic.span_suggestion_hidden(sp, msg, suggestion, applicability);
382         self
383     }
384
385     /// See [`Diagnostic::tool_only_span_suggestion()`] for more information.
386     pub fn tool_only_span_suggestion(
387         &mut self,
388         sp: Span,
389         msg: &str,
390         suggestion: String,
391         applicability: Applicability,
392     ) -> &mut Self {
393         if !self.0.allow_suggestions {
394             return self;
395         }
396         self.0.diagnostic.tool_only_span_suggestion(sp, msg, suggestion, applicability);
397         self
398     }
399
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);
403
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;
409         self
410     }
411
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)
416     }
417
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,
422         level: Level,
423         code: Option<DiagnosticId>,
424         message: &str,
425     ) -> DiagnosticBuilder<'a> {
426         let diagnostic = Diagnostic::new_with_code(level, code, message);
427         DiagnosticBuilder::new_diagnostic(handler, diagnostic)
428     }
429
430     /// Creates a new `DiagnosticBuilder` with an already constructed
431     /// diagnostic.
432     crate fn new_diagnostic(handler: &'a Handler, diagnostic: Diagnostic) -> DiagnosticBuilder<'a> {
433         debug!("Created new diagnostic");
434         DiagnosticBuilder(Box::new(DiagnosticBuilderInner {
435             handler,
436             diagnostic,
437             allow_suggestions: true,
438         }))
439     }
440 }
441
442 impl<'a> Debug for DiagnosticBuilder<'a> {
443     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
444         self.0.diagnostic.fmt(f)
445     }
446 }
447
448 /// Destructor bomb - a `DiagnosticBuilder` must be either emitted or canceled
449 /// or we emit a bug.
450 impl<'a> Drop for DiagnosticBuilder<'a> {
451     fn drop(&mut self) {
452         if !panicking() && !self.cancelled() {
453             let mut db = DiagnosticBuilder::new(
454                 self.0.handler,
455                 Level::Bug,
456                 "the following error was constructed but not emitted",
457             );
458             db.emit();
459             self.emit();
460             panic!();
461         }
462     }
463 }
464
465 #[macro_export]
466 macro_rules! struct_span_err {
467     ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
468         $session.struct_span_err_with_code(
469             $span,
470             &format!($($message)*),
471             $crate::error_code!($code),
472         )
473     })
474 }
475
476 #[macro_export]
477 macro_rules! error_code {
478     ($code:ident) => {{ $crate::DiagnosticId::Error(stringify!($code).to_owned()) }};
479 }