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