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