]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/json.rs
Auto merge of #41542 - petrochenkov:objpars2, r=nikomatsakis
[rust.git] / src / libsyntax / json.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 //! A JSON emitter for errors.
12 //!
13 //! This works by converting errors to a simplified structural format (see the
14 //! structs at the start of the file) and then serialising them. These should
15 //! contain as much information about the error as possible.
16 //!
17 //! The format of the JSON output should be considered *unstable*. For now the
18 //! structs at the end of this file (Diagnostic*) specify the error format.
19
20 // FIXME spec the JSON output properly.
21
22 use codemap::{CodeMap, FilePathMapping};
23 use syntax_pos::{self, MacroBacktrace, Span, SpanLabel, MultiSpan};
24 use errors::registry::Registry;
25 use errors::{DiagnosticBuilder, SubDiagnostic, RenderSpan, CodeSuggestion, CodeMapper};
26 use errors::emitter::Emitter;
27
28 use std::rc::Rc;
29 use std::io::{self, Write};
30 use std::vec;
31
32 use rustc_serialize::json::as_json;
33
34 pub struct JsonEmitter {
35     dst: Box<Write + Send>,
36     registry: Option<Registry>,
37     cm: Rc<CodeMapper + 'static>,
38 }
39
40 impl JsonEmitter {
41     pub fn stderr(registry: Option<Registry>,
42                   code_map: Rc<CodeMap>) -> JsonEmitter {
43         JsonEmitter {
44             dst: Box::new(io::stderr()),
45             registry: registry,
46             cm: code_map,
47         }
48     }
49
50     pub fn basic() -> JsonEmitter {
51         let file_path_mapping = FilePathMapping::empty();
52         JsonEmitter::stderr(None, Rc::new(CodeMap::new(file_path_mapping)))
53     }
54
55     pub fn new(dst: Box<Write + Send>,
56                registry: Option<Registry>,
57                code_map: Rc<CodeMap>) -> JsonEmitter {
58         JsonEmitter {
59             dst: dst,
60             registry: registry,
61             cm: code_map,
62         }
63     }
64 }
65
66 impl Emitter for JsonEmitter {
67     fn emit(&mut self, db: &DiagnosticBuilder) {
68         let data = Diagnostic::from_diagnostic_builder(db, self);
69         if let Err(e) = writeln!(&mut self.dst, "{}", as_json(&data)) {
70             panic!("failed to print diagnostics: {:?}", e);
71         }
72     }
73 }
74
75 // The following data types are provided just for serialisation.
76
77 #[derive(RustcEncodable)]
78 struct Diagnostic {
79     /// The primary error message.
80     message: String,
81     code: Option<DiagnosticCode>,
82     /// "error: internal compiler error", "error", "warning", "note", "help".
83     level: &'static str,
84     spans: Vec<DiagnosticSpan>,
85     /// Associated diagnostic messages.
86     children: Vec<Diagnostic>,
87     /// The message as rustc would render it. Currently this is only
88     /// `Some` for "suggestions", but eventually it will include all
89     /// snippets.
90     rendered: Option<String>,
91 }
92
93 #[derive(RustcEncodable)]
94 struct DiagnosticSpan {
95     file_name: String,
96     byte_start: u32,
97     byte_end: u32,
98     /// 1-based.
99     line_start: usize,
100     line_end: usize,
101     /// 1-based, character offset.
102     column_start: usize,
103     column_end: usize,
104     /// Is this a "primary" span -- meaning the point, or one of the points,
105     /// where the error occurred?
106     is_primary: bool,
107     /// Source text from the start of line_start to the end of line_end.
108     text: Vec<DiagnosticSpanLine>,
109     /// Label that should be placed at this location (if any)
110     label: Option<String>,
111     /// If we are suggesting a replacement, this will contain text
112     /// that should be sliced in atop this span. You may prefer to
113     /// load the fully rendered version from the parent `Diagnostic`,
114     /// however.
115     suggested_replacement: Option<String>,
116     /// Macro invocations that created the code at this span, if any.
117     expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
118 }
119
120 #[derive(RustcEncodable)]
121 struct DiagnosticSpanLine {
122     text: String,
123
124     /// 1-based, character offset in self.text.
125     highlight_start: usize,
126
127     highlight_end: usize,
128 }
129
130 #[derive(RustcEncodable)]
131 struct DiagnosticSpanMacroExpansion {
132     /// span where macro was applied to generate this code; note that
133     /// this may itself derive from a macro (if
134     /// `span.expansion.is_some()`)
135     span: DiagnosticSpan,
136
137     /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
138     macro_decl_name: String,
139
140     /// span where macro was defined (if known)
141     def_site_span: Option<DiagnosticSpan>,
142 }
143
144 #[derive(RustcEncodable)]
145 struct DiagnosticCode {
146     /// The code itself.
147     code: String,
148     /// An explanation for the code.
149     explanation: Option<&'static str>,
150 }
151
152 impl Diagnostic {
153     fn from_diagnostic_builder(db: &DiagnosticBuilder,
154                                je: &JsonEmitter)
155                                -> Diagnostic {
156         Diagnostic {
157             message: db.message(),
158             code: DiagnosticCode::map_opt_string(db.code.clone(), je),
159             level: db.level.to_str(),
160             spans: DiagnosticSpan::from_multispan(&db.span, je),
161             children: db.children.iter().map(|c| {
162                 Diagnostic::from_sub_diagnostic(c, je)
163             }).collect(),
164             rendered: None,
165         }
166     }
167
168     fn from_sub_diagnostic(db: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic {
169         Diagnostic {
170             message: db.message(),
171             code: None,
172             level: db.level.to_str(),
173             spans: db.render_span.as_ref()
174                      .map(|sp| DiagnosticSpan::from_render_span(sp, je))
175                      .unwrap_or_else(|| DiagnosticSpan::from_multispan(&db.span, je)),
176             children: vec![],
177             rendered: db.render_span.as_ref()
178                                     .and_then(|rsp| je.render(rsp)),
179         }
180     }
181 }
182
183 impl DiagnosticSpan {
184     fn from_span_label(span: SpanLabel,
185                        suggestion: Option<&String>,
186                        je: &JsonEmitter)
187                        -> DiagnosticSpan {
188         Self::from_span_etc(span.span,
189                             span.is_primary,
190                             span.label,
191                             suggestion,
192                             je)
193     }
194
195     fn from_span_etc(span: Span,
196                      is_primary: bool,
197                      label: Option<String>,
198                      suggestion: Option<&String>,
199                      je: &JsonEmitter)
200                      -> DiagnosticSpan {
201         // obtain the full backtrace from the `macro_backtrace`
202         // helper; in some ways, it'd be better to expand the
203         // backtrace ourselves, but the `macro_backtrace` helper makes
204         // some decision, such as dropping some frames, and I don't
205         // want to duplicate that logic here.
206         let backtrace = span.macro_backtrace().into_iter();
207         DiagnosticSpan::from_span_full(span,
208                                        is_primary,
209                                        label,
210                                        suggestion,
211                                        backtrace,
212                                        je)
213     }
214
215     fn from_span_full(span: Span,
216                       is_primary: bool,
217                       label: Option<String>,
218                       suggestion: Option<&String>,
219                       mut backtrace: vec::IntoIter<MacroBacktrace>,
220                       je: &JsonEmitter)
221                       -> DiagnosticSpan {
222         let start = je.cm.lookup_char_pos(span.lo);
223         let end = je.cm.lookup_char_pos(span.hi);
224         let backtrace_step = backtrace.next().map(|bt| {
225             let call_site =
226                 Self::from_span_full(bt.call_site,
227                                      false,
228                                      None,
229                                      None,
230                                      backtrace,
231                                      je);
232             let def_site_span = bt.def_site_span.map(|sp| {
233                 Self::from_span_full(sp,
234                                      false,
235                                      None,
236                                      None,
237                                      vec![].into_iter(),
238                                      je)
239             });
240             Box::new(DiagnosticSpanMacroExpansion {
241                 span: call_site,
242                 macro_decl_name: bt.macro_decl_name,
243                 def_site_span: def_site_span,
244             })
245         });
246         DiagnosticSpan {
247             file_name: start.file.name.clone(),
248             byte_start: span.lo.0,
249             byte_end: span.hi.0,
250             line_start: start.line,
251             line_end: end.line,
252             column_start: start.col.0 + 1,
253             column_end: end.col.0 + 1,
254             is_primary: is_primary,
255             text: DiagnosticSpanLine::from_span(span, je),
256             suggested_replacement: suggestion.cloned(),
257             expansion: backtrace_step,
258             label: label,
259         }
260     }
261
262     fn from_multispan(msp: &MultiSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
263         msp.span_labels()
264            .into_iter()
265            .map(|span_str| Self::from_span_label(span_str, None, je))
266            .collect()
267     }
268
269     fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter)
270                        -> Vec<DiagnosticSpan> {
271         assert_eq!(suggestion.msp.span_labels().len(), suggestion.substitutes.len());
272         suggestion.msp.span_labels()
273                       .into_iter()
274                       .zip(&suggestion.substitutes)
275                       .map(|(span_label, suggestion)| {
276                           DiagnosticSpan::from_span_label(span_label,
277                                                           Some(suggestion),
278                                                           je)
279                       })
280                       .collect()
281     }
282
283     fn from_render_span(rsp: &RenderSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
284         match *rsp {
285             RenderSpan::FullSpan(ref msp) =>
286                 DiagnosticSpan::from_multispan(msp, je),
287             RenderSpan::Suggestion(ref suggestion) =>
288                 DiagnosticSpan::from_suggestion(suggestion, je),
289         }
290     }
291 }
292
293 impl DiagnosticSpanLine {
294     fn line_from_filemap(fm: &syntax_pos::FileMap,
295                          index: usize,
296                          h_start: usize,
297                          h_end: usize)
298                          -> DiagnosticSpanLine {
299         DiagnosticSpanLine {
300             text: fm.get_line(index).unwrap_or("").to_owned(),
301             highlight_start: h_start,
302             highlight_end: h_end,
303         }
304     }
305
306     /// Create a list of DiagnosticSpanLines from span - each line with any part
307     /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
308     /// `span` within the line.
309     fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
310         je.cm.span_to_lines(span)
311              .map(|lines| {
312                  let fm = &*lines.file;
313                  lines.lines
314                       .iter()
315                       .map(|line| {
316                           DiagnosticSpanLine::line_from_filemap(fm,
317                                                                 line.line_index,
318                                                                 line.start_col.0 + 1,
319                                                                 line.end_col.0 + 1)
320                       })
321                      .collect()
322              })
323             .unwrap_or(vec![])
324     }
325 }
326
327 impl DiagnosticCode {
328     fn map_opt_string(s: Option<String>, je: &JsonEmitter) -> Option<DiagnosticCode> {
329         s.map(|s| {
330
331             let explanation = je.registry
332                                 .as_ref()
333                                 .and_then(|registry| registry.find_description(&s));
334
335             DiagnosticCode {
336                 code: s,
337                 explanation: explanation,
338             }
339         })
340     }
341 }
342
343 impl JsonEmitter {
344     fn render(&self, render_span: &RenderSpan) -> Option<String> {
345         use std::borrow::Borrow;
346
347         match *render_span {
348             RenderSpan::FullSpan(_) => {
349                 None
350             }
351             RenderSpan::Suggestion(ref suggestion) => {
352                 Some(suggestion.splice_lines(self.cm.borrow()))
353             }
354         }
355     }
356 }
357