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};
23 use std::sync::{Arc, Mutex};
25 use rustc_serialize::json::{as_json, as_pretty_json};
27 pub struct JsonEmitter {
28 dst: Box<dyn Write + Send>,
29 registry: Option<Registry>,
30 sm: Lrc<dyn SourceMapper + sync::Send + sync::Sync>,
33 json_rendered: HumanReadableErrorType,
38 registry: Option<Registry>,
39 source_map: Lrc<SourceMap>,
41 json_rendered: HumanReadableErrorType,
44 dst: Box::new(io::stderr()),
53 pub fn basic(pretty: bool, json_rendered: HumanReadableErrorType) -> JsonEmitter {
54 let file_path_mapping = FilePathMapping::empty();
55 JsonEmitter::stderr(None, Lrc::new(SourceMap::new(file_path_mapping)),
56 pretty, json_rendered)
60 dst: Box<dyn Write + Send>,
61 registry: Option<Registry>,
62 source_map: Lrc<SourceMap>,
64 json_rendered: HumanReadableErrorType,
76 pub fn ui_testing(self, ui_testing: bool) -> Self {
77 Self { ui_testing, ..self }
81 impl Emitter for JsonEmitter {
82 fn emit_diagnostic(&mut self, db: &DiagnosticBuilder<'_>) {
83 let data = Diagnostic::from_diagnostic_builder(db, self);
84 let result = if self.pretty {
85 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
87 writeln!(&mut self.dst, "{}", as_json(&data))
89 if let Err(e) = result {
90 panic!("failed to print diagnostics: {:?}", e);
94 fn maybe_emit_json_directive(&mut self, directive: String) {
95 let data = Directive { directive };
96 let result = if self.pretty {
97 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
99 writeln!(&mut self.dst, "{}", as_json(&data))
101 if let Err(e) = result {
102 panic!("failed to print message: {:?}", e);
107 // The following data types are provided just for serialisation.
109 #[derive(RustcEncodable)]
111 /// The primary error message.
113 code: Option<DiagnosticCode>,
114 /// "error: internal compiler error", "error", "warning", "note", "help".
116 spans: Vec<DiagnosticSpan>,
117 /// Associated diagnostic messages.
118 children: Vec<Diagnostic>,
119 /// The message as rustc would render it.
120 rendered: Option<String>,
123 #[derive(RustcEncodable)]
124 #[allow(unused_attributes)]
125 struct DiagnosticSpan {
132 /// 1-based, character offset.
135 /// Is this a "primary" span -- meaning the point, or one of the points,
136 /// where the error occurred?
138 /// Source text from the start of line_start to the end of line_end.
139 text: Vec<DiagnosticSpanLine>,
140 /// Label that should be placed at this location (if any)
141 label: Option<String>,
142 /// If we are suggesting a replacement, this will contain text
143 /// that should be sliced in atop this span.
144 suggested_replacement: Option<String>,
145 /// If the suggestion is approximate
146 suggestion_applicability: Option<Applicability>,
147 /// Macro invocations that created the code at this span, if any.
148 expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
151 #[derive(RustcEncodable)]
152 struct DiagnosticSpanLine {
155 /// 1-based, character offset in self.text.
156 highlight_start: usize,
158 highlight_end: usize,
161 #[derive(RustcEncodable)]
162 struct DiagnosticSpanMacroExpansion {
163 /// span where macro was applied to generate this code; note that
164 /// this may itself derive from a macro (if
165 /// `span.expansion.is_some()`)
166 span: DiagnosticSpan,
168 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
169 macro_decl_name: String,
171 /// span where macro was defined (if known)
172 def_site_span: Option<DiagnosticSpan>,
175 #[derive(RustcEncodable)]
176 struct DiagnosticCode {
179 /// An explanation for the code.
180 explanation: Option<&'static str>,
183 #[derive(RustcEncodable)]
185 /// The directive itself.
190 fn from_diagnostic_builder(db: &DiagnosticBuilder<'_>,
193 let sugg = db.suggestions.iter().map(|sugg| {
195 message: sugg.msg.clone(),
198 spans: DiagnosticSpan::from_suggestion(sugg, je),
204 // generate regular command line output and store it in the json
206 // A threadsafe buffer for writing.
207 #[derive(Default, Clone)]
208 struct BufWriter(Arc<Mutex<Vec<u8>>>);
210 impl Write for BufWriter {
211 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
212 self.0.lock().unwrap().write(buf)
214 fn flush(&mut self) -> io::Result<()> {
215 self.0.lock().unwrap().flush()
218 let buf = BufWriter::default();
219 let output = buf.clone();
220 je.json_rendered.new_emitter(Box::new(buf), Some(je.sm.clone()), false)
221 .ui_testing(je.ui_testing).emit_diagnostic(db);
222 let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
223 let output = String::from_utf8(output).unwrap();
226 message: db.message(),
227 code: DiagnosticCode::map_opt_string(db.code.clone(), je),
228 level: db.level.to_str(),
229 spans: DiagnosticSpan::from_multispan(&db.span, je),
230 children: db.children.iter().map(|c| {
231 Diagnostic::from_sub_diagnostic(c, je)
232 }).chain(sugg).collect(),
233 rendered: Some(output),
237 fn from_sub_diagnostic(db: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic {
239 message: db.message(),
241 level: db.level.to_str(),
242 spans: db.render_span.as_ref()
243 .map(|sp| DiagnosticSpan::from_multispan(sp, je))
244 .unwrap_or_else(|| DiagnosticSpan::from_multispan(&db.span, je)),
251 impl DiagnosticSpan {
252 fn from_span_label(span: SpanLabel,
253 suggestion: Option<(&String, Applicability)>,
256 Self::from_span_etc(span.span,
263 fn from_span_etc(span: Span,
265 label: Option<String>,
266 suggestion: Option<(&String, Applicability)>,
269 // obtain the full backtrace from the `macro_backtrace`
270 // helper; in some ways, it'd be better to expand the
271 // backtrace ourselves, but the `macro_backtrace` helper makes
272 // some decision, such as dropping some frames, and I don't
273 // want to duplicate that logic here.
274 let backtrace = span.macro_backtrace().into_iter();
275 DiagnosticSpan::from_span_full(span,
283 fn from_span_full(span: Span,
285 label: Option<String>,
286 suggestion: Option<(&String, Applicability)>,
287 mut backtrace: vec::IntoIter<MacroBacktrace>,
290 let start = je.sm.lookup_char_pos(span.lo());
291 let end = je.sm.lookup_char_pos(span.hi());
292 let backtrace_step = backtrace.next().map(|bt| {
294 Self::from_span_full(bt.call_site,
300 let def_site_span = bt.def_site_span.map(|sp| {
301 Self::from_span_full(sp,
308 Box::new(DiagnosticSpanMacroExpansion {
310 macro_decl_name: bt.macro_decl_name,
316 file_name: start.file.name.to_string(),
317 byte_start: span.lo().0 - start.file.start_pos.0,
318 byte_end: span.hi().0 - start.file.start_pos.0,
319 line_start: start.line,
321 column_start: start.col.0 + 1,
322 column_end: end.col.0 + 1,
324 text: DiagnosticSpanLine::from_span(span, je),
325 suggested_replacement: suggestion.map(|x| x.0.clone()),
326 suggestion_applicability: suggestion.map(|x| x.1),
327 expansion: backtrace_step,
332 fn from_multispan(msp: &MultiSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
335 .map(|span_str| Self::from_span_label(span_str, None, je))
339 fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter)
340 -> Vec<DiagnosticSpan> {
341 suggestion.substitutions
343 .flat_map(|substitution| {
344 substitution.parts.iter().map(move |suggestion_inner| {
345 let span_label = SpanLabel {
346 span: suggestion_inner.span,
350 DiagnosticSpan::from_span_label(span_label,
351 Some((&suggestion_inner.snippet,
352 suggestion.applicability)),
360 impl DiagnosticSpanLine {
361 fn line_from_source_file(fm: &syntax_pos::SourceFile,
365 -> DiagnosticSpanLine {
367 text: fm.get_line(index).map_or(String::new(), |l| l.into_owned()),
368 highlight_start: h_start,
369 highlight_end: h_end,
373 /// Creates a list of DiagnosticSpanLines from span - each line with any part
374 /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
375 /// `span` within the line.
376 fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
377 je.sm.span_to_lines(span)
379 let fm = &*lines.file;
382 .map(|line| DiagnosticSpanLine::line_from_source_file(
385 line.start_col.0 + 1,
388 }).unwrap_or_else(|_| vec![])
392 impl DiagnosticCode {
393 fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
396 DiagnosticId::Error(s) => s,
397 DiagnosticId::Lint(s) => s,
399 let explanation = je.registry
401 .and_then(|registry| registry.find_description(&s));