Skip to main content

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