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 crate::source_map::{SourceMap, FilePathMapping};
14 use errors::registry::Registry;
15 use errors::{SubDiagnostic, CodeSuggestion, SourceMapper, SourceMapperDyn};
16 use errors::{DiagnosticId, Applicability};
17 use errors::emitter::{Emitter, HumanReadableErrorType};
19 use syntax_pos::{MacroBacktrace, Span, SpanLabel, MultiSpan};
20 use rustc_data_structures::sync::{self, Lrc};
21 use std::io::{self, Write};
24 use std::sync::{Arc, Mutex};
26 use rustc_serialize::json::{as_json, as_pretty_json};
28 pub struct JsonEmitter {
29 dst: Box<dyn Write + Send>,
30 registry: Option<Registry>,
31 sm: Lrc<dyn SourceMapper + sync::Send + sync::Sync>,
34 json_rendered: HumanReadableErrorType,
35 external_macro_backtrace: bool,
40 registry: Option<Registry>,
41 source_map: Lrc<SourceMap>,
43 json_rendered: HumanReadableErrorType,
44 external_macro_backtrace: bool,
47 dst: Box::new(io::stderr()),
53 external_macro_backtrace,
59 json_rendered: HumanReadableErrorType,
60 external_macro_backtrace: bool,
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)
68 dst: Box<dyn Write + Send>,
69 registry: Option<Registry>,
70 source_map: Lrc<SourceMap>,
72 json_rendered: HumanReadableErrorType,
73 external_macro_backtrace: bool,
82 external_macro_backtrace,
86 pub fn ui_testing(self, ui_testing: bool) -> Self {
87 Self { ui_testing, ..self }
91 impl Emitter for JsonEmitter {
92 fn emit_diagnostic(&mut self, diag: &errors::Diagnostic) {
93 let data = Diagnostic::from_errors_diagnostic(diag, self);
94 let result = if self.pretty {
95 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
97 writeln!(&mut self.dst, "{}", as_json(&data))
99 if let Err(e) = result {
100 panic!("failed to print diagnostics: {:?}", e);
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))
109 writeln!(&mut self.dst, "{}", as_json(&data))
111 if let Err(e) = result {
112 panic!("failed to print notification: {:?}", e);
116 fn source_map(&self) -> Option<&Lrc<SourceMapperDyn>> {
120 fn should_show_explain(&self) -> bool {
121 match self.json_rendered {
122 HumanReadableErrorType::Short(_) => false,
128 // The following data types are provided just for serialisation.
130 #[derive(RustcEncodable)]
132 /// The primary error message.
134 code: Option<DiagnosticCode>,
135 /// "error: internal compiler error", "error", "warning", "note", "help".
137 spans: Vec<DiagnosticSpan>,
138 /// Associated diagnostic messages.
139 children: Vec<Diagnostic>,
140 /// The message as rustc would render it.
141 rendered: Option<String>,
144 #[derive(RustcEncodable)]
145 struct DiagnosticSpan {
152 /// 1-based, character offset.
155 /// Is this a "primary" span -- meaning the point, or one of the points,
156 /// where the error occurred?
158 /// Source text from the start of line_start to the end of line_end.
159 text: Vec<DiagnosticSpanLine>,
160 /// Label that should be placed at this location (if any)
161 label: Option<String>,
162 /// If we are suggesting a replacement, this will contain text
163 /// that should be sliced in atop this span.
164 suggested_replacement: Option<String>,
165 /// If the suggestion is approximate
166 suggestion_applicability: Option<Applicability>,
167 /// Macro invocations that created the code at this span, if any.
168 expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
171 #[derive(RustcEncodable)]
172 struct DiagnosticSpanLine {
175 /// 1-based, character offset in self.text.
176 highlight_start: usize,
178 highlight_end: usize,
181 #[derive(RustcEncodable)]
182 struct DiagnosticSpanMacroExpansion {
183 /// span where macro was applied to generate this code; note that
184 /// this may itself derive from a macro (if
185 /// `span.expansion.is_some()`)
186 span: DiagnosticSpan,
188 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
189 macro_decl_name: String,
191 /// span where macro was defined (if known)
192 def_site_span: DiagnosticSpan,
195 #[derive(RustcEncodable)]
196 struct DiagnosticCode {
199 /// An explanation for the code.
200 explanation: Option<&'static str>,
203 #[derive(RustcEncodable)]
204 struct ArtifactNotification<'a> {
205 /// The path of the artifact.
207 /// What kind of artifact we're emitting.
212 fn from_errors_diagnostic(diag: &errors::Diagnostic,
215 let sugg = diag.suggestions.iter().map(|sugg| {
217 message: sugg.msg.clone(),
220 spans: DiagnosticSpan::from_suggestion(sugg, je),
226 // generate regular command line output and store it in the json
228 // A threadsafe buffer for writing.
229 #[derive(Default, Clone)]
230 struct BufWriter(Arc<Mutex<Vec<u8>>>);
232 impl Write for BufWriter {
233 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
234 self.0.lock().unwrap().write(buf)
236 fn flush(&mut self) -> io::Result<()> {
237 self.0.lock().unwrap().flush()
240 let buf = BufWriter::default();
241 let output = buf.clone();
242 je.json_rendered.new_emitter(
243 Box::new(buf), Some(je.sm.clone()), false, None, je.external_macro_backtrace
244 ).ui_testing(je.ui_testing).emit_diagnostic(diag);
245 let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
246 let output = String::from_utf8(output).unwrap();
249 message: diag.message(),
250 code: DiagnosticCode::map_opt_string(diag.code.clone(), je),
251 level: diag.level.to_str(),
252 spans: DiagnosticSpan::from_multispan(&diag.span, je),
253 children: diag.children.iter().map(|c| {
254 Diagnostic::from_sub_diagnostic(c, je)
255 }).chain(sugg).collect(),
256 rendered: Some(output),
260 fn from_sub_diagnostic(diag: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic {
262 message: diag.message(),
264 level: diag.level.to_str(),
265 spans: diag.render_span.as_ref()
266 .map(|sp| DiagnosticSpan::from_multispan(sp, je))
267 .unwrap_or_else(|| DiagnosticSpan::from_multispan(&diag.span, je)),
274 impl DiagnosticSpan {
275 fn from_span_label(span: SpanLabel,
276 suggestion: Option<(&String, Applicability)>,
279 Self::from_span_etc(span.span,
286 fn from_span_etc(span: Span,
288 label: Option<String>,
289 suggestion: Option<(&String, Applicability)>,
292 // obtain the full backtrace from the `macro_backtrace`
293 // helper; in some ways, it'd be better to expand the
294 // backtrace ourselves, but the `macro_backtrace` helper makes
295 // some decision, such as dropping some frames, and I don't
296 // want to duplicate that logic here.
297 let backtrace = span.macro_backtrace().into_iter();
298 DiagnosticSpan::from_span_full(span,
306 fn from_span_full(span: Span,
308 label: Option<String>,
309 suggestion: Option<(&String, Applicability)>,
310 mut backtrace: vec::IntoIter<MacroBacktrace>,
313 let start = je.sm.lookup_char_pos(span.lo());
314 let end = je.sm.lookup_char_pos(span.hi());
315 let backtrace_step = backtrace.next().map(|bt| {
317 Self::from_span_full(bt.call_site,
324 Self::from_span_full(bt.def_site_span,
330 Box::new(DiagnosticSpanMacroExpansion {
332 macro_decl_name: bt.macro_decl_name,
338 file_name: start.file.name.to_string(),
339 byte_start: span.lo().0 - start.file.start_pos.0,
340 byte_end: span.hi().0 - start.file.start_pos.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)
362 -> Vec<DiagnosticSpan> {
363 suggestion.substitutions
365 .flat_map(|substitution| {
366 substitution.parts.iter().map(move |suggestion_inner| {
367 let span_label = SpanLabel {
368 span: suggestion_inner.span,
372 DiagnosticSpan::from_span_label(span_label,
373 Some((&suggestion_inner.snippet,
374 suggestion.applicability)),
382 impl DiagnosticSpanLine {
383 fn line_from_source_file(fm: &syntax_pos::SourceFile,
387 -> DiagnosticSpanLine {
389 text: fm.get_line(index).map_or(String::new(), |l| l.into_owned()),
390 highlight_start: h_start,
391 highlight_end: h_end,
395 /// Creates a list of DiagnosticSpanLines from span - each line with any part
396 /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
397 /// `span` within the line.
398 fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
399 je.sm.span_to_lines(span)
401 let fm = &*lines.file;
404 .map(|line| DiagnosticSpanLine::line_from_source_file(
407 line.start_col.0 + 1,
410 }).unwrap_or_else(|_| vec![])
414 impl DiagnosticCode {
415 fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
418 DiagnosticId::Error(s) => s,
419 DiagnosticId::Lint(s) => s,
421 let explanation = je.registry
423 .and_then(|registry| registry.find_description(&s));