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, artifact_type: &str) {
96 let data = ArtifactNotification { artifact: path, emit: artifact_type };
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.
188 /// What kind of artifact we're emitting.
193 fn from_diagnostic_builder(db: &DiagnosticBuilder<'_>,
196 let sugg = db.suggestions.iter().map(|sugg| {
198 message: sugg.msg.clone(),
201 spans: DiagnosticSpan::from_suggestion(sugg, je),
207 // generate regular command line output and store it in the json
209 // A threadsafe buffer for writing.
210 #[derive(Default, Clone)]
211 struct BufWriter(Arc<Mutex<Vec<u8>>>);
213 impl Write for BufWriter {
214 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
215 self.0.lock().unwrap().write(buf)
217 fn flush(&mut self) -> io::Result<()> {
218 self.0.lock().unwrap().flush()
221 let buf = BufWriter::default();
222 let output = buf.clone();
223 je.json_rendered.new_emitter(Box::new(buf), Some(je.sm.clone()), false)
224 .ui_testing(je.ui_testing).emit_diagnostic(db);
225 let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
226 let output = String::from_utf8(output).unwrap();
229 message: db.message(),
230 code: DiagnosticCode::map_opt_string(db.code.clone(), je),
231 level: db.level.to_str(),
232 spans: DiagnosticSpan::from_multispan(&db.span, je),
233 children: db.children.iter().map(|c| {
234 Diagnostic::from_sub_diagnostic(c, je)
235 }).chain(sugg).collect(),
236 rendered: Some(output),
240 fn from_sub_diagnostic(db: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic {
242 message: db.message(),
244 level: db.level.to_str(),
245 spans: db.render_span.as_ref()
246 .map(|sp| DiagnosticSpan::from_multispan(sp, je))
247 .unwrap_or_else(|| DiagnosticSpan::from_multispan(&db.span, je)),
254 impl DiagnosticSpan {
255 fn from_span_label(span: SpanLabel,
256 suggestion: Option<(&String, Applicability)>,
259 Self::from_span_etc(span.span,
266 fn from_span_etc(span: Span,
268 label: Option<String>,
269 suggestion: Option<(&String, Applicability)>,
272 // obtain the full backtrace from the `macro_backtrace`
273 // helper; in some ways, it'd be better to expand the
274 // backtrace ourselves, but the `macro_backtrace` helper makes
275 // some decision, such as dropping some frames, and I don't
276 // want to duplicate that logic here.
277 let backtrace = span.macro_backtrace().into_iter();
278 DiagnosticSpan::from_span_full(span,
286 fn from_span_full(span: Span,
288 label: Option<String>,
289 suggestion: Option<(&String, Applicability)>,
290 mut backtrace: vec::IntoIter<MacroBacktrace>,
293 let start = je.sm.lookup_char_pos(span.lo());
294 let end = je.sm.lookup_char_pos(span.hi());
295 let backtrace_step = backtrace.next().map(|bt| {
297 Self::from_span_full(bt.call_site,
303 let def_site_span = bt.def_site_span.map(|sp| {
304 Self::from_span_full(sp,
311 Box::new(DiagnosticSpanMacroExpansion {
313 macro_decl_name: bt.macro_decl_name,
319 file_name: start.file.name.to_string(),
320 byte_start: span.lo().0 - start.file.start_pos.0,
321 byte_end: span.hi().0 - start.file.start_pos.0,
322 line_start: start.line,
324 column_start: start.col.0 + 1,
325 column_end: end.col.0 + 1,
327 text: DiagnosticSpanLine::from_span(span, je),
328 suggested_replacement: suggestion.map(|x| x.0.clone()),
329 suggestion_applicability: suggestion.map(|x| x.1),
330 expansion: backtrace_step,
335 fn from_multispan(msp: &MultiSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
338 .map(|span_str| Self::from_span_label(span_str, None, je))
342 fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter)
343 -> Vec<DiagnosticSpan> {
344 suggestion.substitutions
346 .flat_map(|substitution| {
347 substitution.parts.iter().map(move |suggestion_inner| {
348 let span_label = SpanLabel {
349 span: suggestion_inner.span,
353 DiagnosticSpan::from_span_label(span_label,
354 Some((&suggestion_inner.snippet,
355 suggestion.applicability)),
363 impl DiagnosticSpanLine {
364 fn line_from_source_file(fm: &syntax_pos::SourceFile,
368 -> DiagnosticSpanLine {
370 text: fm.get_line(index).map_or(String::new(), |l| l.into_owned()),
371 highlight_start: h_start,
372 highlight_end: h_end,
376 /// Creates a list of DiagnosticSpanLines from span - each line with any part
377 /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
378 /// `span` within the line.
379 fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
380 je.sm.span_to_lines(span)
382 let fm = &*lines.file;
385 .map(|line| DiagnosticSpanLine::line_from_source_file(
388 line.start_col.0 + 1,
391 }).unwrap_or_else(|_| vec![])
395 impl DiagnosticCode {
396 fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
399 DiagnosticId::Error(s) => s,
400 DiagnosticId::Lint(s) => s,
402 let explanation = je.registry
404 .and_then(|registry| registry.find_description(&s));