]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/diagnostic.rs
861880aa265ec140a1072f8b25a12bc211c827e6
[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 Substitution;
13 use Level;
14 use RenderSpan;
15 use std::fmt;
16 use syntax_pos::{MultiSpan, Span};
17 use snippet::Style;
18
19 #[must_use]
20 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
21 pub struct Diagnostic {
22     pub level: Level,
23     pub message: Vec<(String, Style)>,
24     pub code: Option<String>,
25     pub span: MultiSpan,
26     pub children: Vec<SubDiagnostic>,
27     pub suggestions: Vec<CodeSuggestion>,
28 }
29
30 /// For example a note attached to an error.
31 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable)]
32 pub struct SubDiagnostic {
33     pub level: Level,
34     pub message: Vec<(String, Style)>,
35     pub span: MultiSpan,
36     pub render_span: Option<RenderSpan>,
37 }
38
39 #[derive(PartialEq, Eq)]
40 pub struct DiagnosticStyledString(pub Vec<StringPart>);
41
42 impl DiagnosticStyledString {
43     pub fn new() -> DiagnosticStyledString {
44         DiagnosticStyledString(vec![])
45     }
46     pub fn push_normal<S: Into<String>>(&mut self, t: S) {
47         self.0.push(StringPart::Normal(t.into()));
48     }
49     pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
50         self.0.push(StringPart::Highlighted(t.into()));
51     }
52     pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
53         DiagnosticStyledString(vec![StringPart::Normal(t.into())])
54     }
55
56     pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
57         DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
58     }
59
60     pub fn content(&self) -> String {
61         self.0.iter().map(|x| x.content()).collect::<String>()
62     }
63 }
64
65 #[derive(PartialEq, Eq)]
66 pub enum StringPart {
67     Normal(String),
68     Highlighted(String),
69 }
70
71 impl StringPart {
72     pub fn content(&self) -> String {
73         match self {
74             &StringPart::Normal(ref s) | & StringPart::Highlighted(ref s) => s.to_owned()
75         }
76     }
77 }
78
79 impl Diagnostic {
80     pub fn new(level: Level, message: &str) -> Self {
81         Diagnostic::new_with_code(level, None, message)
82     }
83
84     pub fn new_with_code(level: Level, code: Option<String>, message: &str) -> Self {
85         Diagnostic {
86             level: level,
87             message: vec![(message.to_owned(), Style::NoStyle)],
88             code: code,
89             span: MultiSpan::new(),
90             children: vec![],
91             suggestions: vec![],
92         }
93     }
94
95     /// Cancel the diagnostic (a structured diagnostic must either be emitted or
96     /// cancelled or it will panic when dropped).
97     /// BEWARE: if this DiagnosticBuilder is an error, then creating it will
98     /// bump the error count on the Handler and cancelling it won't undo that.
99     /// If you want to decrement the error count you should use `Handler::cancel`.
100     pub fn cancel(&mut self) {
101         self.level = Level::Cancelled;
102     }
103
104     pub fn cancelled(&self) -> bool {
105         self.level == Level::Cancelled
106     }
107
108     pub fn is_fatal(&self) -> bool {
109         self.level == Level::Fatal
110     }
111
112     /// Add a span/label to be included in the resulting snippet.
113     /// This is pushed onto the `MultiSpan` that was created when the
114     /// diagnostic was first built. If you don't call this function at
115     /// all, and you just supplied a `Span` to create the diagnostic,
116     /// then the snippet will just include that `Span`, which is
117     /// called the primary span.
118     pub fn span_label<T: Into<String>>(&mut self, span: Span, label: T) -> &mut Self {
119         self.span.push_span_label(span, label.into());
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         self.suggestions.push(CodeSuggestion {
209             substitution_parts: vec![Substitution {
210                 span: sp,
211                 substitutions: vec![suggestion],
212             }],
213             msg: msg.to_owned(),
214         });
215         self
216     }
217
218     pub fn span_suggestions(&mut self, sp: Span, msg: &str, suggestions: Vec<String>) -> &mut Self {
219         self.suggestions.push(CodeSuggestion {
220             substitution_parts: vec![Substitution {
221                 span: sp,
222                 substitutions: suggestions,
223             }],
224             msg: msg.to_owned(),
225         });
226         self
227     }
228
229     pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
230         self.span = sp.into();
231         self
232     }
233
234     pub fn code(&mut self, s: String) -> &mut Self {
235         self.code = Some(s);
236         self
237     }
238
239     pub fn message(&self) -> String {
240         self.message.iter().map(|i| i.0.to_owned()).collect::<String>()
241     }
242
243     pub fn styled_message(&self) -> &Vec<(String, Style)> {
244         &self.message
245     }
246
247     pub fn level(&self) -> Level {
248         self.level
249     }
250
251     /// Used by a lint. Copies over all details *but* the "main
252     /// message".
253     pub fn copy_details_not_message(&mut self, from: &Diagnostic) {
254         self.span = from.span.clone();
255         self.code = from.code.clone();
256         self.children.extend(from.children.iter().cloned())
257     }
258
259     /// Convenience function for internal use, clients should use one of the
260     /// public methods above.
261     fn sub(&mut self,
262            level: Level,
263            message: &str,
264            span: MultiSpan,
265            render_span: Option<RenderSpan>) {
266         let sub = SubDiagnostic {
267             level: level,
268             message: vec![(message.to_owned(), Style::NoStyle)],
269             span: span,
270             render_span: render_span,
271         };
272         self.children.push(sub);
273     }
274
275     /// Convenience function for internal use, clients should use one of the
276     /// public methods above.
277     fn sub_with_highlights(&mut self,
278                            level: Level,
279                            message: Vec<(String, Style)>,
280                            span: MultiSpan,
281                            render_span: Option<RenderSpan>) {
282         let sub = SubDiagnostic {
283             level: level,
284             message: message,
285             span: span,
286             render_span: render_span,
287         };
288         self.children.push(sub);
289     }
290 }
291
292 impl SubDiagnostic {
293     pub fn message(&self) -> String {
294         self.message.iter().map(|i| i.0.to_owned()).collect::<String>()
295     }
296
297     pub fn styled_message(&self) -> &Vec<(String, Style)> {
298         &self.message
299     }
300 }