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::{Applicability, DiagnosticId};
17 use crate::{CodeSuggestion, SubDiagnostic};
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};
24 use std::sync::{Arc, Mutex};
27 use rustc_serialize::json::{as_json, as_pretty_json};
32 pub struct JsonEmitter {
33 dst: Box<dyn Write + Send>,
34 registry: Option<Registry>,
38 json_rendered: HumanReadableErrorType,
39 terminal_width: Option<usize>,
40 macro_backtrace: bool,
45 registry: Option<Registry>,
46 source_map: Lrc<SourceMap>,
48 json_rendered: HumanReadableErrorType,
49 terminal_width: Option<usize>,
50 macro_backtrace: bool,
53 dst: Box::new(io::BufWriter::new(io::stderr())),
66 json_rendered: HumanReadableErrorType,
67 terminal_width: Option<usize>,
68 macro_backtrace: bool,
70 let file_path_mapping = FilePathMapping::empty();
73 Lrc::new(SourceMap::new(file_path_mapping)),
82 dst: Box<dyn Write + Send>,
83 registry: Option<Registry>,
84 source_map: Lrc<SourceMap>,
86 json_rendered: HumanReadableErrorType,
87 terminal_width: Option<usize>,
88 macro_backtrace: bool,
102 pub fn ui_testing(self, ui_testing: bool) -> Self {
103 Self { ui_testing, ..self }
107 impl Emitter for JsonEmitter {
108 fn emit_diagnostic(&mut self, diag: &crate::Diagnostic) {
109 let data = Diagnostic::from_errors_diagnostic(diag, self);
110 let result = if self.pretty {
111 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
113 writeln!(&mut self.dst, "{}", as_json(&data))
115 .and_then(|_| self.dst.flush());
116 if let Err(e) = result {
117 panic!("failed to print diagnostics: {:?}", e);
121 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
122 let data = ArtifactNotification { artifact: path, emit: artifact_type };
123 let result = if self.pretty {
124 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
126 writeln!(&mut self.dst, "{}", as_json(&data))
128 .and_then(|_| self.dst.flush());
129 if let Err(e) = result {
130 panic!("failed to print notification: {:?}", e);
134 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
138 fn should_show_explain(&self) -> bool {
139 match self.json_rendered {
140 HumanReadableErrorType::Short(_) => false,
146 // The following data types are provided just for serialisation.
148 #[derive(RustcEncodable)]
150 /// The primary error message.
152 code: Option<DiagnosticCode>,
153 /// "error: internal compiler error", "error", "warning", "note", "help".
155 spans: Vec<DiagnosticSpan>,
156 /// Associated diagnostic messages.
157 children: Vec<Diagnostic>,
158 /// The message as rustc would render it.
159 rendered: Option<String>,
162 #[derive(RustcEncodable)]
163 struct DiagnosticSpan {
170 /// 1-based, character offset.
173 /// Is this a "primary" span -- meaning the point, or one of the points,
174 /// where the error occurred?
176 /// Source text from the start of line_start to the end of line_end.
177 text: Vec<DiagnosticSpanLine>,
178 /// Label that should be placed at this location (if any)
179 label: Option<String>,
180 /// If we are suggesting a replacement, this will contain text
181 /// that should be sliced in atop this span.
182 suggested_replacement: Option<String>,
183 /// If the suggestion is approximate
184 suggestion_applicability: Option<Applicability>,
185 /// Macro invocations that created the code at this span, if any.
186 expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
189 #[derive(RustcEncodable)]
190 struct DiagnosticSpanLine {
193 /// 1-based, character offset in self.text.
194 highlight_start: usize,
196 highlight_end: usize,
199 #[derive(RustcEncodable)]
200 struct DiagnosticSpanMacroExpansion {
201 /// span where macro was applied to generate this code; note that
202 /// this may itself derive from a macro (if
203 /// `span.expansion.is_some()`)
204 span: DiagnosticSpan,
206 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
207 macro_decl_name: String,
209 /// span where macro was defined (if known)
210 def_site_span: DiagnosticSpan,
213 #[derive(RustcEncodable)]
214 struct DiagnosticCode {
217 /// An explanation for the code.
218 explanation: Option<&'static str>,
221 #[derive(RustcEncodable)]
222 struct ArtifactNotification<'a> {
223 /// The path of the artifact.
225 /// What kind of artifact we're emitting.
230 fn from_errors_diagnostic(diag: &crate::Diagnostic, je: &JsonEmitter) -> Diagnostic {
231 let sugg = diag.suggestions.iter().map(|sugg| Diagnostic {
232 message: sugg.msg.clone(),
235 spans: DiagnosticSpan::from_suggestion(sugg, je),
240 // generate regular command line output and store it in the json
242 // A threadsafe buffer for writing.
243 #[derive(Default, Clone)]
244 struct BufWriter(Arc<Mutex<Vec<u8>>>);
246 impl Write for BufWriter {
247 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
248 self.0.lock().unwrap().write(buf)
250 fn flush(&mut self) -> io::Result<()> {
251 self.0.lock().unwrap().flush()
254 let buf = BufWriter::default();
255 let output = buf.clone();
264 .ui_testing(je.ui_testing)
265 .emit_diagnostic(diag);
266 let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
267 let output = String::from_utf8(output).unwrap();
270 message: diag.message(),
271 code: DiagnosticCode::map_opt_string(diag.code.clone(), je),
272 level: diag.level.to_str(),
273 spans: DiagnosticSpan::from_multispan(&diag.span, je),
277 .map(|c| Diagnostic::from_sub_diagnostic(c, je))
280 rendered: Some(output),
284 fn from_sub_diagnostic(diag: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic {
286 message: diag.message(),
288 level: diag.level.to_str(),
292 .map(|sp| DiagnosticSpan::from_multispan(sp, je))
293 .unwrap_or_else(|| DiagnosticSpan::from_multispan(&diag.span, je)),
300 impl DiagnosticSpan {
303 suggestion: Option<(&String, Applicability)>,
305 ) -> DiagnosticSpan {
306 Self::from_span_etc(span.span, span.is_primary, span.label, suggestion, je)
312 label: Option<String>,
313 suggestion: Option<(&String, Applicability)>,
315 ) -> DiagnosticSpan {
316 // obtain the full backtrace from the `macro_backtrace`
317 // helper; in some ways, it'd be better to expand the
318 // backtrace ourselves, but the `macro_backtrace` helper makes
319 // some decision, such as dropping some frames, and I don't
320 // want to duplicate that logic here.
321 let backtrace = span.macro_backtrace();
322 DiagnosticSpan::from_span_full(span, is_primary, label, suggestion, backtrace, je)
328 label: Option<String>,
329 suggestion: Option<(&String, Applicability)>,
330 mut backtrace: impl Iterator<Item = ExpnData>,
332 ) -> DiagnosticSpan {
333 let start = je.sm.lookup_char_pos(span.lo());
334 let end = je.sm.lookup_char_pos(span.hi());
335 let backtrace_step = backtrace.next().map(|bt| {
336 let call_site = Self::from_span_full(bt.call_site, false, None, None, backtrace, je);
338 Self::from_span_full(bt.def_site, false, None, None, vec![].into_iter(), je);
339 Box::new(DiagnosticSpanMacroExpansion {
341 macro_decl_name: bt.kind.descr(),
347 file_name: start.file.name.to_string(),
348 byte_start: start.file.original_relative_byte_pos(span.lo()).0,
349 byte_end: start.file.original_relative_byte_pos(span.hi()).0,
350 line_start: start.line,
352 column_start: start.col.0 + 1,
353 column_end: end.col.0 + 1,
355 text: DiagnosticSpanLine::from_span(span, je),
356 suggested_replacement: suggestion.map(|x| x.0.clone()),
357 suggestion_applicability: suggestion.map(|x| x.1),
358 expansion: backtrace_step,
363 fn from_multispan(msp: &MultiSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
366 .map(|span_str| Self::from_span_label(span_str, None, je))
370 fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
374 .flat_map(|substitution| {
375 substitution.parts.iter().map(move |suggestion_inner| {
377 SpanLabel { span: suggestion_inner.span, is_primary: true, label: None };
378 DiagnosticSpan::from_span_label(
380 Some((&suggestion_inner.snippet, suggestion.applicability)),
389 impl DiagnosticSpanLine {
390 fn line_from_source_file(
391 sf: &rustc_span::SourceFile,
395 ) -> DiagnosticSpanLine {
397 text: sf.get_line(index).map_or(String::new(), |l| l.into_owned()),
398 highlight_start: h_start,
399 highlight_end: h_end,
403 /// Creates a list of DiagnosticSpanLines from span - each line with any part
404 /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
405 /// `span` within the line.
406 fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
410 // We can't get any lines if the source is unavailable.
411 if !je.sm.ensure_source_file_source_present(lines.file.clone()) {
415 let sf = &*lines.file;
420 DiagnosticSpanLine::line_from_source_file(
423 line.start_col.0 + 1,
429 .unwrap_or_else(|_| vec![])
433 impl DiagnosticCode {
434 fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
437 DiagnosticId::Error(s) => s,
438 DiagnosticId::Lint(s) => s,
441 je.registry.as_ref().map(|registry| registry.try_find_description(&s)).unwrap();
443 DiagnosticCode { code: s, explanation: je_result.unwrap_or(None) }