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 external_macro_backtrace: bool,
44 registry: Option<Registry>,
45 source_map: Lrc<SourceMap>,
47 json_rendered: HumanReadableErrorType,
48 external_macro_backtrace: bool,
51 dst: Box::new(io::stderr()),
57 external_macro_backtrace,
63 json_rendered: HumanReadableErrorType,
64 external_macro_backtrace: bool,
66 let file_path_mapping = FilePathMapping::empty();
69 Lrc::new(SourceMap::new(file_path_mapping)),
72 external_macro_backtrace,
77 dst: Box<dyn Write + Send>,
78 registry: Option<Registry>,
79 source_map: Lrc<SourceMap>,
81 json_rendered: HumanReadableErrorType,
82 external_macro_backtrace: bool,
91 external_macro_backtrace,
95 pub fn ui_testing(self, ui_testing: bool) -> Self {
96 Self { ui_testing, ..self }
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))
106 writeln!(&mut self.dst, "{}", as_json(&data))
108 if let Err(e) = result {
109 panic!("failed to print diagnostics: {:?}", e);
113 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
114 let data = ArtifactNotification { artifact: path, emit: artifact_type };
115 let result = if self.pretty {
116 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
118 writeln!(&mut self.dst, "{}", as_json(&data))
120 if let Err(e) = result {
121 panic!("failed to print notification: {:?}", e);
125 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
129 fn should_show_explain(&self) -> bool {
130 match self.json_rendered {
131 HumanReadableErrorType::Short(_) => false,
137 // The following data types are provided just for serialisation.
139 #[derive(RustcEncodable)]
141 /// The primary error message.
143 code: Option<DiagnosticCode>,
144 /// "error: internal compiler error", "error", "warning", "note", "help".
146 spans: Vec<DiagnosticSpan>,
147 /// Associated diagnostic messages.
148 children: Vec<Diagnostic>,
149 /// The message as rustc would render it.
150 rendered: Option<String>,
153 #[derive(RustcEncodable)]
154 struct DiagnosticSpan {
161 /// 1-based, character offset.
164 /// Is this a "primary" span -- meaning the point, or one of the points,
165 /// where the error occurred?
167 /// Source text from the start of line_start to the end of line_end.
168 text: Vec<DiagnosticSpanLine>,
169 /// Label that should be placed at this location (if any)
170 label: Option<String>,
171 /// If we are suggesting a replacement, this will contain text
172 /// that should be sliced in atop this span.
173 suggested_replacement: Option<String>,
174 /// If the suggestion is approximate
175 suggestion_applicability: Option<Applicability>,
176 /// Macro invocations that created the code at this span, if any.
177 expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
180 #[derive(RustcEncodable)]
181 struct DiagnosticSpanLine {
184 /// 1-based, character offset in self.text.
185 highlight_start: usize,
187 highlight_end: usize,
190 #[derive(RustcEncodable)]
191 struct DiagnosticSpanMacroExpansion {
192 /// span where macro was applied to generate this code; note that
193 /// this may itself derive from a macro (if
194 /// `span.expansion.is_some()`)
195 span: DiagnosticSpan,
197 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
198 macro_decl_name: String,
200 /// span where macro was defined (if known)
201 def_site_span: DiagnosticSpan,
204 #[derive(RustcEncodable)]
205 struct DiagnosticCode {
208 /// An explanation for the code.
209 explanation: Option<&'static str>,
212 #[derive(RustcEncodable)]
213 struct ArtifactNotification<'a> {
214 /// The path of the artifact.
216 /// What kind of artifact we're emitting.
221 fn from_errors_diagnostic(diag: &crate::Diagnostic, je: &JsonEmitter) -> Diagnostic {
222 let sugg = diag.suggestions.iter().map(|sugg| Diagnostic {
223 message: sugg.msg.clone(),
226 spans: DiagnosticSpan::from_suggestion(sugg, je),
231 // generate regular command line output and store it in the json
233 // A threadsafe buffer for writing.
234 #[derive(Default, Clone)]
235 struct BufWriter(Arc<Mutex<Vec<u8>>>);
237 impl Write for BufWriter {
238 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
239 self.0.lock().unwrap().write(buf)
241 fn flush(&mut self) -> io::Result<()> {
242 self.0.lock().unwrap().flush()
245 let buf = BufWriter::default();
246 let output = buf.clone();
253 je.external_macro_backtrace,
255 .ui_testing(je.ui_testing)
256 .emit_diagnostic(diag);
257 let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
258 let output = String::from_utf8(output).unwrap();
261 message: diag.message(),
262 code: DiagnosticCode::map_opt_string(diag.code.clone(), je),
263 level: diag.level.to_str(),
264 spans: DiagnosticSpan::from_multispan(&diag.span, je),
268 .map(|c| Diagnostic::from_sub_diagnostic(c, je))
271 rendered: Some(output),
275 fn from_sub_diagnostic(diag: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic {
277 message: diag.message(),
279 level: diag.level.to_str(),
283 .map(|sp| DiagnosticSpan::from_multispan(sp, je))
284 .unwrap_or_else(|| DiagnosticSpan::from_multispan(&diag.span, je)),
291 impl DiagnosticSpan {
294 suggestion: Option<(&String, Applicability)>,
296 ) -> DiagnosticSpan {
297 Self::from_span_etc(span.span, span.is_primary, span.label, suggestion, je)
303 label: Option<String>,
304 suggestion: Option<(&String, Applicability)>,
306 ) -> DiagnosticSpan {
307 // obtain the full backtrace from the `macro_backtrace`
308 // helper; in some ways, it'd be better to expand the
309 // backtrace ourselves, but the `macro_backtrace` helper makes
310 // some decision, such as dropping some frames, and I don't
311 // want to duplicate that logic here.
312 let backtrace = span.macro_backtrace().into_iter();
313 DiagnosticSpan::from_span_full(span, is_primary, label, suggestion, backtrace, je)
319 label: Option<String>,
320 suggestion: Option<(&String, Applicability)>,
321 mut backtrace: vec::IntoIter<ExpnData>,
323 ) -> DiagnosticSpan {
324 let start = je.sm.lookup_char_pos(span.lo());
325 let end = je.sm.lookup_char_pos(span.hi());
326 let backtrace_step = backtrace.next().map(|bt| {
327 let call_site = Self::from_span_full(bt.call_site, false, None, None, backtrace, je);
329 Self::from_span_full(bt.def_site, false, None, None, vec![].into_iter(), je);
330 Box::new(DiagnosticSpanMacroExpansion {
332 macro_decl_name: bt.kind.descr(),
338 file_name: start.file.name.to_string(),
339 byte_start: start.file.original_relative_byte_pos(span.lo()).0,
340 byte_end: start.file.original_relative_byte_pos(span.hi()).0,
341 line_start: start.line,
343 column_start: start.col.0 + 1,
344 column_end: end.col.0 + 1,
346 text: DiagnosticSpanLine::from_span(span, je),
347 suggested_replacement: suggestion.map(|x| x.0.clone()),
348 suggestion_applicability: suggestion.map(|x| x.1),
349 expansion: backtrace_step,
354 fn from_multispan(msp: &MultiSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
357 .map(|span_str| Self::from_span_label(span_str, None, je))
361 fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
365 .flat_map(|substitution| {
366 substitution.parts.iter().map(move |suggestion_inner| {
368 SpanLabel { span: suggestion_inner.span, is_primary: true, label: None };
369 DiagnosticSpan::from_span_label(
371 Some((&suggestion_inner.snippet, suggestion.applicability)),
380 impl DiagnosticSpanLine {
381 fn line_from_source_file(
382 fm: &rustc_span::SourceFile,
386 ) -> DiagnosticSpanLine {
388 text: fm.get_line(index).map_or(String::new(), |l| l.into_owned()),
389 highlight_start: h_start,
390 highlight_end: h_end,
394 /// Creates a list of DiagnosticSpanLines from span - each line with any part
395 /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
396 /// `span` within the line.
397 fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
401 let fm = &*lines.file;
406 DiagnosticSpanLine::line_from_source_file(
409 line.start_col.0 + 1,
415 .unwrap_or_else(|_| vec![])
419 impl DiagnosticCode {
420 fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
423 DiagnosticId::Error(s) => s,
424 DiagnosticId::Lint(s) => s,
427 je.registry.as_ref().and_then(|registry| registry.find_description(&s));
429 DiagnosticCode { code: s, explanation }