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