]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/json.rs
Auto merge of #61212 - alexcrichton:skip-rustc, r=pietroalbini
[rust.git] / src / libsyntax / json.rs
1 //! A JSON emitter for errors.
2 //!
3 //! This works by converting errors to a simplified structural format (see the
4 //! structs at the start of the file) and then serializing them. These should
5 //! contain as much information about the error as possible.
6 //!
7 //! The format of the JSON output should be considered *unstable*. For now the
8 //! structs at the end of this file (Diagnostic*) specify the error format.
9
10 // FIXME: spec the JSON output properly.
11
12 use crate::source_map::{SourceMap, FilePathMapping};
13
14 use errors::registry::Registry;
15 use errors::{DiagnosticBuilder, SubDiagnostic, CodeSuggestion, SourceMapper};
16 use errors::{DiagnosticId, Applicability};
17 use errors::emitter::{Emitter, HumanReadableErrorType};
18
19 use syntax_pos::{MacroBacktrace, Span, SpanLabel, MultiSpan};
20 use rustc_data_structures::sync::{self, Lrc};
21 use std::io::{self, Write};
22 use std::path::Path;
23 use std::vec;
24 use std::sync::{Arc, Mutex};
25
26 use rustc_serialize::json::{as_json, as_pretty_json};
27
28 pub struct JsonEmitter {
29     dst: Box<dyn Write + Send>,
30     registry: Option<Registry>,
31     sm: Lrc<dyn SourceMapper + sync::Send + sync::Sync>,
32     pretty: bool,
33     ui_testing: bool,
34     json_rendered: HumanReadableErrorType,
35 }
36
37 impl JsonEmitter {
38     pub fn stderr(
39         registry: Option<Registry>,
40         source_map: Lrc<SourceMap>,
41         pretty: bool,
42         json_rendered: HumanReadableErrorType,
43     ) -> JsonEmitter {
44         JsonEmitter {
45             dst: Box::new(io::stderr()),
46             registry,
47             sm: source_map,
48             pretty,
49             ui_testing: false,
50             json_rendered,
51         }
52     }
53
54     pub fn basic(pretty: bool, json_rendered: HumanReadableErrorType) -> JsonEmitter {
55         let file_path_mapping = FilePathMapping::empty();
56         JsonEmitter::stderr(None, Lrc::new(SourceMap::new(file_path_mapping)),
57                             pretty, json_rendered)
58     }
59
60     pub fn new(
61         dst: Box<dyn Write + Send>,
62         registry: Option<Registry>,
63         source_map: Lrc<SourceMap>,
64         pretty: bool,
65         json_rendered: HumanReadableErrorType,
66     ) -> JsonEmitter {
67         JsonEmitter {
68             dst,
69             registry,
70             sm: source_map,
71             pretty,
72             ui_testing: false,
73             json_rendered,
74         }
75     }
76
77     pub fn ui_testing(self, ui_testing: bool) -> Self {
78         Self { ui_testing, ..self }
79     }
80 }
81
82 impl Emitter for JsonEmitter {
83     fn emit_diagnostic(&mut self, db: &DiagnosticBuilder<'_>) {
84         let data = Diagnostic::from_diagnostic_builder(db, self);
85         let result = if self.pretty {
86             writeln!(&mut self.dst, "{}", as_pretty_json(&data))
87         } else {
88             writeln!(&mut self.dst, "{}", as_json(&data))
89         };
90         if let Err(e) = result {
91             panic!("failed to print diagnostics: {:?}", e);
92         }
93     }
94
95     fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
96         let data = ArtifactNotification { artifact: path, emit: artifact_type };
97         let result = if self.pretty {
98             writeln!(&mut self.dst, "{}", as_pretty_json(&data))
99         } else {
100             writeln!(&mut self.dst, "{}", as_json(&data))
101         };
102         if let Err(e) = result {
103             panic!("failed to print notification: {:?}", e);
104         }
105     }
106 }
107
108 // The following data types are provided just for serialisation.
109
110 #[derive(RustcEncodable)]
111 struct Diagnostic {
112     /// The primary error message.
113     message: String,
114     code: Option<DiagnosticCode>,
115     /// "error: internal compiler error", "error", "warning", "note", "help".
116     level: &'static str,
117     spans: Vec<DiagnosticSpan>,
118     /// Associated diagnostic messages.
119     children: Vec<Diagnostic>,
120     /// The message as rustc would render it.
121     rendered: Option<String>,
122 }
123
124 #[derive(RustcEncodable)]
125 #[allow(unused_attributes)]
126 struct DiagnosticSpan {
127     file_name: String,
128     byte_start: u32,
129     byte_end: u32,
130     /// 1-based.
131     line_start: usize,
132     line_end: usize,
133     /// 1-based, character offset.
134     column_start: usize,
135     column_end: usize,
136     /// Is this a "primary" span -- meaning the point, or one of the points,
137     /// where the error occurred?
138     is_primary: bool,
139     /// Source text from the start of line_start to the end of line_end.
140     text: Vec<DiagnosticSpanLine>,
141     /// Label that should be placed at this location (if any)
142     label: Option<String>,
143     /// If we are suggesting a replacement, this will contain text
144     /// that should be sliced in atop this span.
145     suggested_replacement: Option<String>,
146     /// If the suggestion is approximate
147     suggestion_applicability: Option<Applicability>,
148     /// Macro invocations that created the code at this span, if any.
149     expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
150 }
151
152 #[derive(RustcEncodable)]
153 struct DiagnosticSpanLine {
154     text: String,
155
156     /// 1-based, character offset in self.text.
157     highlight_start: usize,
158
159     highlight_end: usize,
160 }
161
162 #[derive(RustcEncodable)]
163 struct DiagnosticSpanMacroExpansion {
164     /// span where macro was applied to generate this code; note that
165     /// this may itself derive from a macro (if
166     /// `span.expansion.is_some()`)
167     span: DiagnosticSpan,
168
169     /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
170     macro_decl_name: String,
171
172     /// span where macro was defined (if known)
173     def_site_span: Option<DiagnosticSpan>,
174 }
175
176 #[derive(RustcEncodable)]
177 struct DiagnosticCode {
178     /// The code itself.
179     code: String,
180     /// An explanation for the code.
181     explanation: Option<&'static str>,
182 }
183
184 #[derive(RustcEncodable)]
185 struct ArtifactNotification<'a> {
186     /// The path of the artifact.
187     artifact: &'a Path,
188     /// What kind of artifact we're emitting.
189     emit: &'a str,
190 }
191
192 impl Diagnostic {
193     fn from_diagnostic_builder(db: &DiagnosticBuilder<'_>,
194                                je: &JsonEmitter)
195                                -> Diagnostic {
196         let sugg = db.suggestions.iter().map(|sugg| {
197             Diagnostic {
198                 message: sugg.msg.clone(),
199                 code: None,
200                 level: "help",
201                 spans: DiagnosticSpan::from_suggestion(sugg, je),
202                 children: vec![],
203                 rendered: None,
204             }
205         });
206
207         // generate regular command line output and store it in the json
208
209         // A threadsafe buffer for writing.
210         #[derive(Default, Clone)]
211         struct BufWriter(Arc<Mutex<Vec<u8>>>);
212
213         impl Write for BufWriter {
214             fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
215                 self.0.lock().unwrap().write(buf)
216             }
217             fn flush(&mut self) -> io::Result<()> {
218                 self.0.lock().unwrap().flush()
219             }
220         }
221         let buf = BufWriter::default();
222         let output = buf.clone();
223         je.json_rendered.new_emitter(Box::new(buf), Some(je.sm.clone()), false)
224             .ui_testing(je.ui_testing).emit_diagnostic(db);
225         let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
226         let output = String::from_utf8(output).unwrap();
227
228         Diagnostic {
229             message: db.message(),
230             code: DiagnosticCode::map_opt_string(db.code.clone(), je),
231             level: db.level.to_str(),
232             spans: DiagnosticSpan::from_multispan(&db.span, je),
233             children: db.children.iter().map(|c| {
234                 Diagnostic::from_sub_diagnostic(c, je)
235             }).chain(sugg).collect(),
236             rendered: Some(output),
237         }
238     }
239
240     fn from_sub_diagnostic(db: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic {
241         Diagnostic {
242             message: db.message(),
243             code: None,
244             level: db.level.to_str(),
245             spans: db.render_span.as_ref()
246                      .map(|sp| DiagnosticSpan::from_multispan(sp, je))
247                      .unwrap_or_else(|| DiagnosticSpan::from_multispan(&db.span, je)),
248             children: vec![],
249             rendered: None,
250         }
251     }
252 }
253
254 impl DiagnosticSpan {
255     fn from_span_label(span: SpanLabel,
256                        suggestion: Option<(&String, Applicability)>,
257                        je: &JsonEmitter)
258                        -> DiagnosticSpan {
259         Self::from_span_etc(span.span,
260                             span.is_primary,
261                             span.label,
262                             suggestion,
263                             je)
264     }
265
266     fn from_span_etc(span: Span,
267                      is_primary: bool,
268                      label: Option<String>,
269                      suggestion: Option<(&String, Applicability)>,
270                      je: &JsonEmitter)
271                      -> DiagnosticSpan {
272         // obtain the full backtrace from the `macro_backtrace`
273         // helper; in some ways, it'd be better to expand the
274         // backtrace ourselves, but the `macro_backtrace` helper makes
275         // some decision, such as dropping some frames, and I don't
276         // want to duplicate that logic here.
277         let backtrace = span.macro_backtrace().into_iter();
278         DiagnosticSpan::from_span_full(span,
279                                        is_primary,
280                                        label,
281                                        suggestion,
282                                        backtrace,
283                                        je)
284     }
285
286     fn from_span_full(span: Span,
287                       is_primary: bool,
288                       label: Option<String>,
289                       suggestion: Option<(&String, Applicability)>,
290                       mut backtrace: vec::IntoIter<MacroBacktrace>,
291                       je: &JsonEmitter)
292                       -> DiagnosticSpan {
293         let start = je.sm.lookup_char_pos(span.lo());
294         let end = je.sm.lookup_char_pos(span.hi());
295         let backtrace_step = backtrace.next().map(|bt| {
296             let call_site =
297                 Self::from_span_full(bt.call_site,
298                                      false,
299                                      None,
300                                      None,
301                                      backtrace,
302                                      je);
303             let def_site_span = bt.def_site_span.map(|sp| {
304                 Self::from_span_full(sp,
305                                      false,
306                                      None,
307                                      None,
308                                      vec![].into_iter(),
309                                      je)
310             });
311             Box::new(DiagnosticSpanMacroExpansion {
312                 span: call_site,
313                 macro_decl_name: bt.macro_decl_name,
314                 def_site_span,
315             })
316         });
317
318         DiagnosticSpan {
319             file_name: start.file.name.to_string(),
320             byte_start: span.lo().0 - start.file.start_pos.0,
321             byte_end: span.hi().0 - start.file.start_pos.0,
322             line_start: start.line,
323             line_end: end.line,
324             column_start: start.col.0 + 1,
325             column_end: end.col.0 + 1,
326             is_primary,
327             text: DiagnosticSpanLine::from_span(span, je),
328             suggested_replacement: suggestion.map(|x| x.0.clone()),
329             suggestion_applicability: suggestion.map(|x| x.1),
330             expansion: backtrace_step,
331             label,
332         }
333     }
334
335     fn from_multispan(msp: &MultiSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
336         msp.span_labels()
337            .into_iter()
338            .map(|span_str| Self::from_span_label(span_str, None, je))
339            .collect()
340     }
341
342     fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter)
343                        -> Vec<DiagnosticSpan> {
344         suggestion.substitutions
345                       .iter()
346                       .flat_map(|substitution| {
347                           substitution.parts.iter().map(move |suggestion_inner| {
348                               let span_label = SpanLabel {
349                                   span: suggestion_inner.span,
350                                   is_primary: true,
351                                   label: None,
352                               };
353                               DiagnosticSpan::from_span_label(span_label,
354                                                               Some((&suggestion_inner.snippet,
355                                                                    suggestion.applicability)),
356                                                               je)
357                           })
358                       })
359                       .collect()
360     }
361 }
362
363 impl DiagnosticSpanLine {
364     fn line_from_source_file(fm: &syntax_pos::SourceFile,
365                          index: usize,
366                          h_start: usize,
367                          h_end: usize)
368                          -> DiagnosticSpanLine {
369         DiagnosticSpanLine {
370             text: fm.get_line(index).map_or(String::new(), |l| l.into_owned()),
371             highlight_start: h_start,
372             highlight_end: h_end,
373         }
374     }
375
376     /// Creates a list of DiagnosticSpanLines from span - each line with any part
377     /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
378     /// `span` within the line.
379     fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
380         je.sm.span_to_lines(span)
381             .map(|lines| {
382                 let fm = &*lines.file;
383                 lines.lines
384                     .iter()
385                     .map(|line| DiagnosticSpanLine::line_from_source_file(
386                         fm,
387                         line.line_index,
388                         line.start_col.0 + 1,
389                         line.end_col.0 + 1,
390                     )).collect()
391             }).unwrap_or_else(|_| vec![])
392     }
393 }
394
395 impl DiagnosticCode {
396     fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
397         s.map(|s| {
398             let s = match s {
399                 DiagnosticId::Error(s) => s,
400                 DiagnosticId::Lint(s) => s,
401             };
402             let explanation = je.registry
403                                 .as_ref()
404                                 .and_then(|registry| registry.find_description(&s));
405
406             DiagnosticCode {
407                 code: s,
408                 explanation,
409             }
410         })
411     }
412 }