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::{DiagnosticBuilder, 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,
39 registry: Option<Registry>,
40 source_map: Lrc<SourceMap>,
42 json_rendered: HumanReadableErrorType,
45 dst: Box::new(io::stderr()),
54 pub fn basic(pretty: bool, json_rendered: HumanReadableErrorType) -> JsonEmitter {
55 let file_path_mapping = FilePathMapping::empty();
56 JsonEmitter::stderr(None, Lrc::new(SourceMap::new(file_path_mapping)),
57 pretty, json_rendered)
61 dst: Box<dyn Write + Send>,
62 registry: Option<Registry>,
63 source_map: Lrc<SourceMap>,
65 json_rendered: HumanReadableErrorType,
77 pub fn ui_testing(self, ui_testing: bool) -> Self {
78 Self { ui_testing, ..self }
82 impl Emitter for JsonEmitter {
83 fn emit_diagnostic(&mut self, db: &DiagnosticBuilder<'_>) {
84 let data = Diagnostic::from_diagnostic_builder(db, self);
85 let result = if self.pretty {
86 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
88 writeln!(&mut self.dst, "{}", as_json(&data))
90 if let Err(e) = result {
91 panic!("failed to print diagnostics: {:?}", e);
95 fn emit_artifact_notification(&mut self, path: &Path) {
96 let data = ArtifactNotification { artifact: path };
97 let result = if self.pretty {
98 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
100 writeln!(&mut self.dst, "{}", as_json(&data))
102 if let Err(e) = result {
103 panic!("failed to print notification: {:?}", e);
108 // The following data types are provided just for serialisation.
110 #[derive(RustcEncodable)]
112 /// The primary error message.
114 code: Option<DiagnosticCode>,
115 /// "error: internal compiler error", "error", "warning", "note", "help".
117 spans: Vec<DiagnosticSpan>,
118 /// Associated diagnostic messages.
119 children: Vec<Diagnostic>,
120 /// The message as rustc would render it.
121 rendered: Option<String>,
124 #[derive(RustcEncodable)]
125 #[allow(unused_attributes)]
126 struct DiagnosticSpan {
133 /// 1-based, character offset.
136 /// Is this a "primary" span -- meaning the point, or one of the points,
137 /// where the error occurred?
139 /// Source text from the start of line_start to the end of line_end.
140 text: Vec<DiagnosticSpanLine>,
141 /// Label that should be placed at this location (if any)
142 label: Option<String>,
143 /// If we are suggesting a replacement, this will contain text
144 /// that should be sliced in atop this span.
145 suggested_replacement: Option<String>,
146 /// If the suggestion is approximate
147 suggestion_applicability: Option<Applicability>,
148 /// Macro invocations that created the code at this span, if any.
149 expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
152 #[derive(RustcEncodable)]
153 struct DiagnosticSpanLine {
156 /// 1-based, character offset in self.text.
157 highlight_start: usize,
159 highlight_end: usize,
162 #[derive(RustcEncodable)]
163 struct DiagnosticSpanMacroExpansion {
164 /// span where macro was applied to generate this code; note that
165 /// this may itself derive from a macro (if
166 /// `span.expansion.is_some()`)
167 span: DiagnosticSpan,
169 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
170 macro_decl_name: String,
172 /// span where macro was defined (if known)
173 def_site_span: Option<DiagnosticSpan>,
176 #[derive(RustcEncodable)]
177 struct DiagnosticCode {
180 /// An explanation for the code.
181 explanation: Option<&'static str>,
184 #[derive(RustcEncodable)]
185 struct ArtifactNotification<'a> {
186 /// The path of the artifact.
191 fn from_diagnostic_builder(db: &DiagnosticBuilder<'_>,
194 let sugg = db.suggestions.iter().map(|sugg| {
196 message: sugg.msg.clone(),
199 spans: DiagnosticSpan::from_suggestion(sugg, je),
205 // generate regular command line output and store it in the json
207 // A threadsafe buffer for writing.
208 #[derive(Default, Clone)]
209 struct BufWriter(Arc<Mutex<Vec<u8>>>);
211 impl Write for BufWriter {
212 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
213 self.0.lock().unwrap().write(buf)
215 fn flush(&mut self) -> io::Result<()> {
216 self.0.lock().unwrap().flush()
219 let buf = BufWriter::default();
220 let output = buf.clone();
221 je.json_rendered.new_emitter(Box::new(buf), Some(je.sm.clone()), false)
222 .ui_testing(je.ui_testing).emit_diagnostic(db);
223 let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
224 let output = String::from_utf8(output).unwrap();
227 message: db.message(),
228 code: DiagnosticCode::map_opt_string(db.code.clone(), je),
229 level: db.level.to_str(),
230 spans: DiagnosticSpan::from_multispan(&db.span, je),
231 children: db.children.iter().map(|c| {
232 Diagnostic::from_sub_diagnostic(c, je)
233 }).chain(sugg).collect(),
234 rendered: Some(output),
238 fn from_sub_diagnostic(db: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic {
240 message: db.message(),
242 level: db.level.to_str(),
243 spans: db.render_span.as_ref()
244 .map(|sp| DiagnosticSpan::from_multispan(sp, je))
245 .unwrap_or_else(|| DiagnosticSpan::from_multispan(&db.span, je)),
252 impl DiagnosticSpan {
253 fn from_span_label(span: SpanLabel,
254 suggestion: Option<(&String, Applicability)>,
257 Self::from_span_etc(span.span,
264 fn from_span_etc(span: Span,
266 label: Option<String>,
267 suggestion: Option<(&String, Applicability)>,
270 // obtain the full backtrace from the `macro_backtrace`
271 // helper; in some ways, it'd be better to expand the
272 // backtrace ourselves, but the `macro_backtrace` helper makes
273 // some decision, such as dropping some frames, and I don't
274 // want to duplicate that logic here.
275 let backtrace = span.macro_backtrace().into_iter();
276 DiagnosticSpan::from_span_full(span,
284 fn from_span_full(span: Span,
286 label: Option<String>,
287 suggestion: Option<(&String, Applicability)>,
288 mut backtrace: vec::IntoIter<MacroBacktrace>,
291 let start = je.sm.lookup_char_pos(span.lo());
292 let end = je.sm.lookup_char_pos(span.hi());
293 let backtrace_step = backtrace.next().map(|bt| {
295 Self::from_span_full(bt.call_site,
301 let def_site_span = bt.def_site_span.map(|sp| {
302 Self::from_span_full(sp,
309 Box::new(DiagnosticSpanMacroExpansion {
311 macro_decl_name: bt.macro_decl_name,
317 file_name: start.file.name.to_string(),
318 byte_start: span.lo().0 - start.file.start_pos.0,
319 byte_end: span.hi().0 - start.file.start_pos.0,
320 line_start: start.line,
322 column_start: start.col.0 + 1,
323 column_end: end.col.0 + 1,
325 text: DiagnosticSpanLine::from_span(span, je),
326 suggested_replacement: suggestion.map(|x| x.0.clone()),
327 suggestion_applicability: suggestion.map(|x| x.1),
328 expansion: backtrace_step,
333 fn from_multispan(msp: &MultiSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
336 .map(|span_str| Self::from_span_label(span_str, None, je))
340 fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter)
341 -> Vec<DiagnosticSpan> {
342 suggestion.substitutions
344 .flat_map(|substitution| {
345 substitution.parts.iter().map(move |suggestion_inner| {
346 let span_label = SpanLabel {
347 span: suggestion_inner.span,
351 DiagnosticSpan::from_span_label(span_label,
352 Some((&suggestion_inner.snippet,
353 suggestion.applicability)),
361 impl DiagnosticSpanLine {
362 fn line_from_source_file(fm: &syntax_pos::SourceFile,
366 -> DiagnosticSpanLine {
368 text: fm.get_line(index).map_or(String::new(), |l| l.into_owned()),
369 highlight_start: h_start,
370 highlight_end: h_end,
374 /// Creates a list of DiagnosticSpanLines from span - each line with any part
375 /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
376 /// `span` within the line.
377 fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
378 je.sm.span_to_lines(span)
380 let fm = &*lines.file;
383 .map(|line| DiagnosticSpanLine::line_from_source_file(
386 line.start_col.0 + 1,
389 }).unwrap_or_else(|_| vec![])
393 impl DiagnosticCode {
394 fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
397 DiagnosticId::Error(s) => s,
398 DiagnosticId::Lint(s) => s,
400 let explanation = je.registry
402 .and_then(|registry| registry.find_description(&s));