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, EmitterWriter};
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>,
36 pub fn stderr(registry: Option<Registry>,
37 source_map: Lrc<SourceMap>,
38 pretty: bool) -> JsonEmitter {
40 dst: Box::new(io::stderr()),
48 pub fn basic(pretty: bool) -> JsonEmitter {
49 let file_path_mapping = FilePathMapping::empty();
50 JsonEmitter::stderr(None, Lrc::new(SourceMap::new(file_path_mapping)),
54 pub fn new(dst: Box<dyn Write + Send>,
55 registry: Option<Registry>,
56 source_map: Lrc<SourceMap>,
57 pretty: bool) -> JsonEmitter {
67 pub fn ui_testing(self, ui_testing: bool) -> Self {
68 Self { ui_testing, ..self }
72 impl Emitter for JsonEmitter {
73 fn emit(&mut self, db: &DiagnosticBuilder<'_>) {
74 let data = Diagnostic::from_diagnostic_builder(db, self);
75 let result = if self.pretty {
76 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
78 writeln!(&mut self.dst, "{}", as_json(&data))
80 if let Err(e) = result {
81 panic!("failed to print diagnostics: {:?}", e);
86 // The following data types are provided just for serialisation.
88 #[derive(RustcEncodable)]
90 /// The primary error message.
92 code: Option<DiagnosticCode>,
93 /// "error: internal compiler error", "error", "warning", "note", "help".
95 spans: Vec<DiagnosticSpan>,
96 /// Associated diagnostic messages.
97 children: Vec<Diagnostic>,
98 /// The message as rustc would render it.
99 rendered: Option<String>,
102 #[derive(RustcEncodable)]
103 #[allow(unused_attributes)]
104 struct DiagnosticSpan {
111 /// 1-based, character offset.
114 /// Is this a "primary" span -- meaning the point, or one of the points,
115 /// where the error occurred?
117 /// Source text from the start of line_start to the end of line_end.
118 text: Vec<DiagnosticSpanLine>,
119 /// Label that should be placed at this location (if any)
120 label: Option<String>,
121 /// If we are suggesting a replacement, this will contain text
122 /// that should be sliced in atop this span.
123 suggested_replacement: Option<String>,
124 /// If the suggestion is approximate
125 suggestion_applicability: Option<Applicability>,
126 /// Macro invocations that created the code at this span, if any.
127 expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
130 #[derive(RustcEncodable)]
131 struct DiagnosticSpanLine {
134 /// 1-based, character offset in self.text.
135 highlight_start: usize,
137 highlight_end: usize,
140 #[derive(RustcEncodable)]
141 struct DiagnosticSpanMacroExpansion {
142 /// span where macro was applied to generate this code; note that
143 /// this may itself derive from a macro (if
144 /// `span.expansion.is_some()`)
145 span: DiagnosticSpan,
147 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
148 macro_decl_name: String,
150 /// span where macro was defined (if known)
151 def_site_span: Option<DiagnosticSpan>,
154 #[derive(RustcEncodable)]
155 struct DiagnosticCode {
158 /// An explanation for the code.
159 explanation: Option<&'static str>,
163 fn from_diagnostic_builder(db: &DiagnosticBuilder<'_>,
166 let sugg = db.suggestions.iter().map(|sugg| {
168 message: sugg.msg.clone(),
171 spans: DiagnosticSpan::from_suggestion(sugg, je),
177 // generate regular command line output and store it in the json
179 // A threadsafe buffer for writing.
180 #[derive(Default, Clone)]
181 struct BufWriter(Arc<Mutex<Vec<u8>>>);
183 impl Write for BufWriter {
184 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
185 self.0.lock().unwrap().write(buf)
187 fn flush(&mut self) -> io::Result<()> {
188 self.0.lock().unwrap().flush()
191 let buf = BufWriter::default();
192 let output = buf.clone();
193 EmitterWriter::new(Box::new(buf), Some(je.sm.clone()), false, false)
194 .ui_testing(je.ui_testing).emit(db);
195 let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
196 let output = String::from_utf8(output).unwrap();
199 message: db.message(),
200 code: DiagnosticCode::map_opt_string(db.code.clone(), je),
201 level: db.level.to_str(),
202 spans: DiagnosticSpan::from_multispan(&db.span, je),
203 children: db.children.iter().map(|c| {
204 Diagnostic::from_sub_diagnostic(c, je)
205 }).chain(sugg).collect(),
206 rendered: Some(output),
210 fn from_sub_diagnostic(db: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic {
212 message: db.message(),
214 level: db.level.to_str(),
215 spans: db.render_span.as_ref()
216 .map(|sp| DiagnosticSpan::from_multispan(sp, je))
217 .unwrap_or_else(|| DiagnosticSpan::from_multispan(&db.span, je)),
224 impl DiagnosticSpan {
225 fn from_span_label(span: SpanLabel,
226 suggestion: Option<(&String, Applicability)>,
229 Self::from_span_etc(span.span,
236 fn from_span_etc(span: Span,
238 label: Option<String>,
239 suggestion: Option<(&String, Applicability)>,
242 // obtain the full backtrace from the `macro_backtrace`
243 // helper; in some ways, it'd be better to expand the
244 // backtrace ourselves, but the `macro_backtrace` helper makes
245 // some decision, such as dropping some frames, and I don't
246 // want to duplicate that logic here.
247 let backtrace = span.macro_backtrace().into_iter();
248 DiagnosticSpan::from_span_full(span,
256 fn from_span_full(span: Span,
258 label: Option<String>,
259 suggestion: Option<(&String, Applicability)>,
260 mut backtrace: vec::IntoIter<MacroBacktrace>,
263 let start = je.sm.lookup_char_pos(span.lo());
264 let end = je.sm.lookup_char_pos(span.hi());
265 let backtrace_step = backtrace.next().map(|bt| {
267 Self::from_span_full(bt.call_site,
273 let def_site_span = bt.def_site_span.map(|sp| {
274 Self::from_span_full(sp,
281 Box::new(DiagnosticSpanMacroExpansion {
283 macro_decl_name: bt.macro_decl_name,
289 file_name: start.file.name.to_string(),
290 byte_start: span.lo().0 - start.file.start_pos.0,
291 byte_end: span.hi().0 - start.file.start_pos.0,
292 line_start: start.line,
294 column_start: start.col.0 + 1,
295 column_end: end.col.0 + 1,
297 text: DiagnosticSpanLine::from_span(span, je),
298 suggested_replacement: suggestion.map(|x| x.0.clone()),
299 suggestion_applicability: suggestion.map(|x| x.1),
300 expansion: backtrace_step,
305 fn from_multispan(msp: &MultiSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
308 .map(|span_str| Self::from_span_label(span_str, None, je))
312 fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter)
313 -> Vec<DiagnosticSpan> {
314 suggestion.substitutions
316 .flat_map(|substitution| {
317 substitution.parts.iter().map(move |suggestion_inner| {
318 let span_label = SpanLabel {
319 span: suggestion_inner.span,
323 DiagnosticSpan::from_span_label(span_label,
324 Some((&suggestion_inner.snippet,
325 suggestion.applicability)),
333 impl DiagnosticSpanLine {
334 fn line_from_source_file(fm: &syntax_pos::SourceFile,
338 -> DiagnosticSpanLine {
340 text: fm.get_line(index).map_or(String::new(), |l| l.into_owned()),
341 highlight_start: h_start,
342 highlight_end: h_end,
346 /// Creates a list of DiagnosticSpanLines from span - each line with any part
347 /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
348 /// `span` within the line.
349 fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
350 je.sm.span_to_lines(span)
352 let fm = &*lines.file;
356 DiagnosticSpanLine::line_from_source_file(fm,
358 line.start_col.0 + 1,
363 .unwrap_or_else(|_| vec![])
367 impl DiagnosticCode {
368 fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
371 DiagnosticId::Error(s) => s,
372 DiagnosticId::Lint(s) => s,
374 let explanation = je.registry
376 .and_then(|registry| registry.find_description(&s));