1 //! A JSON emitter for errors.
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.
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.
10 // FIXME: spec the JSON output properly.
12 use rustc_span::source_map::{FilePathMapping, SourceMap};
14 use crate::emitter::{Emitter, HumanReadableErrorType};
15 use crate::registry::Registry;
16 use crate::DiagnosticId;
17 use crate::ToolMetadata;
18 use crate::{CodeSuggestion, SubDiagnostic};
19 use rustc_lint_defs::{Applicability, FutureBreakage};
21 use rustc_data_structures::sync::Lrc;
22 use rustc_span::hygiene::ExpnData;
23 use rustc_span::{MultiSpan, Span, SpanLabel};
24 use std::io::{self, Write};
26 use std::sync::{Arc, Mutex};
29 use rustc_serialize::json::{as_json, as_pretty_json};
30 use rustc_serialize::{Encodable, Encoder};
35 pub struct JsonEmitter {
36 dst: Box<dyn Write + Send>,
37 registry: Option<Registry>,
41 json_rendered: HumanReadableErrorType,
42 terminal_width: Option<usize>,
43 macro_backtrace: bool,
48 registry: Option<Registry>,
49 source_map: Lrc<SourceMap>,
51 json_rendered: HumanReadableErrorType,
52 terminal_width: Option<usize>,
53 macro_backtrace: bool,
56 dst: Box::new(io::BufWriter::new(io::stderr())),
69 json_rendered: HumanReadableErrorType,
70 terminal_width: Option<usize>,
71 macro_backtrace: bool,
73 let file_path_mapping = FilePathMapping::empty();
76 Lrc::new(SourceMap::new(file_path_mapping)),
85 dst: Box<dyn Write + Send>,
86 registry: Option<Registry>,
87 source_map: Lrc<SourceMap>,
89 json_rendered: HumanReadableErrorType,
90 terminal_width: Option<usize>,
91 macro_backtrace: bool,
105 pub fn ui_testing(self, ui_testing: bool) -> Self {
106 Self { ui_testing, ..self }
110 impl Emitter for JsonEmitter {
111 fn emit_diagnostic(&mut self, diag: &crate::Diagnostic) {
112 let data = Diagnostic::from_errors_diagnostic(diag, self);
113 let result = if self.pretty {
114 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
116 writeln!(&mut self.dst, "{}", as_json(&data))
118 .and_then(|_| self.dst.flush());
119 if let Err(e) = result {
120 panic!("failed to print diagnostics: {:?}", e);
124 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
125 let data = ArtifactNotification { artifact: path, emit: artifact_type };
126 let result = if self.pretty {
127 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
129 writeln!(&mut self.dst, "{}", as_json(&data))
131 .and_then(|_| self.dst.flush());
132 if let Err(e) = result {
133 panic!("failed to print notification: {:?}", e);
137 fn emit_future_breakage_report(&mut self, diags: Vec<(FutureBreakage, crate::Diagnostic)>) {
138 let data: Vec<FutureBreakageItem> = diags
140 .map(|(breakage, mut diag)| {
141 if diag.level == crate::Level::Allow {
142 diag.level = crate::Level::Warning;
145 future_breakage_date: breakage.date,
146 diagnostic: Diagnostic::from_errors_diagnostic(&diag, self),
150 let report = FutureIncompatReport { future_incompat_report: data };
151 let result = if self.pretty {
152 writeln!(&mut self.dst, "{}", as_pretty_json(&report))
154 writeln!(&mut self.dst, "{}", as_json(&report))
156 .and_then(|_| self.dst.flush());
157 if let Err(e) = result {
158 panic!("failed to print future breakage report: {:?}", e);
162 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
166 fn should_show_explain(&self) -> bool {
167 !matches!(self.json_rendered, HumanReadableErrorType::Short(_))
171 // The following data types are provided just for serialisation.
173 // NOTE: this has a manual implementation of Encodable which needs to be updated in
176 /// The primary error message.
178 code: Option<DiagnosticCode>,
179 /// "error: internal compiler error", "error", "warning", "note", "help".
181 spans: Vec<DiagnosticSpan>,
182 /// Associated diagnostic messages.
183 children: Vec<Diagnostic>,
184 /// The message as rustc would render it.
185 rendered: Option<String>,
186 /// Extra tool metadata
187 tool_metadata: ToolMetadata,
190 macro_rules! encode_fields {
192 $enc:expr, // encoder
193 $idx:expr, // starting field index
194 $struct:expr, // struct we're serializing
195 $struct_name:ident, // struct name
196 [ $($name:ident),+$(,)? ], // fields to encode
197 [ $($ignore:ident),+$(,)? ] // fields we're skipping
200 // Pattern match to make sure all fields are accounted for
201 let $struct_name { $($name,)+ $($ignore: _,)+ } = $struct;
204 $enc.emit_struct_field(
207 |enc| $name.encode(enc),
216 // Special-case encoder to skip tool_metadata if not set
217 impl<E: Encoder> Encodable<E> for Diagnostic {
218 fn encode(&self, s: &mut E) -> Result<(), E::Error> {
219 s.emit_struct("diagnostic", 7, |s| {
222 idx = encode_fields!(
227 [message, code, level, spans, children, rendered],
230 if self.tool_metadata.is_set() {
231 idx = encode_fields!(
237 [message, code, level, spans, children, rendered]
248 struct DiagnosticSpan {
255 /// 1-based, character offset.
258 /// Is this a "primary" span -- meaning the point, or one of the points,
259 /// where the error occurred?
261 /// Source text from the start of line_start to the end of line_end.
262 text: Vec<DiagnosticSpanLine>,
263 /// Label that should be placed at this location (if any)
264 label: Option<String>,
265 /// If we are suggesting a replacement, this will contain text
266 /// that should be sliced in atop this span.
267 suggested_replacement: Option<String>,
268 /// If the suggestion is approximate
269 suggestion_applicability: Option<Applicability>,
270 /// Macro invocations that created the code at this span, if any.
271 expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
275 struct DiagnosticSpanLine {
278 /// 1-based, character offset in self.text.
279 highlight_start: usize,
281 highlight_end: usize,
285 struct DiagnosticSpanMacroExpansion {
286 /// span where macro was applied to generate this code; note that
287 /// this may itself derive from a macro (if
288 /// `span.expansion.is_some()`)
289 span: DiagnosticSpan,
291 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
292 macro_decl_name: String,
294 /// span where macro was defined (if known)
295 def_site_span: DiagnosticSpan,
299 struct DiagnosticCode {
302 /// An explanation for the code.
303 explanation: Option<&'static str>,
307 struct ArtifactNotification<'a> {
308 /// The path of the artifact.
310 /// What kind of artifact we're emitting.
315 struct FutureBreakageItem {
316 future_breakage_date: Option<&'static str>,
317 diagnostic: Diagnostic,
321 struct FutureIncompatReport {
322 future_incompat_report: Vec<FutureBreakageItem>,
326 fn from_errors_diagnostic(diag: &crate::Diagnostic, je: &JsonEmitter) -> Diagnostic {
327 let sugg = diag.suggestions.iter().map(|sugg| Diagnostic {
328 message: sugg.msg.clone(),
331 spans: DiagnosticSpan::from_suggestion(sugg, je),
334 tool_metadata: sugg.tool_metadata.clone(),
337 // generate regular command line output and store it in the json
339 // A threadsafe buffer for writing.
340 #[derive(Default, Clone)]
341 struct BufWriter(Arc<Mutex<Vec<u8>>>);
343 impl Write for BufWriter {
344 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
345 self.0.lock().unwrap().write(buf)
347 fn flush(&mut self) -> io::Result<()> {
348 self.0.lock().unwrap().flush()
351 let buf = BufWriter::default();
352 let output = buf.clone();
361 .ui_testing(je.ui_testing)
362 .emit_diagnostic(diag);
363 let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
364 let output = String::from_utf8(output).unwrap();
367 message: diag.message(),
368 code: DiagnosticCode::map_opt_string(diag.code.clone(), je),
369 level: diag.level.to_str(),
370 spans: DiagnosticSpan::from_multispan(&diag.span, je),
374 .map(|c| Diagnostic::from_sub_diagnostic(c, je))
377 rendered: Some(output),
378 tool_metadata: ToolMetadata::default(),
382 fn from_sub_diagnostic(diag: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic {
384 message: diag.message(),
386 level: diag.level.to_str(),
390 .map(|sp| DiagnosticSpan::from_multispan(sp, je))
391 .unwrap_or_else(|| DiagnosticSpan::from_multispan(&diag.span, je)),
394 tool_metadata: ToolMetadata::default(),
399 impl DiagnosticSpan {
402 suggestion: Option<(&String, Applicability)>,
404 ) -> DiagnosticSpan {
405 Self::from_span_etc(span.span, span.is_primary, span.label, suggestion, je)
411 label: Option<String>,
412 suggestion: Option<(&String, Applicability)>,
414 ) -> DiagnosticSpan {
415 // obtain the full backtrace from the `macro_backtrace`
416 // helper; in some ways, it'd be better to expand the
417 // backtrace ourselves, but the `macro_backtrace` helper makes
418 // some decision, such as dropping some frames, and I don't
419 // want to duplicate that logic here.
420 let backtrace = span.macro_backtrace();
421 DiagnosticSpan::from_span_full(span, is_primary, label, suggestion, backtrace, je)
427 label: Option<String>,
428 suggestion: Option<(&String, Applicability)>,
429 mut backtrace: impl Iterator<Item = ExpnData>,
431 ) -> DiagnosticSpan {
432 let start = je.sm.lookup_char_pos(span.lo());
433 let end = je.sm.lookup_char_pos(span.hi());
434 let backtrace_step = backtrace.next().map(|bt| {
435 let call_site = Self::from_span_full(bt.call_site, false, None, None, backtrace, je);
437 Self::from_span_full(bt.def_site, false, None, None, vec![].into_iter(), je);
438 Box::new(DiagnosticSpanMacroExpansion {
440 macro_decl_name: bt.kind.descr(),
446 file_name: start.file.name.to_string(),
447 byte_start: start.file.original_relative_byte_pos(span.lo()).0,
448 byte_end: start.file.original_relative_byte_pos(span.hi()).0,
449 line_start: start.line,
451 column_start: start.col.0 + 1,
452 column_end: end.col.0 + 1,
454 text: DiagnosticSpanLine::from_span(span, je),
455 suggested_replacement: suggestion.map(|x| x.0.clone()),
456 suggestion_applicability: suggestion.map(|x| x.1),
457 expansion: backtrace_step,
462 fn from_multispan(msp: &MultiSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
465 .map(|span_str| Self::from_span_label(span_str, None, je))
469 fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
473 .flat_map(|substitution| {
474 substitution.parts.iter().map(move |suggestion_inner| {
476 SpanLabel { span: suggestion_inner.span, is_primary: true, label: None };
477 DiagnosticSpan::from_span_label(
479 Some((&suggestion_inner.snippet, suggestion.applicability)),
488 impl DiagnosticSpanLine {
489 fn line_from_source_file(
490 sf: &rustc_span::SourceFile,
494 ) -> DiagnosticSpanLine {
496 text: sf.get_line(index).map_or(String::new(), |l| l.into_owned()),
497 highlight_start: h_start,
498 highlight_end: h_end,
502 /// Creates a list of DiagnosticSpanLines from span - each line with any part
503 /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
504 /// `span` within the line.
505 fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
509 // We can't get any lines if the source is unavailable.
510 if !je.sm.ensure_source_file_source_present(lines.file.clone()) {
514 let sf = &*lines.file;
519 DiagnosticSpanLine::line_from_source_file(
522 line.start_col.0 + 1,
528 .unwrap_or_else(|_| vec![])
532 impl DiagnosticCode {
533 fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
536 DiagnosticId::Error(s) => s,
537 DiagnosticId::Lint { name, has_future_breakage: _ } => name,
540 je.registry.as_ref().map(|registry| registry.try_find_description(&s)).unwrap();
542 DiagnosticCode { code: s, explanation: je_result.unwrap_or(None) }