]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/diagnostic_builder.rs
Rollup merge of #59979 - stepancheg:num-size, r=ehuss
[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 ||
107             self.handler.flags.treat_err_as_bug.is_some()
108         {
109             self.emit();
110             return;
111         }
112
113         // We need to use `ptr::read` because `DiagnosticBuilder`
114         // implements `Drop`.
115         let diagnostic;
116         unsafe {
117             diagnostic = std::ptr::read(&self.diagnostic);
118             std::mem::forget(self);
119         };
120         // Logging here is useful to help track down where in logs an error was
121         // actually emitted.
122         debug!("buffer: diagnostic={:?}", diagnostic);
123         buffered_diagnostics.push(diagnostic);
124     }
125
126     /// Convenience function for internal use, clients should use one of the
127     /// span_* methods instead.
128     pub fn sub<S: Into<MultiSpan>>(
129         &mut self,
130         level: Level,
131         message: &str,
132         span: Option<S>,
133     ) -> &mut Self {
134         let span = span.map(|s| s.into()).unwrap_or_else(|| MultiSpan::new());
135         self.diagnostic.sub(level, message, span, None);
136         self
137     }
138
139     /// Delay emission of this diagnostic as a bug.
140     ///
141     /// This can be useful in contexts where an error indicates a bug but
142     /// typically this only happens when other compilation errors have already
143     /// happened. In those cases this can be used to defer emission of this
144     /// diagnostic as a bug in the compiler only if no other errors have been
145     /// emitted.
146     ///
147     /// In the meantime, though, callsites are required to deal with the "bug"
148     /// locally in whichever way makes the most sense.
149     pub fn delay_as_bug(&mut self) {
150         self.level = Level::Bug;
151         self.handler.delay_as_bug(self.diagnostic.clone());
152         self.cancel();
153     }
154
155     /// Adds a span/label to be included in the resulting snippet.
156     /// This is pushed onto the `MultiSpan` that was created when the
157     /// diagnostic was first built. If you don't call this function at
158     /// all, and you just supplied a `Span` to create the diagnostic,
159     /// then the snippet will just include that `Span`, which is
160     /// called the primary span.
161     pub fn span_label<T: Into<String>>(&mut self, span: Span, label: T) -> &mut Self {
162         self.diagnostic.span_label(span, label);
163         self
164     }
165
166     forward!(pub fn note_expected_found(&mut self,
167                                         label: &dyn fmt::Display,
168                                         expected: DiagnosticStyledString,
169                                         found: DiagnosticStyledString,
170                                         ) -> &mut Self);
171
172     forward!(pub fn note_expected_found_extra(&mut self,
173                                               label: &dyn fmt::Display,
174                                               expected: DiagnosticStyledString,
175                                               found: DiagnosticStyledString,
176                                               expected_extra: &dyn fmt::Display,
177                                               found_extra: &dyn fmt::Display,
178                                               ) -> &mut Self);
179
180     forward!(pub fn note(&mut self, msg: &str) -> &mut Self);
181     forward!(pub fn span_note<S: Into<MultiSpan>>(&mut self,
182                                                   sp: S,
183                                                   msg: &str,
184                                                   ) -> &mut Self);
185     forward!(pub fn warn(&mut self, msg: &str) -> &mut Self);
186     forward!(pub fn span_warn<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self);
187     forward!(pub fn help(&mut self, msg: &str) -> &mut Self);
188     forward!(pub fn span_help<S: Into<MultiSpan>>(&mut self,
189                                                   sp: S,
190                                                   msg: &str,
191                                                   ) -> &mut Self);
192
193     pub fn multipart_suggestion(
194         &mut self,
195         msg: &str,
196         suggestion: Vec<(Span, String)>,
197         applicability: Applicability,
198     ) -> &mut Self {
199         if !self.allow_suggestions {
200             return self
201         }
202         self.diagnostic.multipart_suggestion(
203             msg,
204             suggestion,
205             applicability,
206         );
207         self
208     }
209
210     pub fn tool_only_multipart_suggestion(
211         &mut self,
212         msg: &str,
213         suggestion: Vec<(Span, String)>,
214         applicability: Applicability,
215     ) -> &mut Self {
216         if !self.allow_suggestions {
217             return self
218         }
219         self.diagnostic.tool_only_multipart_suggestion(
220             msg,
221             suggestion,
222             applicability,
223         );
224         self
225     }
226
227
228     pub fn span_suggestion(
229         &mut self,
230         sp: Span,
231         msg: &str,
232         suggestion: String,
233         applicability: Applicability,
234     ) -> &mut Self {
235         if !self.allow_suggestions {
236             return self
237         }
238         self.diagnostic.span_suggestion(
239             sp,
240             msg,
241             suggestion,
242             applicability,
243         );
244         self
245     }
246
247     pub fn span_suggestions(
248         &mut self,
249         sp: Span,
250         msg: &str,
251         suggestions: impl Iterator<Item = String>,
252         applicability: Applicability,
253     ) -> &mut Self {
254         if !self.allow_suggestions {
255             return self
256         }
257         self.diagnostic.span_suggestions(
258             sp,
259             msg,
260             suggestions,
261             applicability,
262         );
263         self
264     }
265
266     pub fn span_suggestion_short(
267         &mut self,
268         sp: Span,
269         msg: &str,
270         suggestion: String,
271         applicability: Applicability,
272     ) -> &mut Self {
273         if !self.allow_suggestions {
274             return self
275         }
276         self.diagnostic.span_suggestion_short(
277             sp,
278             msg,
279             suggestion,
280             applicability,
281         );
282         self
283     }
284
285     pub fn span_suggestion_hidden(
286         &mut self,
287         sp: Span,
288         msg: &str,
289         suggestion: String,
290         applicability: Applicability,
291     ) -> &mut Self {
292         if !self.allow_suggestions {
293             return self
294         }
295         self.diagnostic.span_suggestion_hidden(
296             sp,
297             msg,
298             suggestion,
299             applicability,
300         );
301         self
302     }
303
304     pub fn tool_only_span_suggestion(
305         &mut self,
306         sp: Span,
307         msg: &str,
308         suggestion: String,
309         applicability: Applicability,
310     ) -> &mut Self {
311         if !self.allow_suggestions {
312             return self
313         }
314         self.diagnostic.tool_only_span_suggestion(
315             sp,
316             msg,
317             suggestion,
318             applicability,
319         );
320         self
321     }
322
323     forward!(pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self);
324     forward!(pub fn code(&mut self, s: DiagnosticId) -> &mut Self);
325
326     pub fn allow_suggestions(&mut self, allow: bool) -> &mut Self {
327         self.allow_suggestions = allow;
328         self
329     }
330
331     /// Convenience function for internal use, clients should use one of the
332     /// struct_* methods on Handler.
333     pub fn new(handler: &'a Handler, level: Level, message: &str) -> DiagnosticBuilder<'a> {
334         DiagnosticBuilder::new_with_code(handler, level, None, message)
335     }
336
337     /// Convenience function for internal use, clients should use one of the
338     /// struct_* methods on Handler.
339     pub fn new_with_code(handler: &'a Handler,
340                          level: Level,
341                          code: Option<DiagnosticId>,
342                          message: &str)
343                          -> DiagnosticBuilder<'a> {
344         let diagnostic = Diagnostic::new_with_code(level, code, message);
345         DiagnosticBuilder::new_diagnostic(handler, diagnostic)
346     }
347
348     /// Creates a new `DiagnosticBuilder` with an already constructed
349     /// diagnostic.
350     pub fn new_diagnostic(handler: &'a Handler, diagnostic: Diagnostic)
351                          -> DiagnosticBuilder<'a> {
352         DiagnosticBuilder {
353             handler,
354             diagnostic,
355             allow_suggestions: true,
356         }
357     }
358 }
359
360 impl<'a> Debug for DiagnosticBuilder<'a> {
361     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362         self.diagnostic.fmt(f)
363     }
364 }
365
366 /// Destructor bomb - a `DiagnosticBuilder` must be either emitted or canceled
367 /// or we emit a bug.
368 impl<'a> Drop for DiagnosticBuilder<'a> {
369     fn drop(&mut self) {
370         if !panicking() && !self.cancelled() {
371             let mut db = DiagnosticBuilder::new(self.handler,
372                                                 Level::Bug,
373                                                 "Error constructed but not emitted");
374             db.emit();
375             panic!();
376         }
377     }
378 }