]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/diagnostic.rs
38fa35ecb126299a7fec1f01638447bf3c510b07
[rust.git] / src / librustc_errors / diagnostic.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 CodeSuggestion;
12 use Level;
13 use RenderSpan;
14 use std::fmt;
15 use syntax_pos::{MultiSpan, Span};
16 use snippet::Style;
17
18 #[must_use]
19 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
20 pub struct Diagnostic {
21     pub level: Level,
22     pub message: Vec<(String, Style)>,
23     pub code: Option<String>,
24     pub span: MultiSpan,
25     pub children: Vec<SubDiagnostic>,
26     pub suggestion: Option<CodeSuggestion>,
27 }
28
29 /// For example a note attached to an error.
30 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
31 pub struct SubDiagnostic {
32     pub level: Level,
33     pub message: Vec<(String, Style)>,
34     pub span: MultiSpan,
35     pub render_span: Option<RenderSpan>,
36 }
37
38 #[derive(PartialEq, Eq)]
39 pub struct DiagnosticStyledString(pub Vec<StringPart>);
40
41 impl DiagnosticStyledString {
42     pub fn new() -> DiagnosticStyledString {
43         DiagnosticStyledString(vec![])
44     }
45     pub fn push_normal<S: Into<String>>(&mut self, t: S) {
46         self.0.push(StringPart::Normal(t.into()));
47     }
48     pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
49         self.0.push(StringPart::Highlighted(t.into()));
50     }
51     pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
52         DiagnosticStyledString(vec![StringPart::Normal(t.into())])
53     }
54
55     pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
56         DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
57     }
58
59     pub fn content(&self) -> String {
60         self.0.iter().map(|x| x.content()).collect::<String>()
61     }
62 }
63
64 #[derive(PartialEq, Eq)]
65 pub enum StringPart {
66     Normal(String),
67     Highlighted(String),
68 }
69
70 impl StringPart {
71     pub fn content(&self) -> String {
72         match self {
73             &StringPart::Normal(ref s) | & StringPart::Highlighted(ref s) => s.to_owned()
74         }
75     }
76 }
77
78 impl Diagnostic {
79     pub fn new(level: Level, message: &str) -> Self {
80         Diagnostic::new_with_code(level, None, message)
81     }
82
83     pub fn new_with_code(level: Level, code: Option<String>, message: &str) -> Self {
84         Diagnostic {
85             level: level,
86             message: vec![(message.to_owned(), Style::NoStyle)],
87             code: code,
88             span: MultiSpan::new(),
89             children: vec![],
90             suggestion: None,
91         }
92     }
93
94     /// Cancel the diagnostic (a structured diagnostic must either be emitted or
95     /// cancelled or it will panic when dropped).
96     /// BEWARE: if this DiagnosticBuilder is an error, then creating it will
97     /// bump the error count on the Handler and cancelling it won't undo that.
98     /// If you want to decrement the error count you should use `Handler::cancel`.
99     pub fn cancel(&mut self) {
100         self.level = Level::Cancelled;
101     }
102
103     pub fn cancelled(&self) -> bool {
104         self.level == Level::Cancelled
105     }
106
107     pub fn is_fatal(&self) -> bool {
108         self.level == Level::Fatal
109     }
110
111     /// Add a span/label to be included in the resulting snippet.
112     /// This is pushed onto the `MultiSpan` that was created when the
113     /// diagnostic was first built. If you don't call this function at
114     /// all, and you just supplied a `Span` to create the diagnostic,
115     /// then the snippet will just include that `Span`, which is
116     /// called the primary span.
117     pub fn span_label(&mut self, span: Span, label: &fmt::Display)
118                       -> &mut Self {
119         self.span.push_span_label(span, format!("{}", label));
120         self
121     }
122
123     pub fn note_expected_found(&mut self,
124                                label: &fmt::Display,
125                                expected: DiagnosticStyledString,
126                                found: DiagnosticStyledString)
127                                -> &mut Self
128     {
129         self.note_expected_found_extra(label, expected, found, &"", &"")
130     }
131
132     pub fn note_expected_found_extra(&mut self,
133                                      label: &fmt::Display,
134                                      expected: DiagnosticStyledString,
135                                      found: DiagnosticStyledString,
136                                      expected_extra: &fmt::Display,
137                                      found_extra: &fmt::Display)
138                                      -> &mut Self
139     {
140         let mut msg: Vec<_> = vec![(format!("expected {} `", label), Style::NoStyle)];
141         msg.extend(expected.0.iter()
142                    .map(|x| match *x {
143                        StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
144                        StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
145                    }));
146         msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
147         msg.push((format!("   found {} `", label), Style::NoStyle));
148         msg.extend(found.0.iter()
149                    .map(|x| match *x {
150                        StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
151                        StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
152                    }));
153         msg.push((format!("`{}", found_extra), Style::NoStyle));
154
155         // For now, just attach these as notes
156         self.highlighted_note(msg);
157         self
158     }
159
160     pub fn note(&mut self, msg: &str) -> &mut Self {
161         self.sub(Level::Note, msg, MultiSpan::new(), None);
162         self
163     }
164
165     pub fn highlighted_note(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
166         self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
167         self
168     }
169
170     pub fn span_note<S: Into<MultiSpan>>(&mut self,
171                                          sp: S,
172                                          msg: &str)
173                                          -> &mut Self {
174         self.sub(Level::Note, msg, sp.into(), None);
175         self
176     }
177
178     pub fn warn(&mut self, msg: &str) -> &mut Self {
179         self.sub(Level::Warning, msg, MultiSpan::new(), None);
180         self
181     }
182
183     pub fn span_warn<S: Into<MultiSpan>>(&mut self,
184                                          sp: S,
185                                          msg: &str)
186                                          -> &mut Self {
187         self.sub(Level::Warning, msg, sp.into(), None);
188         self
189     }
190
191     pub fn help(&mut self , msg: &str) -> &mut Self {
192         self.sub(Level::Help, msg, MultiSpan::new(), None);
193         self
194     }
195
196     pub fn span_help<S: Into<MultiSpan>>(&mut self,
197                                          sp: S,
198                                          msg: &str)
199                                          -> &mut Self {
200         self.sub(Level::Help, msg, sp.into(), None);
201         self
202     }
203
204     /// Prints out a message with a suggested edit of the code.
205     ///
206     /// See `diagnostic::CodeSuggestion` for more information.
207     pub fn span_suggestion(&mut self, sp: Span, msg: &str, suggestion: String) -> &mut Self {
208         assert!(self.suggestion.is_none());
209         self.suggestion = Some(CodeSuggestion {
210             msp: sp.into(),
211             substitutes: vec![suggestion],
212             msg: msg.to_owned(),
213         });
214         self
215     }
216
217     pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
218         self.span = sp.into();
219         self
220     }
221
222     pub fn code(&mut self, s: String) -> &mut Self {
223         self.code = Some(s);
224         self
225     }
226
227     pub fn message(&self) -> String {
228         self.message.iter().map(|i| i.0.to_owned()).collect::<String>()
229     }
230
231     pub fn styled_message(&self) -> &Vec<(String, Style)> {
232         &self.message
233     }
234
235     pub fn level(&self) -> Level {
236         self.level
237     }
238
239     /// Used by a lint. Copies over all details *but* the "main
240     /// message".
241     pub fn copy_details_not_message(&mut self, from: &Diagnostic) {
242         self.span = from.span.clone();
243         self.code = from.code.clone();
244         self.children.extend(from.children.iter().cloned())
245     }
246
247     /// Convenience function for internal use, clients should use one of the
248     /// public methods above.
249     fn sub(&mut self,
250            level: Level,
251            message: &str,
252            span: MultiSpan,
253            render_span: Option<RenderSpan>) {
254         let sub = SubDiagnostic {
255             level: level,
256             message: vec![(message.to_owned(), Style::NoStyle)],
257             span: span,
258             render_span: render_span,
259         };
260         self.children.push(sub);
261     }
262
263     /// Convenience function for internal use, clients should use one of the
264     /// public methods above.
265     fn sub_with_highlights(&mut self,
266                            level: Level,
267                            message: Vec<(String, Style)>,
268                            span: MultiSpan,
269                            render_span: Option<RenderSpan>) {
270         let sub = SubDiagnostic {
271             level: level,
272             message: message,
273             span: span,
274             render_span: render_span,
275         };
276         self.children.push(sub);
277     }
278 }
279
280 impl SubDiagnostic {
281     pub fn message(&self) -> String {
282         self.message.iter().map(|i| i.0.to_owned()).collect::<String>()
283     }
284
285     pub fn styled_message(&self) -> &Vec<(String, Style)> {
286         &self.message
287     }
288 }