]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/diagnostic_builder.rs
Auto merge of #67076 - mbrubeck:condvar, r=dtolnay
[rust.git] / src / librustc_errors / diagnostic_builder.rs
1 use crate::{Applicability, Handler, Level, StashKey};
2 use crate::{Diagnostic, DiagnosticId, DiagnosticStyledString};
3
4 use log::debug;
5 use rustc_span::{MultiSpan, Span};
6 use std::fmt::{self, Debug};
7 use std::ops::{Deref, DerefMut};
8 use std::thread::panicking;
9
10 /// Used for emitting structured error messages and other diagnostic information.
11 ///
12 /// If there is some state in a downstream crate you would like to
13 /// access in the methods of `DiagnosticBuilder` here, consider
14 /// extending `HandlerFlags`, accessed via `self.handler.flags`.
15 #[must_use]
16 #[derive(Clone)]
17 pub struct DiagnosticBuilder<'a>(Box<DiagnosticBuilderInner<'a>>);
18
19 /// This is a large type, and often used as a return value, especially within
20 /// the frequently-used `PResult` type. In theory, return value optimization
21 /// (RVO) should avoid unnecessary copying. In practice, it does not (at the
22 /// time of writing). The split between `DiagnosticBuilder` and
23 /// `DiagnosticBuilderInner` exists to avoid many `memcpy` calls.
24 #[must_use]
25 #[derive(Clone)]
26 struct DiagnosticBuilderInner<'a> {
27     handler: &'a Handler,
28     diagnostic: Diagnostic,
29     allow_suggestions: bool,
30 }
31
32 /// In general, the `DiagnosticBuilder` uses deref to allow access to
33 /// the fields and methods of the embedded `diagnostic` in a
34 /// transparent way. *However,* many of the methods are intended to
35 /// be used in a chained way, and hence ought to return `self`. In
36 /// that case, we can't just naively forward to the method on the
37 /// `diagnostic`, because the return type would be a `&Diagnostic`
38 /// instead of a `&DiagnosticBuilder<'a>`. This `forward!` macro makes
39 /// it easy to declare such methods on the builder.
40 macro_rules! forward {
41     // Forward pattern for &self -> &Self
42     (
43         $(#[$attrs:meta])*
44         pub fn $n:ident(&self, $($name:ident: $ty:ty),* $(,)?) -> &Self
45     ) => {
46         $(#[$attrs])*
47         pub fn $n(&self, $($name: $ty),*) -> &Self {
48             self.diagnostic.$n($($name),*);
49             self
50         }
51     };
52
53     // Forward pattern for &mut self -> &mut Self
54     (
55         $(#[$attrs:meta])*
56         pub fn $n:ident(&mut self, $($name:ident: $ty:ty),* $(,)?) -> &mut Self
57     ) => {
58         $(#[$attrs])*
59         pub fn $n(&mut self, $($name: $ty),*) -> &mut Self {
60             self.0.diagnostic.$n($($name),*);
61             self
62         }
63     };
64
65     // Forward pattern for &mut self -> &mut Self, with S: Into<MultiSpan>
66     // type parameter. No obvious way to make this more generic.
67     (
68         $(#[$attrs:meta])*
69         pub fn $n:ident<S: Into<MultiSpan>>(
70             &mut self,
71             $($name:ident: $ty:ty),*
72             $(,)?
73         ) -> &mut Self
74     ) => {
75         $(#[$attrs])*
76         pub fn $n<S: Into<MultiSpan>>(&mut self, $($name: $ty),*) -> &mut Self {
77             self.0.diagnostic.$n($($name),*);
78             self
79         }
80     };
81 }
82
83 impl<'a> Deref for DiagnosticBuilder<'a> {
84     type Target = Diagnostic;
85
86     fn deref(&self) -> &Diagnostic {
87         &self.0.diagnostic
88     }
89 }
90
91 impl<'a> DerefMut for DiagnosticBuilder<'a> {
92     fn deref_mut(&mut self) -> &mut Diagnostic {
93         &mut self.0.diagnostic
94     }
95 }
96
97 impl<'a> DiagnosticBuilder<'a> {
98     /// Emit the diagnostic.
99     pub fn emit(&mut self) {
100         self.0.handler.emit_diagnostic(&self);
101         self.cancel();
102     }
103
104     /// Emit the diagnostic unless `delay` is true,
105     /// in which case the emission will be delayed as a bug.
106     ///
107     /// See `emit` and `delay_as_bug` for details.
108     pub fn emit_unless(&mut self, delay: bool) {
109         if delay { self.delay_as_bug() } else { self.emit() }
110     }
111
112     /// Stashes diagnostic for possible later improvement in a different,
113     /// later stage of the compiler. The diagnostic can be accessed with
114     /// the provided `span` and `key` through `.steal_diagnostic` on `Handler`.
115     ///
116     /// As with `buffer`, this is unless the handler has disabled such buffering.
117     pub fn stash(self, span: Span, key: StashKey) {
118         if let Some((diag, handler)) = self.into_diagnostic() {
119             handler.stash_diagnostic(span, key, diag);
120         }
121     }
122
123     /// Converts the builder to a `Diagnostic` for later emission,
124     /// unless handler has disabled such buffering.
125     pub fn into_diagnostic(mut self) -> Option<(Diagnostic, &'a Handler)> {
126         if self.0.handler.flags.dont_buffer_diagnostics
127             || self.0.handler.flags.treat_err_as_bug.is_some()
128         {
129             self.emit();
130             return None;
131         }
132
133         let handler = self.0.handler;
134
135         // We need to use `ptr::read` because `DiagnosticBuilder` implements `Drop`.
136         let diagnostic;
137         unsafe {
138             diagnostic = std::ptr::read(&self.0.diagnostic);
139             std::mem::forget(self);
140         };
141         // Logging here is useful to help track down where in logs an error was
142         // actually emitted.
143         debug!("buffer: diagnostic={:?}", diagnostic);
144
145         Some((diagnostic, handler))
146     }
147
148     /// Buffers the diagnostic for later emission,
149     /// unless handler has disabled such buffering.
150     pub fn buffer(self, buffered_diagnostics: &mut Vec<Diagnostic>) {
151         buffered_diagnostics.extend(self.into_diagnostic().map(|(diag, _)| diag));
152     }
153
154     /// Convenience function for internal use, clients should use one of the
155     /// span_* methods instead.
156     pub fn sub<S: Into<MultiSpan>>(
157         &mut self,
158         level: Level,
159         message: &str,
160         span: Option<S>,
161     ) -> &mut Self {
162         let span = span.map(|s| s.into()).unwrap_or_else(|| MultiSpan::new());
163         self.0.diagnostic.sub(level, message, span, None);
164         self
165     }
166
167     /// Delay emission of this diagnostic as a bug.
168     ///
169     /// This can be useful in contexts where an error indicates a bug but
170     /// typically this only happens when other compilation errors have already
171     /// happened. In those cases this can be used to defer emission of this
172     /// diagnostic as a bug in the compiler only if no other errors have been
173     /// emitted.
174     ///
175     /// In the meantime, though, callsites are required to deal with the "bug"
176     /// locally in whichever way makes the most sense.
177     pub fn delay_as_bug(&mut self) {
178         self.level = Level::Bug;
179         self.0.handler.delay_as_bug(self.0.diagnostic.clone());
180         self.cancel();
181     }
182
183     /// Adds a span/label to be included in the resulting snippet.
184     /// This is pushed onto the `MultiSpan` that was created when the
185     /// diagnostic was first built. If you don't call this function at
186     /// all, and you just supplied a `Span` to create the diagnostic,
187     /// then the snippet will just include that `Span`, which is
188     /// called the primary span.
189     pub fn span_label<T: Into<String>>(&mut self, span: Span, label: T) -> &mut Self {
190         self.0.diagnostic.span_label(span, label);
191         self
192     }
193
194     forward!(pub fn note_expected_found(
195         &mut self,
196         expected_label: &dyn fmt::Display,
197         expected: DiagnosticStyledString,
198         found_label: &dyn fmt::Display,
199         found: DiagnosticStyledString,
200     ) -> &mut Self);
201
202     forward!(pub fn note_expected_found_extra(
203         &mut self,
204         expected_label: &dyn fmt::Display,
205         expected: DiagnosticStyledString,
206         found_label: &dyn fmt::Display,
207         found: DiagnosticStyledString,
208         expected_extra: &dyn fmt::Display,
209         found_extra: &dyn fmt::Display,
210     ) -> &mut Self);
211
212     forward!(pub fn note_unsuccessfull_coercion(
213         &mut self,
214         expected: DiagnosticStyledString,
215         found: DiagnosticStyledString,
216     ) -> &mut Self);
217
218     forward!(pub fn note(&mut self, msg: &str) -> &mut Self);
219     forward!(pub fn span_note<S: Into<MultiSpan>>(
220         &mut self,
221         sp: S,
222         msg: &str,
223     ) -> &mut Self);
224     forward!(pub fn warn(&mut self, msg: &str) -> &mut Self);
225     forward!(pub fn span_warn<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self);
226     forward!(pub fn help(&mut self, msg: &str) -> &mut Self);
227     forward!(pub fn span_help<S: Into<MultiSpan>>(
228         &mut self,
229         sp: S,
230         msg: &str,
231     ) -> &mut Self);
232
233     pub fn multipart_suggestion(
234         &mut self,
235         msg: &str,
236         suggestion: Vec<(Span, String)>,
237         applicability: Applicability,
238     ) -> &mut Self {
239         if !self.0.allow_suggestions {
240             return self;
241         }
242         self.0.diagnostic.multipart_suggestion(msg, suggestion, applicability);
243         self
244     }
245
246     pub fn tool_only_multipart_suggestion(
247         &mut self,
248         msg: &str,
249         suggestion: Vec<(Span, String)>,
250         applicability: Applicability,
251     ) -> &mut Self {
252         if !self.0.allow_suggestions {
253             return self;
254         }
255         self.0.diagnostic.tool_only_multipart_suggestion(msg, suggestion, applicability);
256         self
257     }
258
259     pub fn span_suggestion(
260         &mut self,
261         sp: Span,
262         msg: &str,
263         suggestion: String,
264         applicability: Applicability,
265     ) -> &mut Self {
266         if !self.0.allow_suggestions {
267             return self;
268         }
269         self.0.diagnostic.span_suggestion(sp, msg, suggestion, applicability);
270         self
271     }
272
273     pub fn span_suggestions(
274         &mut self,
275         sp: Span,
276         msg: &str,
277         suggestions: impl Iterator<Item = String>,
278         applicability: Applicability,
279     ) -> &mut Self {
280         if !self.0.allow_suggestions {
281             return self;
282         }
283         self.0.diagnostic.span_suggestions(sp, msg, suggestions, applicability);
284         self
285     }
286
287     pub fn span_suggestion_short(
288         &mut self,
289         sp: Span,
290         msg: &str,
291         suggestion: String,
292         applicability: Applicability,
293     ) -> &mut Self {
294         if !self.0.allow_suggestions {
295             return self;
296         }
297         self.0.diagnostic.span_suggestion_short(sp, msg, suggestion, applicability);
298         self
299     }
300
301     pub fn span_suggestion_hidden(
302         &mut self,
303         sp: Span,
304         msg: &str,
305         suggestion: String,
306         applicability: Applicability,
307     ) -> &mut Self {
308         if !self.0.allow_suggestions {
309             return self;
310         }
311         self.0.diagnostic.span_suggestion_hidden(sp, msg, suggestion, applicability);
312         self
313     }
314
315     pub fn tool_only_span_suggestion(
316         &mut self,
317         sp: Span,
318         msg: &str,
319         suggestion: String,
320         applicability: Applicability,
321     ) -> &mut Self {
322         if !self.0.allow_suggestions {
323             return self;
324         }
325         self.0.diagnostic.tool_only_span_suggestion(sp, msg, suggestion, applicability);
326         self
327     }
328
329     forward!(pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self);
330     forward!(pub fn code(&mut self, s: DiagnosticId) -> &mut Self);
331
332     pub fn allow_suggestions(&mut self, allow: bool) -> &mut Self {
333         self.0.allow_suggestions = allow;
334         self
335     }
336
337     /// Convenience function for internal use, clients should use one of the
338     /// struct_* methods on Handler.
339     crate fn new(handler: &'a Handler, level: Level, message: &str) -> DiagnosticBuilder<'a> {
340         DiagnosticBuilder::new_with_code(handler, level, None, message)
341     }
342
343     /// Convenience function for internal use, clients should use one of the
344     /// struct_* methods on Handler.
345     crate fn new_with_code(
346         handler: &'a Handler,
347         level: Level,
348         code: Option<DiagnosticId>,
349         message: &str,
350     ) -> DiagnosticBuilder<'a> {
351         let diagnostic = Diagnostic::new_with_code(level, code, message);
352         DiagnosticBuilder::new_diagnostic(handler, diagnostic)
353     }
354
355     /// Creates a new `DiagnosticBuilder` with an already constructed
356     /// diagnostic.
357     crate fn new_diagnostic(handler: &'a Handler, diagnostic: Diagnostic) -> DiagnosticBuilder<'a> {
358         DiagnosticBuilder(Box::new(DiagnosticBuilderInner {
359             handler,
360             diagnostic,
361             allow_suggestions: true,
362         }))
363     }
364 }
365
366 impl<'a> Debug for DiagnosticBuilder<'a> {
367     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368         self.0.diagnostic.fmt(f)
369     }
370 }
371
372 /// Destructor bomb - a `DiagnosticBuilder` must be either emitted or canceled
373 /// or we emit a bug.
374 impl<'a> Drop for DiagnosticBuilder<'a> {
375     fn drop(&mut self) {
376         if !panicking() && !self.cancelled() {
377             let mut db = DiagnosticBuilder::new(
378                 self.0.handler,
379                 Level::Bug,
380                 "the following error was constructed but not emitted",
381             );
382             db.emit();
383             self.emit();
384             panic!();
385         }
386     }
387 }
388
389 #[macro_export]
390 macro_rules! struct_span_err {
391     ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
392         $session.struct_span_err_with_code(
393             $span,
394             &format!($($message)*),
395             $crate::error_code!($code),
396         )
397     })
398 }
399
400 #[macro_export]
401 macro_rules! error_code {
402     ($code:ident) => {{
403         let _ = $code;
404         $crate::DiagnosticId::Error(stringify!($code).to_owned())
405     }};
406 }