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