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