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};
31 pub struct JsonEmitter {
32 dst: Box<dyn Write + Send>,
33 registry: Option<Registry>,
34 sm: Lrc<dyn SourceMapper + sync::Send + sync::Sync>,
37 json_rendered: HumanReadableErrorType,
38 external_macro_backtrace: bool,
43 registry: Option<Registry>,
44 source_map: Lrc<SourceMap>,
46 json_rendered: HumanReadableErrorType,
47 external_macro_backtrace: bool,
50 dst: Box::new(io::stderr()),
56 external_macro_backtrace,
62 json_rendered: HumanReadableErrorType,
63 external_macro_backtrace: bool,
65 let file_path_mapping = FilePathMapping::empty();
66 JsonEmitter::stderr(None, Lrc::new(SourceMap::new(file_path_mapping)),
67 pretty, json_rendered, external_macro_backtrace)
71 dst: Box<dyn Write + Send>,
72 registry: Option<Registry>,
73 source_map: Lrc<SourceMap>,
75 json_rendered: HumanReadableErrorType,
76 external_macro_backtrace: bool,
85 external_macro_backtrace,
89 pub fn ui_testing(self, ui_testing: bool) -> Self {
90 Self { ui_testing, ..self }
94 impl Emitter for JsonEmitter {
95 fn emit_diagnostic(&mut self, db: &errors::Diagnostic) {
96 let data = Diagnostic::from_errors_diagnostic(db, self);
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 diagnostics: {:?}", e);
107 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
108 let data = ArtifactNotification { artifact: path, emit: artifact_type };
109 let result = if self.pretty {
110 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
112 writeln!(&mut self.dst, "{}", as_json(&data))
114 if let Err(e) = result {
115 panic!("failed to print notification: {:?}", e);
119 fn should_show_explain(&self) -> bool {
120 match self.json_rendered {
121 HumanReadableErrorType::Short(_) => false,
127 // The following data types are provided just for serialisation.
129 #[derive(RustcEncodable)]
131 /// The primary error message.
133 code: Option<DiagnosticCode>,
134 /// "error: internal compiler error", "error", "warning", "note", "help".
136 spans: Vec<DiagnosticSpan>,
137 /// Associated diagnostic messages.
138 children: Vec<Diagnostic>,
139 /// The message as rustc would render it.
140 rendered: Option<String>,
143 #[derive(RustcEncodable)]
144 struct DiagnosticSpan {
151 /// 1-based, character offset.
154 /// Is this a "primary" span -- meaning the point, or one of the points,
155 /// where the error occurred?
157 /// Source text from the start of line_start to the end of line_end.
158 text: Vec<DiagnosticSpanLine>,
159 /// Label that should be placed at this location (if any)
160 label: Option<String>,
161 /// If we are suggesting a replacement, this will contain text
162 /// that should be sliced in atop this span.
163 suggested_replacement: Option<String>,
164 /// If the suggestion is approximate
165 suggestion_applicability: Option<Applicability>,
166 /// Macro invocations that created the code at this span, if any.
167 expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
170 #[derive(RustcEncodable)]
171 struct DiagnosticSpanLine {
174 /// 1-based, character offset in self.text.
175 highlight_start: usize,
177 highlight_end: usize,
180 #[derive(RustcEncodable)]
181 struct DiagnosticSpanMacroExpansion {
182 /// span where macro was applied to generate this code; note that
183 /// this may itself derive from a macro (if
184 /// `span.expansion.is_some()`)
185 span: DiagnosticSpan,
187 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
188 macro_decl_name: String,
190 /// span where macro was defined (if known)
191 def_site_span: DiagnosticSpan,
194 #[derive(RustcEncodable)]
195 struct DiagnosticCode {
198 /// An explanation for the code.
199 explanation: Option<&'static str>,
202 #[derive(RustcEncodable)]
203 struct ArtifactNotification<'a> {
204 /// The path of the artifact.
206 /// What kind of artifact we're emitting.
211 fn from_errors_diagnostic(db: &errors::Diagnostic,
214 let sugg = db.suggestions.iter().map(|sugg| {
216 message: sugg.msg.clone(),
219 spans: DiagnosticSpan::from_suggestion(sugg, je),
225 // generate regular command line output and store it in the json
227 // A threadsafe buffer for writing.
228 #[derive(Default, Clone)]
229 struct BufWriter(Arc<Mutex<Vec<u8>>>);
231 impl Write for BufWriter {
232 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
233 self.0.lock().unwrap().write(buf)
235 fn flush(&mut self) -> io::Result<()> {
236 self.0.lock().unwrap().flush()
239 let buf = BufWriter::default();
240 let output = buf.clone();
241 je.json_rendered.new_emitter(
242 Box::new(buf), Some(je.sm.clone()), false, None, je.external_macro_backtrace
243 ).ui_testing(je.ui_testing).emit_diagnostic(db);
244 let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
245 let output = String::from_utf8(output).unwrap();
248 message: db.message(),
249 code: DiagnosticCode::map_opt_string(db.code.clone(), je),
250 level: db.level.to_str(),
251 spans: DiagnosticSpan::from_multispan(&db.span, je),
252 children: db.children.iter().map(|c| {
253 Diagnostic::from_sub_diagnostic(c, je)
254 }).chain(sugg).collect(),
255 rendered: Some(output),
259 fn from_sub_diagnostic(db: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic {
261 message: db.message(),
263 level: db.level.to_str(),
264 spans: db.render_span.as_ref()
265 .map(|sp| DiagnosticSpan::from_multispan(sp, je))
266 .unwrap_or_else(|| DiagnosticSpan::from_multispan(&db.span, je)),
273 impl DiagnosticSpan {
274 fn from_span_label(span: SpanLabel,
275 suggestion: Option<(&String, Applicability)>,
278 Self::from_span_etc(span.span,
285 fn from_span_etc(span: Span,
287 label: Option<String>,
288 suggestion: Option<(&String, Applicability)>,
291 // obtain the full backtrace from the `macro_backtrace`
292 // helper; in some ways, it'd be better to expand the
293 // backtrace ourselves, but the `macro_backtrace` helper makes
294 // some decision, such as dropping some frames, and I don't
295 // want to duplicate that logic here.
296 let backtrace = span.macro_backtrace().into_iter();
297 DiagnosticSpan::from_span_full(span,
305 fn from_span_full(span: Span,
307 label: Option<String>,
308 suggestion: Option<(&String, Applicability)>,
309 mut backtrace: vec::IntoIter<MacroBacktrace>,
312 let start = je.sm.lookup_char_pos(span.lo());
313 let end = je.sm.lookup_char_pos(span.hi());
314 let backtrace_step = backtrace.next().map(|bt| {
316 Self::from_span_full(bt.call_site,
323 Self::from_span_full(bt.def_site_span,
329 Box::new(DiagnosticSpanMacroExpansion {
331 macro_decl_name: bt.macro_decl_name,
337 file_name: start.file.name.to_string(),
338 byte_start: start.file.original_relative_byte_pos(span.lo()).0,
339 byte_end: start.file.original_relative_byte_pos(span.hi()).0,
340 line_start: start.line,
342 column_start: start.col.0 + 1,
343 column_end: end.col.0 + 1,
345 text: DiagnosticSpanLine::from_span(span, je),
346 suggested_replacement: suggestion.map(|x| x.0.clone()),
347 suggestion_applicability: suggestion.map(|x| x.1),
348 expansion: backtrace_step,
353 fn from_multispan(msp: &MultiSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
356 .map(|span_str| Self::from_span_label(span_str, None, je))
360 fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter)
361 -> Vec<DiagnosticSpan> {
362 suggestion.substitutions
364 .flat_map(|substitution| {
365 substitution.parts.iter().map(move |suggestion_inner| {
366 let span_label = SpanLabel {
367 span: suggestion_inner.span,
371 DiagnosticSpan::from_span_label(span_label,
372 Some((&suggestion_inner.snippet,
373 suggestion.applicability)),
381 impl DiagnosticSpanLine {
382 fn line_from_source_file(fm: &syntax_pos::SourceFile,
386 -> DiagnosticSpanLine {
388 text: fm.get_line(index).map_or(String::new(), |l| l.into_owned()),
389 highlight_start: h_start,
390 highlight_end: h_end,
394 /// Creates a list of DiagnosticSpanLines from span - each line with any part
395 /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
396 /// `span` within the line.
397 fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
398 je.sm.span_to_lines(span)
400 let fm = &*lines.file;
403 .map(|line| DiagnosticSpanLine::line_from_source_file(
406 line.start_col.0 + 1,
409 }).unwrap_or_else(|_| vec![])
413 impl DiagnosticCode {
414 fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
417 DiagnosticId::Error(s) => s,
418 DiagnosticId::Lint(s) => s,
420 let explanation = je.registry
422 .and_then(|registry| registry.find_description(&s));