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};
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, db: &errors::Diagnostic) {
93 let data = Diagnostic::from_errors_diagnostic(db, 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 should_show_explain(&self) -> bool {
117 match self.json_rendered {
118 HumanReadableErrorType::Short(_) => false,
124 // The following data types are provided just for serialisation.
126 #[derive(RustcEncodable)]
128 /// The primary error message.
130 code: Option<DiagnosticCode>,
131 /// "error: internal compiler error", "error", "warning", "note", "help".
133 spans: Vec<DiagnosticSpan>,
134 /// Associated diagnostic messages.
135 children: Vec<Diagnostic>,
136 /// The message as rustc would render it.
137 rendered: Option<String>,
140 #[derive(RustcEncodable)]
141 struct DiagnosticSpan {
148 /// 1-based, character offset.
151 /// Is this a "primary" span -- meaning the point, or one of the points,
152 /// where the error occurred?
154 /// Source text from the start of line_start to the end of line_end.
155 text: Vec<DiagnosticSpanLine>,
156 /// Label that should be placed at this location (if any)
157 label: Option<String>,
158 /// If we are suggesting a replacement, this will contain text
159 /// that should be sliced in atop this span.
160 suggested_replacement: Option<String>,
161 /// If the suggestion is approximate
162 suggestion_applicability: Option<Applicability>,
163 /// Macro invocations that created the code at this span, if any.
164 expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
167 #[derive(RustcEncodable)]
168 struct DiagnosticSpanLine {
171 /// 1-based, character offset in self.text.
172 highlight_start: usize,
174 highlight_end: usize,
177 #[derive(RustcEncodable)]
178 struct DiagnosticSpanMacroExpansion {
179 /// span where macro was applied to generate this code; note that
180 /// this may itself derive from a macro (if
181 /// `span.expansion.is_some()`)
182 span: DiagnosticSpan,
184 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
185 macro_decl_name: String,
187 /// span where macro was defined (if known)
188 def_site_span: DiagnosticSpan,
191 #[derive(RustcEncodable)]
192 struct DiagnosticCode {
195 /// An explanation for the code.
196 explanation: Option<&'static str>,
199 #[derive(RustcEncodable)]
200 struct ArtifactNotification<'a> {
201 /// The path of the artifact.
203 /// What kind of artifact we're emitting.
208 fn from_errors_diagnostic(db: &errors::Diagnostic,
211 let sugg = db.suggestions.iter().map(|sugg| {
213 message: sugg.msg.clone(),
216 spans: DiagnosticSpan::from_suggestion(sugg, je),
222 // generate regular command line output and store it in the json
224 // A threadsafe buffer for writing.
225 #[derive(Default, Clone)]
226 struct BufWriter(Arc<Mutex<Vec<u8>>>);
228 impl Write for BufWriter {
229 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
230 self.0.lock().unwrap().write(buf)
232 fn flush(&mut self) -> io::Result<()> {
233 self.0.lock().unwrap().flush()
236 let buf = BufWriter::default();
237 let output = buf.clone();
238 je.json_rendered.new_emitter(
239 Box::new(buf), Some(je.sm.clone()), false, None, je.external_macro_backtrace
240 ).ui_testing(je.ui_testing).emit_diagnostic(db);
241 let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
242 let output = String::from_utf8(output).unwrap();
245 message: db.message(),
246 code: DiagnosticCode::map_opt_string(db.code.clone(), je),
247 level: db.level.to_str(),
248 spans: DiagnosticSpan::from_multispan(&db.span, je),
249 children: db.children.iter().map(|c| {
250 Diagnostic::from_sub_diagnostic(c, je)
251 }).chain(sugg).collect(),
252 rendered: Some(output),
256 fn from_sub_diagnostic(db: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic {
258 message: db.message(),
260 level: db.level.to_str(),
261 spans: db.render_span.as_ref()
262 .map(|sp| DiagnosticSpan::from_multispan(sp, je))
263 .unwrap_or_else(|| DiagnosticSpan::from_multispan(&db.span, je)),
270 impl DiagnosticSpan {
271 fn from_span_label(span: SpanLabel,
272 suggestion: Option<(&String, Applicability)>,
275 Self::from_span_etc(span.span,
282 fn from_span_etc(span: Span,
284 label: Option<String>,
285 suggestion: Option<(&String, Applicability)>,
288 // obtain the full backtrace from the `macro_backtrace`
289 // helper; in some ways, it'd be better to expand the
290 // backtrace ourselves, but the `macro_backtrace` helper makes
291 // some decision, such as dropping some frames, and I don't
292 // want to duplicate that logic here.
293 let backtrace = span.macro_backtrace().into_iter();
294 DiagnosticSpan::from_span_full(span,
302 fn from_span_full(span: Span,
304 label: Option<String>,
305 suggestion: Option<(&String, Applicability)>,
306 mut backtrace: vec::IntoIter<MacroBacktrace>,
309 let start = je.sm.lookup_char_pos(span.lo());
310 let end = je.sm.lookup_char_pos(span.hi());
311 let backtrace_step = backtrace.next().map(|bt| {
313 Self::from_span_full(bt.call_site,
320 Self::from_span_full(bt.def_site_span,
326 Box::new(DiagnosticSpanMacroExpansion {
328 macro_decl_name: bt.macro_decl_name,
334 file_name: start.file.name.to_string(),
335 byte_start: span.lo().0 - start.file.start_pos.0,
336 byte_end: span.hi().0 - start.file.start_pos.0,
337 line_start: start.line,
339 column_start: start.col.0 + 1,
340 column_end: end.col.0 + 1,
342 text: DiagnosticSpanLine::from_span(span, je),
343 suggested_replacement: suggestion.map(|x| x.0.clone()),
344 suggestion_applicability: suggestion.map(|x| x.1),
345 expansion: backtrace_step,
350 fn from_multispan(msp: &MultiSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
353 .map(|span_str| Self::from_span_label(span_str, None, je))
357 fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter)
358 -> Vec<DiagnosticSpan> {
359 suggestion.substitutions
361 .flat_map(|substitution| {
362 substitution.parts.iter().map(move |suggestion_inner| {
363 let span_label = SpanLabel {
364 span: suggestion_inner.span,
368 DiagnosticSpan::from_span_label(span_label,
369 Some((&suggestion_inner.snippet,
370 suggestion.applicability)),
378 impl DiagnosticSpanLine {
379 fn line_from_source_file(fm: &syntax_pos::SourceFile,
383 -> DiagnosticSpanLine {
385 text: fm.get_line(index).map_or(String::new(), |l| l.into_owned()),
386 highlight_start: h_start,
387 highlight_end: h_end,
391 /// Creates a list of DiagnosticSpanLines from span - each line with any part
392 /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
393 /// `span` within the line.
394 fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
395 je.sm.span_to_lines(span)
397 let fm = &*lines.file;
400 .map(|line| DiagnosticSpanLine::line_from_source_file(
403 line.start_col.0 + 1,
406 }).unwrap_or_else(|_| vec![])
410 impl DiagnosticCode {
411 fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
414 DiagnosticId::Error(s) => s,
415 DiagnosticId::Lint(s) => s,
417 let explanation = je.registry
419 .and_then(|registry| registry.find_description(&s));