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