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;
18 CodeSuggestion, FluentBundle, LazyFallbackBundle, MultiSpan, SpanLabel, SubDiagnostic,
20 use rustc_lint_defs::Applicability;
22 use rustc_data_structures::sync::Lrc;
23 use rustc_error_messages::FluentArgs;
24 use rustc_span::hygiene::ExpnData;
26 use std::io::{self, Write};
28 use std::sync::{Arc, Mutex};
31 use rustc_serialize::json::{as_json, as_pretty_json};
36 pub struct JsonEmitter {
37 dst: Box<dyn Write + Send>,
38 registry: Option<Registry>,
40 fluent_bundle: Option<Lrc<FluentBundle>>,
41 fallback_bundle: LazyFallbackBundle,
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: LazyFallbackBundle,
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: LazyFallbackBundle,
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: LazyFallbackBundle,
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) -> &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.
208 /// The primary error message.
210 code: Option<DiagnosticCode>,
211 /// "error: internal compiler error", "error", "warning", "note", "help".
213 spans: Vec<DiagnosticSpan>,
214 /// Associated diagnostic messages.
215 children: Vec<Diagnostic>,
216 /// The message as rustc would render it.
217 rendered: Option<String>,
221 struct DiagnosticSpan {
228 /// 1-based, character offset.
231 /// Is this a "primary" span -- meaning the point, or one of the points,
232 /// where the error occurred?
234 /// Source text from the start of line_start to the end of line_end.
235 text: Vec<DiagnosticSpanLine>,
236 /// Label that should be placed at this location (if any)
237 label: Option<String>,
238 /// If we are suggesting a replacement, this will contain text
239 /// that should be sliced in atop this span.
240 suggested_replacement: Option<String>,
241 /// If the suggestion is approximate
242 suggestion_applicability: Option<Applicability>,
243 /// Macro invocations that created the code at this span, if any.
244 expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
248 struct DiagnosticSpanLine {
251 /// 1-based, character offset in self.text.
252 highlight_start: usize,
254 highlight_end: usize,
258 struct DiagnosticSpanMacroExpansion {
259 /// span where macro was applied to generate this code; note that
260 /// this may itself derive from a macro (if
261 /// `span.expansion.is_some()`)
262 span: DiagnosticSpan,
264 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
265 macro_decl_name: String,
267 /// span where macro was defined (if known)
268 def_site_span: DiagnosticSpan,
272 struct DiagnosticCode {
275 /// An explanation for the code.
276 explanation: Option<&'static str>,
280 struct ArtifactNotification<'a> {
281 /// The path of the artifact.
283 /// What kind of artifact we're emitting.
288 struct FutureBreakageItem {
289 diagnostic: Diagnostic,
293 struct FutureIncompatReport {
294 future_incompat_report: Vec<FutureBreakageItem>,
297 // NOTE: Keep this in sync with the equivalent structs in rustdoc's
298 // doctest component (as well as cargo).
299 // We could unify this struct the one in rustdoc but they have different
300 // ownership semantics, so doing so would create wasteful allocations.
302 struct UnusedExterns<'a, 'b, 'c> {
303 /// The severity level of the unused dependencies lint
305 /// List of unused externs by their names.
306 unused_extern_names: &'b [&'c str],
310 fn from_errors_diagnostic(diag: &crate::Diagnostic, je: &JsonEmitter) -> Diagnostic {
311 let args = je.to_fluent_args(diag.args());
312 let sugg = diag.suggestions.iter().flatten().map(|sugg| {
313 let translated_message = je.translate_message(&sugg.msg, &args);
315 message: translated_message.to_string(),
318 spans: DiagnosticSpan::from_suggestion(sugg, &args, je),
324 // generate regular command line output and store it in the json
326 // A threadsafe buffer for writing.
327 #[derive(Default, Clone)]
328 struct BufWriter(Arc<Mutex<Vec<u8>>>);
330 impl Write for BufWriter {
331 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
332 self.0.lock().unwrap().write(buf)
334 fn flush(&mut self) -> io::Result<()> {
335 self.0.lock().unwrap().flush()
338 let buf = BufWriter::default();
339 let output = buf.clone();
344 je.fluent_bundle.clone(),
345 je.fallback_bundle.clone(),
350 .ui_testing(je.ui_testing)
351 .emit_diagnostic(diag);
352 let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
353 let output = String::from_utf8(output).unwrap();
355 let translated_message = je.translate_messages(&diag.message, &args);
357 message: translated_message.to_string(),
358 code: DiagnosticCode::map_opt_string(diag.code.clone(), je),
359 level: diag.level.to_str(),
360 spans: DiagnosticSpan::from_multispan(&diag.span, &args, je),
364 .map(|c| Diagnostic::from_sub_diagnostic(c, &args, je))
367 rendered: Some(output),
371 fn from_sub_diagnostic(
372 diag: &SubDiagnostic,
373 args: &FluentArgs<'_>,
376 let translated_message = je.translate_messages(&diag.message, args);
378 message: translated_message.to_string(),
380 level: diag.level.to_str(),
384 .map(|sp| DiagnosticSpan::from_multispan(sp, args, je))
385 .unwrap_or_else(|| DiagnosticSpan::from_multispan(&diag.span, args, je)),
392 impl DiagnosticSpan {
395 suggestion: Option<(&String, Applicability)>,
396 args: &FluentArgs<'_>,
398 ) -> DiagnosticSpan {
402 span.label.as_ref().map(|m| je.translate_message(m, args)).map(|m| m.to_string()),
411 label: Option<String>,
412 suggestion: Option<(&String, Applicability)>,
414 ) -> DiagnosticSpan {
415 // obtain the full backtrace from the `macro_backtrace`
416 // helper; in some ways, it'd be better to expand the
417 // backtrace ourselves, but the `macro_backtrace` helper makes
418 // some decision, such as dropping some frames, and I don't
419 // want to duplicate that logic here.
420 let backtrace = span.macro_backtrace();
421 DiagnosticSpan::from_span_full(span, is_primary, label, suggestion, backtrace, je)
427 label: Option<String>,
428 suggestion: Option<(&String, Applicability)>,
429 mut backtrace: impl Iterator<Item = ExpnData>,
431 ) -> DiagnosticSpan {
432 let start = je.sm.lookup_char_pos(span.lo());
433 let end = je.sm.lookup_char_pos(span.hi());
434 let backtrace_step = backtrace.next().map(|bt| {
435 let call_site = Self::from_span_full(bt.call_site, false, None, None, backtrace, je);
436 let def_site_span = Self::from_span_full(
437 je.sm.guess_head_span(bt.def_site),
444 Box::new(DiagnosticSpanMacroExpansion {
446 macro_decl_name: bt.kind.descr(),
452 file_name: je.sm.filename_for_diagnostics(&start.file.name).to_string(),
453 byte_start: start.file.original_relative_byte_pos(span.lo()).0,
454 byte_end: start.file.original_relative_byte_pos(span.hi()).0,
455 line_start: start.line,
457 column_start: start.col.0 + 1,
458 column_end: end.col.0 + 1,
460 text: DiagnosticSpanLine::from_span(span, je),
461 suggested_replacement: suggestion.map(|x| x.0.clone()),
462 suggestion_applicability: suggestion.map(|x| x.1),
463 expansion: backtrace_step,
470 args: &FluentArgs<'_>,
472 ) -> Vec<DiagnosticSpan> {
475 .map(|span_str| Self::from_span_label(span_str, None, args, je))
480 suggestion: &CodeSuggestion,
481 args: &FluentArgs<'_>,
483 ) -> Vec<DiagnosticSpan> {
487 .flat_map(|substitution| {
488 substitution.parts.iter().map(move |suggestion_inner| {
490 SpanLabel { span: suggestion_inner.span, is_primary: true, label: None };
491 DiagnosticSpan::from_span_label(
493 Some((&suggestion_inner.snippet, suggestion.applicability)),
503 impl DiagnosticSpanLine {
504 fn line_from_source_file(
505 sf: &rustc_span::SourceFile,
509 ) -> DiagnosticSpanLine {
511 text: sf.get_line(index).map_or_else(String::new, |l| l.into_owned()),
512 highlight_start: h_start,
513 highlight_end: h_end,
517 /// Creates a list of DiagnosticSpanLines from span - each line with any part
518 /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
519 /// `span` within the line.
520 fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
524 // We can't get any lines if the source is unavailable.
525 if !je.sm.ensure_source_file_source_present(lines.file.clone()) {
529 let sf = &*lines.file;
534 DiagnosticSpanLine::line_from_source_file(
537 line.start_col.0 + 1,
543 .unwrap_or_else(|_| vec![])
547 impl DiagnosticCode {
548 fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
551 DiagnosticId::Error(s) => s,
552 DiagnosticId::Lint { name, .. } => name,
555 je.registry.as_ref().map(|registry| registry.try_find_description(&s)).unwrap();
557 DiagnosticCode { code: s, explanation: je_result.unwrap_or(None) }