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::translation::{to_fluent_args, Translate};
17 use crate::DiagnosticId;
19 CodeSuggestion, FluentBundle, LazyFallbackBundle, MultiSpan, SpanLabel, SubDiagnostic,
21 use rustc_lint_defs::Applicability;
23 use rustc_data_structures::sync::Lrc;
24 use rustc_error_messages::FluentArgs;
25 use rustc_span::hygiene::ExpnData;
27 use std::io::{self, Write};
29 use std::sync::{Arc, Mutex};
37 pub struct JsonEmitter {
38 dst: Box<dyn Write + Send>,
39 registry: Option<Registry>,
41 fluent_bundle: Option<Lrc<FluentBundle>>,
42 fallback_bundle: LazyFallbackBundle,
45 json_rendered: HumanReadableErrorType,
46 diagnostic_width: Option<usize>,
47 macro_backtrace: bool,
48 track_diagnostics: bool,
53 registry: Option<Registry>,
54 source_map: Lrc<SourceMap>,
55 fluent_bundle: Option<Lrc<FluentBundle>>,
56 fallback_bundle: LazyFallbackBundle,
58 json_rendered: HumanReadableErrorType,
59 diagnostic_width: Option<usize>,
60 macro_backtrace: bool,
61 track_diagnostics: bool,
64 dst: Box::new(io::BufWriter::new(io::stderr())),
80 json_rendered: HumanReadableErrorType,
81 fluent_bundle: Option<Lrc<FluentBundle>>,
82 fallback_bundle: LazyFallbackBundle,
83 diagnostic_width: Option<usize>,
84 macro_backtrace: bool,
85 track_diagnostics: bool,
87 let file_path_mapping = FilePathMapping::empty();
90 Lrc::new(SourceMap::new(file_path_mapping)),
102 dst: Box<dyn Write + Send>,
103 registry: Option<Registry>,
104 source_map: Lrc<SourceMap>,
105 fluent_bundle: Option<Lrc<FluentBundle>>,
106 fallback_bundle: LazyFallbackBundle,
108 json_rendered: HumanReadableErrorType,
109 diagnostic_width: Option<usize>,
110 macro_backtrace: bool,
111 track_diagnostics: bool,
128 pub fn ui_testing(self, ui_testing: bool) -> Self {
129 Self { ui_testing, ..self }
133 impl Translate for JsonEmitter {
134 fn fluent_bundle(&self) -> Option<&Lrc<FluentBundle>> {
135 self.fluent_bundle.as_ref()
138 fn fallback_fluent_bundle(&self) -> &FluentBundle {
139 &self.fallback_bundle
143 impl Emitter for JsonEmitter {
144 fn emit_diagnostic(&mut self, diag: &crate::Diagnostic) {
145 let data = Diagnostic::from_errors_diagnostic(diag, self);
146 let result = if self.pretty {
147 writeln!(&mut self.dst, "{}", serde_json::to_string_pretty(&data).unwrap())
149 writeln!(&mut self.dst, "{}", serde_json::to_string(&data).unwrap())
151 .and_then(|_| self.dst.flush());
152 if let Err(e) = result {
153 panic!("failed to print diagnostics: {:?}", e);
157 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
158 let data = ArtifactNotification { artifact: path, emit: artifact_type };
159 let result = if self.pretty {
160 writeln!(&mut self.dst, "{}", serde_json::to_string_pretty(&data).unwrap())
162 writeln!(&mut self.dst, "{}", serde_json::to_string(&data).unwrap())
164 .and_then(|_| self.dst.flush());
165 if let Err(e) = result {
166 panic!("failed to print notification: {:?}", e);
170 fn emit_future_breakage_report(&mut self, diags: Vec<crate::Diagnostic>) {
171 let data: Vec<FutureBreakageItem> = diags
174 if diag.level == crate::Level::Allow {
175 diag.level = crate::Level::Warning(None);
177 FutureBreakageItem { diagnostic: Diagnostic::from_errors_diagnostic(&diag, self) }
180 let report = FutureIncompatReport { future_incompat_report: data };
181 let result = if self.pretty {
182 writeln!(&mut self.dst, "{}", serde_json::to_string_pretty(&report).unwrap())
184 writeln!(&mut self.dst, "{}", serde_json::to_string(&report).unwrap())
186 .and_then(|_| self.dst.flush());
187 if let Err(e) = result {
188 panic!("failed to print future breakage report: {:?}", e);
192 fn emit_unused_externs(&mut self, lint_level: rustc_lint_defs::Level, unused_externs: &[&str]) {
193 let lint_level = lint_level.as_str();
194 let data = UnusedExterns { lint_level, unused_extern_names: unused_externs };
195 let result = if self.pretty {
196 writeln!(&mut self.dst, "{}", serde_json::to_string_pretty(&data).unwrap())
198 writeln!(&mut self.dst, "{}", serde_json::to_string(&data).unwrap())
200 .and_then(|_| self.dst.flush());
201 if let Err(e) = result {
202 panic!("failed to print unused externs: {:?}", e);
206 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
210 fn should_show_explain(&self) -> bool {
211 !matches!(self.json_rendered, HumanReadableErrorType::Short(_))
215 // The following data types are provided just for serialisation.
219 /// The primary error message.
221 code: Option<DiagnosticCode>,
222 /// "error: internal compiler error", "error", "warning", "note", "help".
224 spans: Vec<DiagnosticSpan>,
225 /// Associated diagnostic messages.
226 children: Vec<Diagnostic>,
227 /// The message as rustc would render it.
228 rendered: Option<String>,
232 struct DiagnosticSpan {
239 /// 1-based, character offset.
242 /// Is this a "primary" span -- meaning the point, or one of the points,
243 /// where the error occurred?
245 /// Source text from the start of line_start to the end of line_end.
246 text: Vec<DiagnosticSpanLine>,
247 /// Label that should be placed at this location (if any)
248 label: Option<String>,
249 /// If we are suggesting a replacement, this will contain text
250 /// that should be sliced in atop this span.
251 suggested_replacement: Option<String>,
252 /// If the suggestion is approximate
253 suggestion_applicability: Option<Applicability>,
254 /// Macro invocations that created the code at this span, if any.
255 expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
259 struct DiagnosticSpanLine {
262 /// 1-based, character offset in self.text.
263 highlight_start: usize,
265 highlight_end: usize,
269 struct DiagnosticSpanMacroExpansion {
270 /// span where macro was applied to generate this code; note that
271 /// this may itself derive from a macro (if
272 /// `span.expansion.is_some()`)
273 span: DiagnosticSpan,
275 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
276 macro_decl_name: String,
278 /// span where macro was defined (if known)
279 def_site_span: DiagnosticSpan,
283 struct DiagnosticCode {
286 /// An explanation for the code.
287 explanation: Option<&'static str>,
291 struct ArtifactNotification<'a> {
292 /// The path of the artifact.
294 /// What kind of artifact we're emitting.
299 struct FutureBreakageItem {
300 diagnostic: Diagnostic,
304 struct FutureIncompatReport {
305 future_incompat_report: Vec<FutureBreakageItem>,
308 // NOTE: Keep this in sync with the equivalent structs in rustdoc's
309 // doctest component (as well as cargo).
310 // We could unify this struct the one in rustdoc but they have different
311 // ownership semantics, so doing so would create wasteful allocations.
313 struct UnusedExterns<'a, 'b, 'c> {
314 /// The severity level of the unused dependencies lint
316 /// List of unused externs by their names.
317 unused_extern_names: &'b [&'c str],
321 fn from_errors_diagnostic(diag: &crate::Diagnostic, je: &JsonEmitter) -> Diagnostic {
322 let args = to_fluent_args(diag.args());
323 let sugg = diag.suggestions.iter().flatten().map(|sugg| {
324 let translated_message = je.translate_message(&sugg.msg, &args);
326 message: translated_message.to_string(),
329 spans: DiagnosticSpan::from_suggestion(sugg, &args, je),
335 // generate regular command line output and store it in the json
337 // A threadsafe buffer for writing.
338 #[derive(Default, Clone)]
339 struct BufWriter(Arc<Mutex<Vec<u8>>>);
341 impl Write for BufWriter {
342 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
343 self.0.lock().unwrap().write(buf)
345 fn flush(&mut self) -> io::Result<()> {
346 self.0.lock().unwrap().flush()
349 let buf = BufWriter::default();
350 let output = buf.clone();
355 je.fluent_bundle.clone(),
356 je.fallback_bundle.clone(),
360 je.track_diagnostics,
362 .ui_testing(je.ui_testing)
363 .emit_diagnostic(diag);
364 let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
365 let output = String::from_utf8(output).unwrap();
367 let translated_message = je.translate_messages(&diag.message, &args);
369 message: translated_message.to_string(),
370 code: DiagnosticCode::map_opt_string(diag.code.clone(), je),
371 level: diag.level.to_str(),
372 spans: DiagnosticSpan::from_multispan(&diag.span, &args, je),
376 .map(|c| Diagnostic::from_sub_diagnostic(c, &args, je))
379 rendered: Some(output),
383 fn from_sub_diagnostic(
384 diag: &SubDiagnostic,
385 args: &FluentArgs<'_>,
388 let translated_message = je.translate_messages(&diag.message, args);
390 message: translated_message.to_string(),
392 level: diag.level.to_str(),
396 .map(|sp| DiagnosticSpan::from_multispan(sp, args, je))
397 .unwrap_or_else(|| DiagnosticSpan::from_multispan(&diag.span, args, je)),
404 impl DiagnosticSpan {
407 suggestion: Option<(&String, Applicability)>,
408 args: &FluentArgs<'_>,
410 ) -> DiagnosticSpan {
414 span.label.as_ref().map(|m| je.translate_message(m, args)).map(|m| m.to_string()),
423 label: Option<String>,
424 suggestion: Option<(&String, Applicability)>,
426 ) -> DiagnosticSpan {
427 // obtain the full backtrace from the `macro_backtrace`
428 // helper; in some ways, it'd be better to expand the
429 // backtrace ourselves, but the `macro_backtrace` helper makes
430 // some decision, such as dropping some frames, and I don't
431 // want to duplicate that logic here.
432 let backtrace = span.macro_backtrace();
433 DiagnosticSpan::from_span_full(span, is_primary, label, suggestion, backtrace, je)
439 label: Option<String>,
440 suggestion: Option<(&String, Applicability)>,
441 mut backtrace: impl Iterator<Item = ExpnData>,
443 ) -> DiagnosticSpan {
444 let start = je.sm.lookup_char_pos(span.lo());
445 let end = je.sm.lookup_char_pos(span.hi());
446 let backtrace_step = backtrace.next().map(|bt| {
447 let call_site = Self::from_span_full(bt.call_site, false, None, None, backtrace, je);
448 let def_site_span = Self::from_span_full(
449 je.sm.guess_head_span(bt.def_site),
456 Box::new(DiagnosticSpanMacroExpansion {
458 macro_decl_name: bt.kind.descr(),
464 file_name: je.sm.filename_for_diagnostics(&start.file.name).to_string(),
465 byte_start: start.file.original_relative_byte_pos(span.lo()).0,
466 byte_end: start.file.original_relative_byte_pos(span.hi()).0,
467 line_start: start.line,
469 column_start: start.col.0 + 1,
470 column_end: end.col.0 + 1,
472 text: DiagnosticSpanLine::from_span(span, je),
473 suggested_replacement: suggestion.map(|x| x.0.clone()),
474 suggestion_applicability: suggestion.map(|x| x.1),
475 expansion: backtrace_step,
482 args: &FluentArgs<'_>,
484 ) -> Vec<DiagnosticSpan> {
487 .map(|span_str| Self::from_span_label(span_str, None, args, je))
492 suggestion: &CodeSuggestion,
493 args: &FluentArgs<'_>,
495 ) -> Vec<DiagnosticSpan> {
499 .flat_map(|substitution| {
500 substitution.parts.iter().map(move |suggestion_inner| {
502 SpanLabel { span: suggestion_inner.span, is_primary: true, label: None };
503 DiagnosticSpan::from_span_label(
505 Some((&suggestion_inner.snippet, suggestion.applicability)),
515 impl DiagnosticSpanLine {
516 fn line_from_source_file(
517 sf: &rustc_span::SourceFile,
521 ) -> DiagnosticSpanLine {
523 text: sf.get_line(index).map_or_else(String::new, |l| l.into_owned()),
524 highlight_start: h_start,
525 highlight_end: h_end,
529 /// Creates a list of DiagnosticSpanLines from span - each line with any part
530 /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
531 /// `span` within the line.
532 fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
536 // We can't get any lines if the source is unavailable.
537 if !je.sm.ensure_source_file_source_present(lines.file.clone()) {
541 let sf = &*lines.file;
546 DiagnosticSpanLine::line_from_source_file(
549 line.start_col.0 + 1,
555 .unwrap_or_else(|_| vec![])
559 impl DiagnosticCode {
560 fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
563 DiagnosticId::Error(s) => s,
564 DiagnosticId::Lint { name, .. } => name,
567 je.registry.as_ref().map(|registry| registry.try_find_description(&s)).unwrap();
569 DiagnosticCode { code: s, explanation: je_result.unwrap_or(None) }