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::{CodeSuggestion, SubDiagnostic};
18 use rustc_lint_defs::{Applicability, FutureBreakage};
20 use rustc_data_structures::sync::Lrc;
21 use rustc_span::hygiene::ExpnData;
22 use rustc_span::{MultiSpan, Span, SpanLabel};
23 use std::io::{self, Write};
25 use std::sync::{Arc, Mutex};
28 use rustc_serialize::json::{as_json, as_pretty_json};
33 pub struct JsonEmitter {
34 dst: Box<dyn Write + Send>,
35 registry: Option<Registry>,
39 json_rendered: HumanReadableErrorType,
40 terminal_width: Option<usize>,
41 macro_backtrace: bool,
46 registry: Option<Registry>,
47 source_map: Lrc<SourceMap>,
49 json_rendered: HumanReadableErrorType,
50 terminal_width: Option<usize>,
51 macro_backtrace: bool,
54 dst: Box::new(io::BufWriter::new(io::stderr())),
67 json_rendered: HumanReadableErrorType,
68 terminal_width: Option<usize>,
69 macro_backtrace: bool,
71 let file_path_mapping = FilePathMapping::empty();
74 Lrc::new(SourceMap::new(file_path_mapping)),
83 dst: Box<dyn Write + Send>,
84 registry: Option<Registry>,
85 source_map: Lrc<SourceMap>,
87 json_rendered: HumanReadableErrorType,
88 terminal_width: Option<usize>,
89 macro_backtrace: bool,
103 pub fn ui_testing(self, ui_testing: bool) -> Self {
104 Self { ui_testing, ..self }
108 impl Emitter for JsonEmitter {
109 fn emit_diagnostic(&mut self, diag: &crate::Diagnostic) {
110 let data = Diagnostic::from_errors_diagnostic(diag, self);
111 let result = if self.pretty {
112 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
114 writeln!(&mut self.dst, "{}", as_json(&data))
116 .and_then(|_| self.dst.flush());
117 if let Err(e) = result {
118 panic!("failed to print diagnostics: {:?}", e);
122 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
123 let data = ArtifactNotification { artifact: path, emit: artifact_type };
124 let result = if self.pretty {
125 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
127 writeln!(&mut self.dst, "{}", as_json(&data))
129 .and_then(|_| self.dst.flush());
130 if let Err(e) = result {
131 panic!("failed to print notification: {:?}", e);
135 fn emit_future_breakage_report(&mut self, diags: Vec<(FutureBreakage, crate::Diagnostic)>) {
136 let data: Vec<FutureBreakageItem> = diags
138 .map(|(breakage, mut diag)| {
139 if diag.level == crate::Level::Allow {
140 diag.level = crate::Level::Warning;
143 future_breakage_date: breakage.date,
144 diagnostic: Diagnostic::from_errors_diagnostic(&diag, self),
148 let report = FutureIncompatReport { future_incompat_report: data };
149 let result = if self.pretty {
150 writeln!(&mut self.dst, "{}", as_pretty_json(&report))
152 writeln!(&mut self.dst, "{}", as_json(&report))
154 .and_then(|_| self.dst.flush());
155 if let Err(e) = result {
156 panic!("failed to print future breakage report: {:?}", e);
160 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
164 fn should_show_explain(&self) -> bool {
165 !matches!(self.json_rendered, HumanReadableErrorType::Short(_))
169 // The following data types are provided just for serialisation.
173 /// The primary error message.
175 code: Option<DiagnosticCode>,
176 /// "error: internal compiler error", "error", "warning", "note", "help".
178 spans: Vec<DiagnosticSpan>,
179 /// Associated diagnostic messages.
180 children: Vec<Diagnostic>,
181 /// The message as rustc would render it.
182 rendered: Option<String>,
186 struct DiagnosticSpan {
193 /// 1-based, character offset.
196 /// Is this a "primary" span -- meaning the point, or one of the points,
197 /// where the error occurred?
199 /// Source text from the start of line_start to the end of line_end.
200 text: Vec<DiagnosticSpanLine>,
201 /// Label that should be placed at this location (if any)
202 label: Option<String>,
203 /// If we are suggesting a replacement, this will contain text
204 /// that should be sliced in atop this span.
205 suggested_replacement: Option<String>,
206 /// If the suggestion is approximate
207 suggestion_applicability: Option<Applicability>,
208 /// Macro invocations that created the code at this span, if any.
209 expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
213 struct DiagnosticSpanLine {
216 /// 1-based, character offset in self.text.
217 highlight_start: usize,
219 highlight_end: usize,
223 struct DiagnosticSpanMacroExpansion {
224 /// span where macro was applied to generate this code; note that
225 /// this may itself derive from a macro (if
226 /// `span.expansion.is_some()`)
227 span: DiagnosticSpan,
229 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
230 macro_decl_name: String,
232 /// span where macro was defined (if known)
233 def_site_span: DiagnosticSpan,
237 struct DiagnosticCode {
240 /// An explanation for the code.
241 explanation: Option<&'static str>,
245 struct ArtifactNotification<'a> {
246 /// The path of the artifact.
248 /// What kind of artifact we're emitting.
253 struct FutureBreakageItem {
254 future_breakage_date: Option<&'static str>,
255 diagnostic: Diagnostic,
259 struct FutureIncompatReport {
260 future_incompat_report: Vec<FutureBreakageItem>,
264 fn from_errors_diagnostic(diag: &crate::Diagnostic, je: &JsonEmitter) -> Diagnostic {
265 let sugg = diag.suggestions.iter().map(|sugg| Diagnostic {
266 message: sugg.msg.clone(),
269 spans: DiagnosticSpan::from_suggestion(sugg, je),
274 // generate regular command line output and store it in the json
276 // A threadsafe buffer for writing.
277 #[derive(Default, Clone)]
278 struct BufWriter(Arc<Mutex<Vec<u8>>>);
280 impl Write for BufWriter {
281 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
282 self.0.lock().unwrap().write(buf)
284 fn flush(&mut self) -> io::Result<()> {
285 self.0.lock().unwrap().flush()
288 let buf = BufWriter::default();
289 let output = buf.clone();
298 .ui_testing(je.ui_testing)
299 .emit_diagnostic(diag);
300 let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
301 let output = String::from_utf8(output).unwrap();
304 message: diag.message(),
305 code: DiagnosticCode::map_opt_string(diag.code.clone(), je),
306 level: diag.level.to_str(),
307 spans: DiagnosticSpan::from_multispan(&diag.span, je),
311 .map(|c| Diagnostic::from_sub_diagnostic(c, je))
314 rendered: Some(output),
318 fn from_sub_diagnostic(diag: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic {
320 message: diag.message(),
322 level: diag.level.to_str(),
326 .map(|sp| DiagnosticSpan::from_multispan(sp, je))
327 .unwrap_or_else(|| DiagnosticSpan::from_multispan(&diag.span, je)),
334 impl DiagnosticSpan {
337 suggestion: Option<(&String, Applicability)>,
339 ) -> DiagnosticSpan {
340 Self::from_span_etc(span.span, span.is_primary, span.label, suggestion, je)
346 label: Option<String>,
347 suggestion: Option<(&String, Applicability)>,
349 ) -> DiagnosticSpan {
350 // obtain the full backtrace from the `macro_backtrace`
351 // helper; in some ways, it'd be better to expand the
352 // backtrace ourselves, but the `macro_backtrace` helper makes
353 // some decision, such as dropping some frames, and I don't
354 // want to duplicate that logic here.
355 let backtrace = span.macro_backtrace();
356 DiagnosticSpan::from_span_full(span, is_primary, label, suggestion, backtrace, je)
362 label: Option<String>,
363 suggestion: Option<(&String, Applicability)>,
364 mut backtrace: impl Iterator<Item = ExpnData>,
366 ) -> DiagnosticSpan {
367 let start = je.sm.lookup_char_pos(span.lo());
368 let end = je.sm.lookup_char_pos(span.hi());
369 let backtrace_step = backtrace.next().map(|bt| {
370 let call_site = Self::from_span_full(bt.call_site, false, None, None, backtrace, je);
372 Self::from_span_full(bt.def_site, false, None, None, vec![].into_iter(), je);
373 Box::new(DiagnosticSpanMacroExpansion {
375 macro_decl_name: bt.kind.descr(),
381 file_name: start.file.name.to_string(),
382 byte_start: start.file.original_relative_byte_pos(span.lo()).0,
383 byte_end: start.file.original_relative_byte_pos(span.hi()).0,
384 line_start: start.line,
386 column_start: start.col.0 + 1,
387 column_end: end.col.0 + 1,
389 text: DiagnosticSpanLine::from_span(span, je),
390 suggested_replacement: suggestion.map(|x| x.0.clone()),
391 suggestion_applicability: suggestion.map(|x| x.1),
392 expansion: backtrace_step,
397 fn from_multispan(msp: &MultiSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
400 .map(|span_str| Self::from_span_label(span_str, None, je))
404 fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
408 .flat_map(|substitution| {
409 substitution.parts.iter().map(move |suggestion_inner| {
411 SpanLabel { span: suggestion_inner.span, is_primary: true, label: None };
412 DiagnosticSpan::from_span_label(
414 Some((&suggestion_inner.snippet, suggestion.applicability)),
423 impl DiagnosticSpanLine {
424 fn line_from_source_file(
425 sf: &rustc_span::SourceFile,
429 ) -> DiagnosticSpanLine {
431 text: sf.get_line(index).map_or(String::new(), |l| l.into_owned()),
432 highlight_start: h_start,
433 highlight_end: h_end,
437 /// Creates a list of DiagnosticSpanLines from span - each line with any part
438 /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
439 /// `span` within the line.
440 fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
444 // We can't get any lines if the source is unavailable.
445 if !je.sm.ensure_source_file_source_present(lines.file.clone()) {
449 let sf = &*lines.file;
454 DiagnosticSpanLine::line_from_source_file(
457 line.start_col.0 + 1,
463 .unwrap_or_else(|_| vec![])
467 impl DiagnosticCode {
468 fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
471 DiagnosticId::Error(s) => s,
472 DiagnosticId::Lint { name, has_future_breakage: _ } => name,
475 je.registry.as_ref().map(|registry| registry.try_find_description(&s)).unwrap();
477 DiagnosticCode { code: s, explanation: je_result.unwrap_or(None) }