]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/diagnostic_builder.rs
Deny bare trait objects in src/librustc_errors
[rust.git] / src / librustc_errors / diagnostic_builder.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use Diagnostic;
12 use DiagnosticId;
13 use DiagnosticStyledString;
14 use Applicability;
15
16 use Level;
17 use Handler;
18 use std::fmt::{self, Debug};
19 use std::ops::{Deref, DerefMut};
20 use std::thread::panicking;
21 use syntax_pos::{MultiSpan, Span};
22
23 /// Used for emitting structured error messages and other diagnostic information.
24 #[must_use]
25 #[derive(Clone)]
26 pub struct DiagnosticBuilder<'a> {
27     pub handler: &'a Handler,
28     diagnostic: Diagnostic,
29 }
30
31 /// In general, the `DiagnosticBuilder` uses deref to allow access to
32 /// the fields and methods of the embedded `diagnostic` in a
33 /// transparent way.  *However,* many of the methods are intended to
34 /// be used in a chained way, and hence ought to return `self`. In
35 /// that case, we can't just naively forward to the method on the
36 /// `diagnostic`, because the return type would be a `&Diagnostic`
37 /// instead of a `&DiagnosticBuilder<'a>`. This `forward!` macro makes
38 /// it easy to declare such methods on the builder.
39 macro_rules! forward {
40     // Forward pattern for &self -> &Self
41     (pub fn $n:ident(&self, $($name:ident: $ty:ty),*) -> &Self) => {
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     (pub fn $n:ident(&mut self, $($name:ident: $ty:ty),*) -> &mut Self) => {
50         pub fn $n(&mut self, $($name: $ty),*) -> &mut Self {
51             self.diagnostic.$n($($name),*);
52             self
53         }
54     };
55
56     // Forward pattern for &mut self -> &mut Self, with S: Into<MultiSpan>
57     // type parameter. No obvious way to make this more generic.
58     (pub fn $n:ident<S: Into<MultiSpan>>(&mut self, $($name:ident: $ty:ty),*) -> &mut Self) => {
59         pub fn $n<S: Into<MultiSpan>>(&mut self, $($name: $ty),*) -> &mut Self {
60             self.diagnostic.$n($($name),*);
61             self
62         }
63     };
64 }
65
66 impl<'a> Deref for DiagnosticBuilder<'a> {
67     type Target = Diagnostic;
68
69     fn deref(&self) -> &Diagnostic {
70         &self.diagnostic
71     }
72 }
73
74 impl<'a> DerefMut for DiagnosticBuilder<'a> {
75     fn deref_mut(&mut self) -> &mut Diagnostic {
76         &mut self.diagnostic
77     }
78 }
79
80 impl<'a> DiagnosticBuilder<'a> {
81     /// Emit the diagnostic.
82     pub fn emit(&mut self) {
83         if self.cancelled() {
84             return;
85         }
86
87         self.handler.emit_db(&self);
88         self.cancel();
89     }
90
91     pub fn is_error(&self) -> bool {
92         match self.level {
93             Level::Bug |
94             Level::Fatal |
95             Level::PhaseFatal |
96             Level::Error |
97             Level::FailureNote => {
98                 true
99             }
100
101             Level::Warning |
102             Level::Note |
103             Level::Help |
104             Level::Cancelled => {
105                 false
106             }
107         }
108     }
109
110     /// Convenience function for internal use, clients should use one of the
111     /// span_* methods instead.
112     pub fn sub<S: Into<MultiSpan>>(
113         &mut self,
114         level: Level,
115         message: &str,
116         span: Option<S>,
117     ) -> &mut Self {
118         let span = span.map(|s| s.into()).unwrap_or(MultiSpan::new());
119         self.diagnostic.sub(level, message, span, None);
120         self
121     }
122
123     /// Delay emission of this diagnostic as a bug.
124     ///
125     /// This can be useful in contexts where an error indicates a bug but
126     /// typically this only happens when other compilation errors have already
127     /// happened. In those cases this can be used to defer emission of this
128     /// diagnostic as a bug in the compiler only if no other errors have been
129     /// emitted.
130     ///
131     /// In the meantime, though, callsites are required to deal with the "bug"
132     /// locally in whichever way makes the most sense.
133     pub fn delay_as_bug(&mut self) {
134         self.level = Level::Bug;
135         *self.handler.delayed_span_bug.borrow_mut() = Some(self.diagnostic.clone());
136         self.cancel();
137     }
138
139     /// Add a span/label to be included in the resulting snippet.
140     /// This is pushed onto the `MultiSpan` that was created when the
141     /// diagnostic was first built. If you don't call this function at
142     /// all, and you just supplied a `Span` to create the diagnostic,
143     /// then the snippet will just include that `Span`, which is
144     /// called the primary span.
145     pub fn span_label<T: Into<String>>(&mut self, span: Span, label: T) -> &mut Self {
146         self.diagnostic.span_label(span, label);
147         self
148     }
149
150     forward!(pub fn note_expected_found(&mut self,
151                                         label: &dyn fmt::Display,
152                                         expected: DiagnosticStyledString,
153                                         found: DiagnosticStyledString)
154                                         -> &mut Self);
155
156     forward!(pub fn note_expected_found_extra(&mut self,
157                                               label: &dyn fmt::Display,
158                                               expected: DiagnosticStyledString,
159                                               found: DiagnosticStyledString,
160                                               expected_extra: &dyn fmt::Display,
161                                               found_extra: &dyn fmt::Display)
162                                               -> &mut Self);
163
164     forward!(pub fn note(&mut self, msg: &str) -> &mut Self);
165     forward!(pub fn span_note<S: Into<MultiSpan>>(&mut self,
166                                                   sp: S,
167                                                   msg: &str)
168                                                   -> &mut Self);
169     forward!(pub fn warn(&mut self, msg: &str) -> &mut Self);
170     forward!(pub fn span_warn<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self);
171     forward!(pub fn help(&mut self , msg: &str) -> &mut Self);
172     forward!(pub fn span_help<S: Into<MultiSpan>>(&mut self,
173                                                   sp: S,
174                                                   msg: &str)
175                                                   -> &mut Self);
176     forward!(pub fn span_suggestion_short(&mut self,
177                                           sp: Span,
178                                           msg: &str,
179                                           suggestion: String)
180                                           -> &mut Self);
181     forward!(pub fn multipart_suggestion(
182         &mut self,
183         msg: &str,
184         suggestion: Vec<(Span, String)>
185     ) -> &mut Self);
186     forward!(pub fn span_suggestion(&mut self,
187                                     sp: Span,
188                                     msg: &str,
189                                     suggestion: String)
190                                     -> &mut Self);
191     forward!(pub fn span_suggestions(&mut self,
192                                      sp: Span,
193                                      msg: &str,
194                                      suggestions: Vec<String>)
195                                      -> &mut Self);
196     forward!(pub fn span_suggestion_with_applicability(&mut self,
197                                                 sp: Span,
198                                                 msg: &str,
199                                                 suggestion: String,
200                                                 applicability: Applicability)
201                                                 -> &mut Self);
202     forward!(pub fn span_suggestions_with_applicability(&mut self,
203                                                  sp: Span,
204                                                  msg: &str,
205                                                  suggestions: Vec<String>,
206                                                  applicability: Applicability)
207                                                  -> &mut Self);
208     forward!(pub fn span_suggestion_short_with_applicability(&mut self,
209                                                              sp: Span,
210                                                              msg: &str,
211                                                              suggestion: String,
212                                                              applicability: Applicability)
213                                                              -> &mut Self);
214     forward!(pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self);
215     forward!(pub fn code(&mut self, s: DiagnosticId) -> &mut Self);
216
217     /// Convenience function for internal use, clients should use one of the
218     /// struct_* methods on Handler.
219     pub fn new(handler: &'a Handler, level: Level, message: &str) -> DiagnosticBuilder<'a> {
220         DiagnosticBuilder::new_with_code(handler, level, None, message)
221     }
222
223     /// Convenience function for internal use, clients should use one of the
224     /// struct_* methods on Handler.
225     pub fn new_with_code(handler: &'a Handler,
226                          level: Level,
227                          code: Option<DiagnosticId>,
228                          message: &str)
229                          -> DiagnosticBuilder<'a> {
230         let diagnostic = Diagnostic::new_with_code(level, code, message);
231         DiagnosticBuilder::new_diagnostic(handler, diagnostic)
232     }
233
234     /// Creates a new `DiagnosticBuilder` with an already constructed
235     /// diagnostic.
236     pub fn new_diagnostic(handler: &'a Handler, diagnostic: Diagnostic)
237                          -> DiagnosticBuilder<'a> {
238         DiagnosticBuilder { handler, diagnostic }
239     }
240 }
241
242 impl<'a> Debug for DiagnosticBuilder<'a> {
243     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
244         self.diagnostic.fmt(f)
245     }
246 }
247
248 /// Destructor bomb - a `DiagnosticBuilder` must be either emitted or canceled
249 /// or we emit a bug.
250 impl<'a> Drop for DiagnosticBuilder<'a> {
251     fn drop(&mut self) {
252         if !panicking() && !self.cancelled() {
253             let mut db = DiagnosticBuilder::new(self.handler,
254                                                 Level::Bug,
255                                                 "Error constructed but not emitted");
256             db.emit();
257             panic!();
258         }
259     }
260 }