rustc_errors/
json.rs

1//! A JSON emitter for errors.
2//!
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.
6//!
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.
9
10// FIXME: spec the JSON output properly.
11
12use std::error::Report;
13use std::io::{self, Write};
14use std::path::Path;
15use std::sync::{Arc, Mutex};
16use std::vec;
17
18use anstream::{AutoStream, ColorChoice};
19use derive_setters::Setters;
20use rustc_data_structures::sync::IntoDynSyncSend;
21use rustc_error_messages::FluentArgs;
22use rustc_lint_defs::Applicability;
23use rustc_span::Span;
24use rustc_span::hygiene::ExpnData;
25use rustc_span::source_map::{FilePathMapping, SourceMap};
26use serde::Serialize;
27
28use crate::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;
29use crate::diagnostic::IsLint;
30use crate::emitter::{
31    ColorConfig, Destination, Emitter, HumanEmitter, HumanReadableErrorType, OutputTheme,
32    TimingEvent, should_show_source_code,
33};
34use crate::registry::Registry;
35use crate::timings::{TimingRecord, TimingSection};
36use crate::translation::{Translator, to_fluent_args};
37use crate::{CodeSuggestion, MultiSpan, SpanLabel, Subdiag, Suggestions, TerminalUrl};
38
39#[cfg(test)]
40mod tests;
41
42#[derive(Setters)]
43pub struct JsonEmitter {
44    #[setters(skip)]
45    dst: IntoDynSyncSend<Box<dyn Write + Send>>,
46    #[setters(skip)]
47    sm: Option<Arc<SourceMap>>,
48    #[setters(skip)]
49    translator: Translator,
50    #[setters(skip)]
51    pretty: bool,
52    ui_testing: bool,
53    ignored_directories_in_source_blocks: Vec<String>,
54    #[setters(skip)]
55    json_rendered: HumanReadableErrorType,
56    color_config: ColorConfig,
57    diagnostic_width: Option<usize>,
58    macro_backtrace: bool,
59    track_diagnostics: bool,
60    terminal_url: TerminalUrl,
61}
62
63impl JsonEmitter {
64    pub fn new(
65        dst: Box<dyn Write + Send>,
66        sm: Option<Arc<SourceMap>>,
67        translator: Translator,
68        pretty: bool,
69        json_rendered: HumanReadableErrorType,
70        color_config: ColorConfig,
71    ) -> JsonEmitter {
72        JsonEmitter {
73            dst: IntoDynSyncSend(dst),
74            sm,
75            translator,
76            pretty,
77            ui_testing: false,
78            ignored_directories_in_source_blocks: Vec::new(),
79            json_rendered,
80            color_config,
81            diagnostic_width: None,
82            macro_backtrace: false,
83            track_diagnostics: false,
84            terminal_url: TerminalUrl::No,
85        }
86    }
87
88    fn emit(&mut self, val: EmitTyped<'_>) -> io::Result<()> {
89        if self.pretty {
90            serde_json::to_writer_pretty(&mut *self.dst, &val)?
91        } else {
92            serde_json::to_writer(&mut *self.dst, &val)?
93        };
94        self.dst.write_all(b"\n")?;
95        self.dst.flush()
96    }
97}
98
99#[derive(Serialize)]
100#[serde(tag = "$message_type", rename_all = "snake_case")]
101enum EmitTyped<'a> {
102    Diagnostic(Diagnostic),
103    Artifact(ArtifactNotification<'a>),
104    SectionTiming(SectionTimestamp<'a>),
105    FutureIncompat(FutureIncompatReport<'a>),
106    UnusedExtern(UnusedExterns<'a>),
107}
108
109impl Emitter for JsonEmitter {
110    fn emit_diagnostic(&mut self, diag: crate::DiagInner, registry: &Registry) {
111        let data = Diagnostic::from_errors_diagnostic(diag, self, registry);
112        let result = self.emit(EmitTyped::Diagnostic(data));
113        if let Err(e) = result {
114            panic!("failed to print diagnostics: {e:?}");
115        }
116    }
117
118    fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
119        let data = ArtifactNotification { artifact: path, emit: artifact_type };
120        let result = self.emit(EmitTyped::Artifact(data));
121        if let Err(e) = result {
122            panic!("failed to print notification: {e:?}");
123        }
124    }
125
126    fn emit_timing_section(&mut self, record: TimingRecord, event: TimingEvent) {
127        let event = match event {
128            TimingEvent::Start => "start",
129            TimingEvent::End => "end",
130        };
131        let name = match record.section {
132            TimingSection::Linking => "link",
133            TimingSection::Codegen => "codegen",
134        };
135        let data = SectionTimestamp { name, event, timestamp: record.timestamp };
136        let result = self.emit(EmitTyped::SectionTiming(data));
137        if let Err(e) = result {
138            panic!("failed to print timing section: {e:?}");
139        }
140    }
141
142    fn emit_future_breakage_report(&mut self, diags: Vec<crate::DiagInner>, registry: &Registry) {
143        let data: Vec<FutureBreakageItem<'_>> = diags
144            .into_iter()
145            .map(|mut diag| {
146                // Allowed or expected lints don't normally (by definition) emit a lint
147                // but future incompat lints are special and are emitted anyway.
148                //
149                // So to avoid ICEs and confused users we "upgrade" the lint level for
150                // those `FutureBreakageItem` to warn.
151                if matches!(diag.level, crate::Level::Allow | crate::Level::Expect) {
152                    diag.level = crate::Level::Warning;
153                }
154                FutureBreakageItem {
155                    diagnostic: EmitTyped::Diagnostic(Diagnostic::from_errors_diagnostic(
156                        diag, self, registry,
157                    )),
158                }
159            })
160            .collect();
161        let report = FutureIncompatReport { future_incompat_report: data };
162        let result = self.emit(EmitTyped::FutureIncompat(report));
163        if let Err(e) = result {
164            panic!("failed to print future breakage report: {e:?}");
165        }
166    }
167
168    fn emit_unused_externs(&mut self, lint_level: rustc_lint_defs::Level, unused_externs: &[&str]) {
169        let lint_level = lint_level.as_str();
170        let data = UnusedExterns { lint_level, unused_extern_names: unused_externs };
171        let result = self.emit(EmitTyped::UnusedExtern(data));
172        if let Err(e) = result {
173            panic!("failed to print unused externs: {e:?}");
174        }
175    }
176
177    fn source_map(&self) -> Option<&SourceMap> {
178        self.sm.as_deref()
179    }
180
181    fn should_show_explain(&self) -> bool {
182        !self.json_rendered.short()
183    }
184
185    fn translator(&self) -> &Translator {
186        &self.translator
187    }
188}
189
190// The following data types are provided just for serialisation.
191
192#[derive(Serialize)]
193struct Diagnostic {
194    /// The primary error message.
195    message: String,
196    code: Option<DiagnosticCode>,
197    /// "error: internal compiler error", "error", "warning", "note", "help".
198    level: &'static str,
199    spans: Vec<DiagnosticSpan>,
200    /// Associated diagnostic messages.
201    children: Vec<Diagnostic>,
202    /// The message as rustc would render it.
203    rendered: Option<String>,
204}
205
206#[derive(Serialize)]
207struct DiagnosticSpan {
208    file_name: String,
209    byte_start: u32,
210    byte_end: u32,
211    /// 1-based.
212    line_start: usize,
213    line_end: usize,
214    /// 1-based, character offset.
215    column_start: usize,
216    column_end: usize,
217    /// Is this a "primary" span -- meaning the point, or one of the points,
218    /// where the error occurred?
219    is_primary: bool,
220    /// Source text from the start of line_start to the end of line_end.
221    text: Vec<DiagnosticSpanLine>,
222    /// Label that should be placed at this location (if any)
223    label: Option<String>,
224    /// If we are suggesting a replacement, this will contain text
225    /// that should be sliced in atop this span.
226    suggested_replacement: Option<String>,
227    /// If the suggestion is approximate
228    suggestion_applicability: Option<Applicability>,
229    /// Macro invocations that created the code at this span, if any.
230    expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
231}
232
233#[derive(Serialize)]
234struct DiagnosticSpanLine {
235    text: String,
236
237    /// 1-based, character offset in self.text.
238    highlight_start: usize,
239
240    highlight_end: usize,
241}
242
243#[derive(Serialize)]
244struct DiagnosticSpanMacroExpansion {
245    /// span where macro was applied to generate this code; note that
246    /// this may itself derive from a macro (if
247    /// `span.expansion.is_some()`)
248    span: DiagnosticSpan,
249
250    /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
251    macro_decl_name: String,
252
253    /// span where macro was defined (if known)
254    def_site_span: DiagnosticSpan,
255}
256
257#[derive(Serialize)]
258struct DiagnosticCode {
259    /// The error code (e.g. "E1234"), if the diagnostic has one. Or the lint
260    /// name, if it's a lint without an error code.
261    code: String,
262    /// An explanation for the code.
263    explanation: Option<&'static str>,
264}
265
266#[derive(Serialize)]
267struct ArtifactNotification<'a> {
268    /// The path of the artifact.
269    artifact: &'a Path,
270    /// What kind of artifact we're emitting.
271    emit: &'a str,
272}
273
274#[derive(Serialize)]
275struct SectionTimestamp<'a> {
276    /// Name of the section
277    name: &'a str,
278    /// Start/end of the section
279    event: &'a str,
280    /// Opaque timestamp.
281    timestamp: u128,
282}
283
284#[derive(Serialize)]
285struct FutureBreakageItem<'a> {
286    // Always EmitTyped::Diagnostic, but we want to make sure it gets serialized
287    // with "$message_type".
288    diagnostic: EmitTyped<'a>,
289}
290
291#[derive(Serialize)]
292struct FutureIncompatReport<'a> {
293    future_incompat_report: Vec<FutureBreakageItem<'a>>,
294}
295
296// NOTE: Keep this in sync with the equivalent structs in rustdoc's
297// doctest component (as well as cargo).
298// We could unify this struct the one in rustdoc but they have different
299// ownership semantics, so doing so would create wasteful allocations.
300#[derive(Serialize)]
301struct UnusedExterns<'a> {
302    /// The severity level of the unused dependencies lint
303    lint_level: &'a str,
304    /// List of unused externs by their names.
305    unused_extern_names: &'a [&'a str],
306}
307
308impl Diagnostic {
309    /// Converts from `rustc_errors::DiagInner` to `Diagnostic`.
310    fn from_errors_diagnostic(
311        diag: crate::DiagInner,
312        je: &JsonEmitter,
313        registry: &Registry,
314    ) -> Diagnostic {
315        let args = to_fluent_args(diag.args.iter());
316        let sugg_to_diag = |sugg: &CodeSuggestion| {
317            let translated_message =
318                je.translator.translate_message(&sugg.msg, &args).map_err(Report::new).unwrap();
319            Diagnostic {
320                message: translated_message.to_string(),
321                code: None,
322                level: "help",
323                spans: DiagnosticSpan::from_suggestion(sugg, &args, je),
324                children: vec![],
325                rendered: None,
326            }
327        };
328        let sugg = match &diag.suggestions {
329            Suggestions::Enabled(suggestions) => suggestions.iter().map(sugg_to_diag),
330            Suggestions::Sealed(suggestions) => suggestions.iter().map(sugg_to_diag),
331            Suggestions::Disabled => [].iter().map(sugg_to_diag),
332        };
333
334        // generate regular command line output and store it in the json
335
336        // A threadsafe buffer for writing.
337        #[derive(Clone)]
338        struct BufWriter(Arc<Mutex<Vec<u8>>>);
339
340        impl Write for BufWriter {
341            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
342                self.0.lock().unwrap().write(buf)
343            }
344            fn flush(&mut self) -> io::Result<()> {
345                self.0.lock().unwrap().flush()
346            }
347        }
348
349        let translated_message = je.translator.translate_messages(&diag.messages, &args);
350
351        let code = if let Some(code) = diag.code {
352            Some(DiagnosticCode {
353                code: code.to_string(),
354                explanation: registry.try_find_description(code).ok(),
355            })
356        } else if let Some(IsLint { name, .. }) = &diag.is_lint {
357            Some(DiagnosticCode { code: name.to_string(), explanation: None })
358        } else {
359            None
360        };
361        let level = diag.level.to_str();
362        let spans = DiagnosticSpan::from_multispan(&diag.span, &args, je);
363        let mut children: Vec<Diagnostic> = diag
364            .children
365            .iter()
366            .map(|c| Diagnostic::from_sub_diagnostic(c, &args, je))
367            .chain(sugg)
368            .collect();
369        if je.track_diagnostics && diag.span.has_primary_spans() && !diag.span.is_dummy() {
370            children
371                .insert(0, Diagnostic::from_sub_diagnostic(&diag.emitted_at_sub_diag(), &args, je));
372        }
373        let buf = BufWriter(Arc::new(Mutex::new(Vec::new())));
374        let dst: Destination = AutoStream::new(
375            Box::new(buf.clone()),
376            match je.color_config.to_color_choice() {
377                ColorChoice::Auto => ColorChoice::Always,
378                choice => choice,
379            },
380        );
381        match je.json_rendered {
382            HumanReadableErrorType::AnnotateSnippet { short, unicode } => {
383                AnnotateSnippetEmitter::new(dst, je.translator.clone())
384                    .short_message(short)
385                    .sm(je.sm.clone())
386                    .diagnostic_width(je.diagnostic_width)
387                    .macro_backtrace(je.macro_backtrace)
388                    .track_diagnostics(je.track_diagnostics)
389                    .terminal_url(je.terminal_url)
390                    .ui_testing(je.ui_testing)
391                    .ignored_directories_in_source_blocks(
392                        je.ignored_directories_in_source_blocks.clone(),
393                    )
394                    .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
395                    .emit_diagnostic(diag, registry)
396            }
397            HumanReadableErrorType::Default { short } => {
398                HumanEmitter::new(dst, je.translator.clone())
399                    .short_message(short)
400                    .sm(je.sm.clone())
401                    .diagnostic_width(je.diagnostic_width)
402                    .macro_backtrace(je.macro_backtrace)
403                    .track_diagnostics(je.track_diagnostics)
404                    .terminal_url(je.terminal_url)
405                    .ui_testing(je.ui_testing)
406                    .ignored_directories_in_source_blocks(
407                        je.ignored_directories_in_source_blocks.clone(),
408                    )
409                    .theme(OutputTheme::Ascii)
410                    .emit_diagnostic(diag, registry)
411            }
412        }
413
414        let buf = Arc::try_unwrap(buf.0).unwrap().into_inner().unwrap();
415        let buf = String::from_utf8(buf).unwrap();
416
417        Diagnostic {
418            message: translated_message.to_string(),
419            code,
420            level,
421            spans,
422            children,
423            rendered: Some(buf),
424        }
425    }
426
427    fn from_sub_diagnostic(
428        subdiag: &Subdiag,
429        args: &FluentArgs<'_>,
430        je: &JsonEmitter,
431    ) -> Diagnostic {
432        let translated_message = je.translator.translate_messages(&subdiag.messages, args);
433        Diagnostic {
434            message: translated_message.to_string(),
435            code: None,
436            level: subdiag.level.to_str(),
437            spans: DiagnosticSpan::from_multispan(&subdiag.span, args, je),
438            children: vec![],
439            rendered: None,
440        }
441    }
442}
443
444impl DiagnosticSpan {
445    fn from_span_label(
446        span: SpanLabel,
447        suggestion: Option<(&String, Applicability)>,
448        args: &FluentArgs<'_>,
449        je: &JsonEmitter,
450    ) -> DiagnosticSpan {
451        Self::from_span_etc(
452            span.span,
453            span.is_primary,
454            span.label
455                .as_ref()
456                .map(|m| je.translator.translate_message(m, args).unwrap())
457                .map(|m| m.to_string()),
458            suggestion,
459            je,
460        )
461    }
462
463    fn from_span_etc(
464        span: Span,
465        is_primary: bool,
466        label: Option<String>,
467        suggestion: Option<(&String, Applicability)>,
468        je: &JsonEmitter,
469    ) -> DiagnosticSpan {
470        // obtain the full backtrace from the `macro_backtrace`
471        // helper; in some ways, it'd be better to expand the
472        // backtrace ourselves, but the `macro_backtrace` helper makes
473        // some decision, such as dropping some frames, and I don't
474        // want to duplicate that logic here.
475        let backtrace = span.macro_backtrace();
476        DiagnosticSpan::from_span_full(span, is_primary, label, suggestion, backtrace, je)
477    }
478
479    fn from_span_full(
480        mut span: Span,
481        is_primary: bool,
482        label: Option<String>,
483        suggestion: Option<(&String, Applicability)>,
484        mut backtrace: impl Iterator<Item = ExpnData>,
485        je: &JsonEmitter,
486    ) -> DiagnosticSpan {
487        let empty_source_map;
488        let sm = match &je.sm {
489            Some(s) => s,
490            None => {
491                span = rustc_span::DUMMY_SP;
492                empty_source_map = Arc::new(SourceMap::new(FilePathMapping::empty()));
493                empty_source_map
494                    .new_source_file(std::path::PathBuf::from("empty.rs").into(), String::new());
495                &empty_source_map
496            }
497        };
498        let start = sm.lookup_char_pos(span.lo());
499        // If this goes from the start of a line to the end and the replacement
500        // is an empty string, increase the length to include the newline so we don't
501        // leave an empty line
502        if start.col.0 == 0
503            && let Some((suggestion, _)) = suggestion
504            && suggestion.is_empty()
505            && let Ok(after) = sm.span_to_next_source(span)
506            && after.starts_with('\n')
507        {
508            span = span.with_hi(span.hi() + rustc_span::BytePos(1));
509        }
510        let end = sm.lookup_char_pos(span.hi());
511        let backtrace_step = backtrace.next().map(|bt| {
512            let call_site = Self::from_span_full(bt.call_site, false, None, None, backtrace, je);
513            let def_site_span = Self::from_span_full(
514                sm.guess_head_span(bt.def_site),
515                false,
516                None,
517                None,
518                [].into_iter(),
519                je,
520            );
521            Box::new(DiagnosticSpanMacroExpansion {
522                span: call_site,
523                macro_decl_name: bt.kind.descr(),
524                def_site_span,
525            })
526        });
527
528        DiagnosticSpan {
529            file_name: sm.filename_for_diagnostics(&start.file.name).to_string(),
530            byte_start: start.file.original_relative_byte_pos(span.lo()).0,
531            byte_end: start.file.original_relative_byte_pos(span.hi()).0,
532            line_start: start.line,
533            line_end: end.line,
534            column_start: start.col.0 + 1,
535            column_end: end.col.0 + 1,
536            is_primary,
537            text: DiagnosticSpanLine::from_span(span, je),
538            suggested_replacement: suggestion.map(|x| x.0.clone()),
539            suggestion_applicability: suggestion.map(|x| x.1),
540            expansion: backtrace_step,
541            label,
542        }
543    }
544
545    fn from_multispan(
546        msp: &MultiSpan,
547        args: &FluentArgs<'_>,
548        je: &JsonEmitter,
549    ) -> Vec<DiagnosticSpan> {
550        msp.span_labels()
551            .into_iter()
552            .map(|span_str| Self::from_span_label(span_str, None, args, je))
553            .collect()
554    }
555
556    fn from_suggestion(
557        suggestion: &CodeSuggestion,
558        args: &FluentArgs<'_>,
559        je: &JsonEmitter,
560    ) -> Vec<DiagnosticSpan> {
561        suggestion
562            .substitutions
563            .iter()
564            .flat_map(|substitution| {
565                substitution.parts.iter().map(move |suggestion_inner| {
566                    let span_label =
567                        SpanLabel { span: suggestion_inner.span, is_primary: true, label: None };
568                    DiagnosticSpan::from_span_label(
569                        span_label,
570                        Some((&suggestion_inner.snippet, suggestion.applicability)),
571                        args,
572                        je,
573                    )
574                })
575            })
576            .collect()
577    }
578}
579
580impl DiagnosticSpanLine {
581    fn line_from_source_file(
582        sf: &rustc_span::SourceFile,
583        index: usize,
584        h_start: usize,
585        h_end: usize,
586    ) -> DiagnosticSpanLine {
587        DiagnosticSpanLine {
588            text: sf.get_line(index).map_or_else(String::new, |l| l.into_owned()),
589            highlight_start: h_start,
590            highlight_end: h_end,
591        }
592    }
593
594    /// Creates a list of DiagnosticSpanLines from span - each line with any part
595    /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
596    /// `span` within the line.
597    fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
598        je.sm
599            .as_ref()
600            .and_then(|sm| {
601                let lines = sm.span_to_lines(span).ok()?;
602                // We can't get any lines if the source is unavailable.
603                if !should_show_source_code(
604                    &je.ignored_directories_in_source_blocks,
605                    &sm,
606                    &lines.file,
607                ) {
608                    return None;
609                }
610
611                let sf = &*lines.file;
612                let span_lines = lines
613                    .lines
614                    .iter()
615                    .map(|line| {
616                        DiagnosticSpanLine::line_from_source_file(
617                            sf,
618                            line.line_index,
619                            line.start_col.0 + 1,
620                            line.end_col.0 + 1,
621                        )
622                    })
623                    .collect();
624                Some(span_lines)
625            })
626            .unwrap_or_default()
627    }
628}