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