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 rustc_span::source_map::{FilePathMapping, SourceMap};
14 use crate::emitter::{Emitter, HumanReadableErrorType};
15 use crate::registry::Registry;
16 use crate::DiagnosticId;
17 use crate::ToolMetadata;
18 use crate::{CodeSuggestion, FluentBundle, MultiSpan, SpanLabel, SubDiagnostic};
19 use rustc_lint_defs::Applicability;
21 use rustc_data_structures::sync::Lrc;
22 use rustc_error_messages::FluentArgs;
23 use rustc_span::hygiene::ExpnData;
25 use std::io::{self, Write};
27 use std::sync::{Arc, Mutex};
30 use rustc_serialize::json::{as_json, as_pretty_json};
31 use rustc_serialize::{Encodable, Encoder};
36 pub struct JsonEmitter {
37 dst: Box<dyn Write + Send>,
38 registry: Option<Registry>,
40 fluent_bundle: Option<Lrc<FluentBundle>>,
41 fallback_bundle: Lrc<FluentBundle>,
44 json_rendered: HumanReadableErrorType,
45 terminal_width: Option<usize>,
46 macro_backtrace: bool,
51 registry: Option<Registry>,
52 source_map: Lrc<SourceMap>,
53 fluent_bundle: Option<Lrc<FluentBundle>>,
54 fallback_bundle: Lrc<FluentBundle>,
56 json_rendered: HumanReadableErrorType,
57 terminal_width: Option<usize>,
58 macro_backtrace: bool,
61 dst: Box::new(io::BufWriter::new(io::stderr())),
76 json_rendered: HumanReadableErrorType,
77 fluent_bundle: Option<Lrc<FluentBundle>>,
78 fallback_bundle: Lrc<FluentBundle>,
79 terminal_width: Option<usize>,
80 macro_backtrace: bool,
82 let file_path_mapping = FilePathMapping::empty();
85 Lrc::new(SourceMap::new(file_path_mapping)),
96 dst: Box<dyn Write + Send>,
97 registry: Option<Registry>,
98 source_map: Lrc<SourceMap>,
99 fluent_bundle: Option<Lrc<FluentBundle>>,
100 fallback_bundle: Lrc<FluentBundle>,
102 json_rendered: HumanReadableErrorType,
103 terminal_width: Option<usize>,
104 macro_backtrace: bool,
120 pub fn ui_testing(self, ui_testing: bool) -> Self {
121 Self { ui_testing, ..self }
125 impl Emitter for JsonEmitter {
126 fn emit_diagnostic(&mut self, diag: &crate::Diagnostic) {
127 let data = Diagnostic::from_errors_diagnostic(diag, self);
128 let result = if self.pretty {
129 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
131 writeln!(&mut self.dst, "{}", as_json(&data))
133 .and_then(|_| self.dst.flush());
134 if let Err(e) = result {
135 panic!("failed to print diagnostics: {:?}", e);
139 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
140 let data = ArtifactNotification { artifact: path, emit: artifact_type };
141 let result = if self.pretty {
142 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
144 writeln!(&mut self.dst, "{}", as_json(&data))
146 .and_then(|_| self.dst.flush());
147 if let Err(e) = result {
148 panic!("failed to print notification: {:?}", e);
152 fn emit_future_breakage_report(&mut self, diags: Vec<crate::Diagnostic>) {
153 let data: Vec<FutureBreakageItem> = diags
156 if diag.level == crate::Level::Allow {
157 diag.level = crate::Level::Warning;
159 FutureBreakageItem { diagnostic: Diagnostic::from_errors_diagnostic(&diag, self) }
162 let report = FutureIncompatReport { future_incompat_report: data };
163 let result = if self.pretty {
164 writeln!(&mut self.dst, "{}", as_pretty_json(&report))
166 writeln!(&mut self.dst, "{}", as_json(&report))
168 .and_then(|_| self.dst.flush());
169 if let Err(e) = result {
170 panic!("failed to print future breakage report: {:?}", e);
174 fn emit_unused_externs(&mut self, lint_level: &str, unused_externs: &[&str]) {
175 let data = UnusedExterns { lint_level, unused_extern_names: unused_externs };
176 let result = if self.pretty {
177 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
179 writeln!(&mut self.dst, "{}", as_json(&data))
181 .and_then(|_| self.dst.flush());
182 if let Err(e) = result {
183 panic!("failed to print unused externs: {:?}", e);
187 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
191 fn fluent_bundle(&self) -> Option<&Lrc<FluentBundle>> {
192 self.fluent_bundle.as_ref()
195 fn fallback_fluent_bundle(&self) -> &Lrc<FluentBundle> {
196 &self.fallback_bundle
199 fn should_show_explain(&self) -> bool {
200 !matches!(self.json_rendered, HumanReadableErrorType::Short(_))
204 // The following data types are provided just for serialisation.
206 // NOTE: this has a manual implementation of Encodable which needs to be updated in
209 /// The primary error message.
211 code: Option<DiagnosticCode>,
212 /// "error: internal compiler error", "error", "warning", "note", "help".
214 spans: Vec<DiagnosticSpan>,
215 /// Associated diagnostic messages.
216 children: Vec<Diagnostic>,
217 /// The message as rustc would render it.
218 rendered: Option<String>,
219 /// Extra tool metadata
220 tool_metadata: ToolMetadata,
223 macro_rules! encode_fields {
225 $enc:expr, // encoder
226 $idx:expr, // starting field index
227 $struct:expr, // struct we're serializing
228 $struct_name:ident, // struct name
229 [ $($name:ident),+$(,)? ], // fields to encode
230 [ $($ignore:ident),+$(,)? ] // fields we're skipping
233 // Pattern match to make sure all fields are accounted for
234 let $struct_name { $($name,)+ $($ignore: _,)+ } = $struct;
237 $enc.emit_struct_field(
240 |enc| $name.encode(enc),
249 // Special-case encoder to skip tool_metadata if not set
250 impl<E: Encoder> Encodable<E> for Diagnostic {
251 fn encode(&self, s: &mut E) -> Result<(), E::Error> {
252 s.emit_struct(false, |s| {
255 idx = encode_fields!(
260 [message, code, level, spans, children, rendered],
263 if self.tool_metadata.is_set() {
264 idx = encode_fields!(
270 [message, code, level, spans, children, rendered]
281 struct DiagnosticSpan {
288 /// 1-based, character offset.
291 /// Is this a "primary" span -- meaning the point, or one of the points,
292 /// where the error occurred?
294 /// Source text from the start of line_start to the end of line_end.
295 text: Vec<DiagnosticSpanLine>,
296 /// Label that should be placed at this location (if any)
297 label: Option<String>,
298 /// If we are suggesting a replacement, this will contain text
299 /// that should be sliced in atop this span.
300 suggested_replacement: Option<String>,
301 /// If the suggestion is approximate
302 suggestion_applicability: Option<Applicability>,
303 /// Macro invocations that created the code at this span, if any.
304 expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
308 struct DiagnosticSpanLine {
311 /// 1-based, character offset in self.text.
312 highlight_start: usize,
314 highlight_end: usize,
318 struct DiagnosticSpanMacroExpansion {
319 /// span where macro was applied to generate this code; note that
320 /// this may itself derive from a macro (if
321 /// `span.expansion.is_some()`)
322 span: DiagnosticSpan,
324 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
325 macro_decl_name: String,
327 /// span where macro was defined (if known)
328 def_site_span: DiagnosticSpan,
332 struct DiagnosticCode {
335 /// An explanation for the code.
336 explanation: Option<&'static str>,
340 struct ArtifactNotification<'a> {
341 /// The path of the artifact.
343 /// What kind of artifact we're emitting.
348 struct FutureBreakageItem {
349 diagnostic: Diagnostic,
353 struct FutureIncompatReport {
354 future_incompat_report: Vec<FutureBreakageItem>,
357 // NOTE: Keep this in sync with the equivalent structs in rustdoc's
358 // doctest component (as well as cargo).
359 // We could unify this struct the one in rustdoc but they have different
360 // ownership semantics, so doing so would create wasteful allocations.
362 struct UnusedExterns<'a, 'b, 'c> {
363 /// The severity level of the unused dependencies lint
365 /// List of unused externs by their names.
366 unused_extern_names: &'b [&'c str],
370 fn from_errors_diagnostic(diag: &crate::Diagnostic, je: &JsonEmitter) -> Diagnostic {
371 let args = je.to_fluent_args(diag.args());
372 let sugg = diag.suggestions.iter().flatten().map(|sugg| {
373 let translated_message = je.translate_message(&sugg.msg, &args);
375 message: translated_message.to_string(),
378 spans: DiagnosticSpan::from_suggestion(sugg, &args, je),
381 tool_metadata: sugg.tool_metadata.clone(),
385 // generate regular command line output and store it in the json
387 // A threadsafe buffer for writing.
388 #[derive(Default, Clone)]
389 struct BufWriter(Arc<Mutex<Vec<u8>>>);
391 impl Write for BufWriter {
392 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
393 self.0.lock().unwrap().write(buf)
395 fn flush(&mut self) -> io::Result<()> {
396 self.0.lock().unwrap().flush()
399 let buf = BufWriter::default();
400 let output = buf.clone();
405 je.fluent_bundle.clone(),
406 je.fallback_bundle.clone(),
411 .ui_testing(je.ui_testing)
412 .emit_diagnostic(diag);
413 let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
414 let output = String::from_utf8(output).unwrap();
416 let translated_message = je.translate_messages(&diag.message, &args);
418 message: translated_message.to_string(),
419 code: DiagnosticCode::map_opt_string(diag.code.clone(), je),
420 level: diag.level.to_str(),
421 spans: DiagnosticSpan::from_multispan(&diag.span, &args, je),
425 .map(|c| Diagnostic::from_sub_diagnostic(c, &args, je))
428 rendered: Some(output),
429 tool_metadata: ToolMetadata::default(),
433 fn from_sub_diagnostic(
434 diag: &SubDiagnostic,
435 args: &FluentArgs<'_>,
438 let translated_message = je.translate_messages(&diag.message, args);
440 message: translated_message.to_string(),
442 level: diag.level.to_str(),
446 .map(|sp| DiagnosticSpan::from_multispan(sp, args, je))
447 .unwrap_or_else(|| DiagnosticSpan::from_multispan(&diag.span, args, je)),
450 tool_metadata: ToolMetadata::default(),
455 impl DiagnosticSpan {
458 suggestion: Option<(&String, Applicability)>,
459 args: &FluentArgs<'_>,
461 ) -> DiagnosticSpan {
465 span.label.as_ref().map(|m| je.translate_message(m, args)).map(|m| m.to_string()),
474 label: Option<String>,
475 suggestion: Option<(&String, Applicability)>,
477 ) -> DiagnosticSpan {
478 // obtain the full backtrace from the `macro_backtrace`
479 // helper; in some ways, it'd be better to expand the
480 // backtrace ourselves, but the `macro_backtrace` helper makes
481 // some decision, such as dropping some frames, and I don't
482 // want to duplicate that logic here.
483 let backtrace = span.macro_backtrace();
484 DiagnosticSpan::from_span_full(span, is_primary, label, suggestion, backtrace, je)
490 label: Option<String>,
491 suggestion: Option<(&String, Applicability)>,
492 mut backtrace: impl Iterator<Item = ExpnData>,
494 ) -> DiagnosticSpan {
495 let start = je.sm.lookup_char_pos(span.lo());
496 let end = je.sm.lookup_char_pos(span.hi());
497 let backtrace_step = backtrace.next().map(|bt| {
498 let call_site = Self::from_span_full(bt.call_site, false, None, None, backtrace, je);
499 let def_site_span = Self::from_span_full(
500 je.sm.guess_head_span(bt.def_site),
507 Box::new(DiagnosticSpanMacroExpansion {
509 macro_decl_name: bt.kind.descr(),
515 file_name: je.sm.filename_for_diagnostics(&start.file.name).to_string(),
516 byte_start: start.file.original_relative_byte_pos(span.lo()).0,
517 byte_end: start.file.original_relative_byte_pos(span.hi()).0,
518 line_start: start.line,
520 column_start: start.col.0 + 1,
521 column_end: end.col.0 + 1,
523 text: DiagnosticSpanLine::from_span(span, je),
524 suggested_replacement: suggestion.map(|x| x.0.clone()),
525 suggestion_applicability: suggestion.map(|x| x.1),
526 expansion: backtrace_step,
533 args: &FluentArgs<'_>,
535 ) -> Vec<DiagnosticSpan> {
538 .map(|span_str| Self::from_span_label(span_str, None, args, je))
543 suggestion: &CodeSuggestion,
544 args: &FluentArgs<'_>,
546 ) -> Vec<DiagnosticSpan> {
550 .flat_map(|substitution| {
551 substitution.parts.iter().map(move |suggestion_inner| {
553 SpanLabel { span: suggestion_inner.span, is_primary: true, label: None };
554 DiagnosticSpan::from_span_label(
556 Some((&suggestion_inner.snippet, suggestion.applicability)),
566 impl DiagnosticSpanLine {
567 fn line_from_source_file(
568 sf: &rustc_span::SourceFile,
572 ) -> DiagnosticSpanLine {
574 text: sf.get_line(index).map_or_else(String::new, |l| l.into_owned()),
575 highlight_start: h_start,
576 highlight_end: h_end,
580 /// Creates a list of DiagnosticSpanLines from span - each line with any part
581 /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
582 /// `span` within the line.
583 fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
587 // We can't get any lines if the source is unavailable.
588 if !je.sm.ensure_source_file_source_present(lines.file.clone()) {
592 let sf = &*lines.file;
597 DiagnosticSpanLine::line_from_source_file(
600 line.start_col.0 + 1,
606 .unwrap_or_else(|_| vec![])
610 impl DiagnosticCode {
611 fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
614 DiagnosticId::Error(s) => s,
615 DiagnosticId::Lint { name, .. } => name,
618 je.registry.as_ref().map(|registry| registry.try_find_description(&s)).unwrap();
620 DiagnosticCode { code: s, explanation: je_result.unwrap_or(None) }