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