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