Skip to main content

solar_interface/diagnostics/emitter/
mod.rs

1//! Diagnostic emitter interfaces and shared rendering helpers.
2//!
3//! Modified from rustc's [`Emitter`](https://github.com/rust-lang/rust/blob/3b58636b30eb364ac72aeaf03d46347084ed87d1/compiler/rustc_errors/src/emitter.rs).
4
5use super::{ConfusionType, Diag, Level, MultiSpan, SuggestionStyle, detect_confusion_type};
6use crate::{SourceMap, diagnostics::Suggestions};
7use std::{any::Any, borrow::Cow, sync::Arc};
8
9mod human;
10pub use human::{HumanBufferEmitter, HumanEmitter};
11
12#[cfg(feature = "json")]
13mod json;
14#[cfg(feature = "json")]
15pub use json::{
16    JsonDiagnostic, JsonDiagnosticCode, JsonDiagnosticMessage, JsonDiagnosticSpan,
17    JsonDiagnosticSpanLine, JsonDiagnosticSpanMacroExpansion, JsonEmitter, Severity,
18    SolcDiagnostic, SourceLocation,
19};
20
21mod mem;
22pub use mem::InMemoryEmitter;
23
24/// Dynamic diagnostic emitter. See [`Emitter`].
25pub type DynEmitter = dyn Emitter + Send;
26
27/// Diagnostic emitter.
28pub trait Emitter: Any {
29    /// Emits a diagnostic.
30    fn emit_diagnostic(&mut self, diagnostic: &mut Diag);
31
32    /// Emits a diagnostic by reference.
33    fn emit_diagnostic_ref(&mut self, diagnostic: &Diag) {
34        let mut diagnostic = diagnostic.clone();
35        self.emit_diagnostic(&mut diagnostic);
36    }
37
38    /// Returns a reference to the source map, if any.
39    #[inline]
40    fn source_map(&self) -> Option<&Arc<SourceMap>> {
41        None
42    }
43
44    /// Returns `true` if we can use colors in the current output stream.
45    #[inline]
46    fn supports_color(&self) -> bool {
47        false
48    }
49
50    /// Formats the substitutions of the primary_span
51    ///
52    /// There are a lot of conditions to this method, but in short:
53    ///
54    /// * If the current `Diag` has only one visible `CodeSuggestion`, we format the `help`
55    ///   suggestion depending on the content of the substitutions. In that case, we modify the span
56    ///   and clear the suggestions.
57    ///
58    /// * If the current `Diag` has multiple suggestions, we leave `primary_span` and the
59    ///   suggestions untouched.
60    fn primary_span_formatted<'a>(
61        &self,
62        primary_span: &mut Cow<'a, MultiSpan>,
63        suggestions: &mut Cow<'a, Suggestions>,
64    ) {
65        if let Some((sugg, rest)) = &suggestions.split_first()
66            // if there are multiple suggestions, print them all in full
67            // to be consistent.
68            && rest.is_empty()
69            // don't display multi-suggestions as labels
70            && let [substitution] = sugg.substitutions.as_slice()
71            // don't display multipart suggestions as labels
72            && let [part] = substitution.parts.as_slice()
73            // don't display long messages as labels
74            && sugg.msg.as_str().split_whitespace().count() < 10
75            // don't display multiline suggestions as labels
76            && !part.snippet.contains('\n')
77            && ![
78                // when this style is set we want the suggestion to be a message, not inline
79                SuggestionStyle::HideCodeAlways,
80                // trivial suggestion for tooling's sake, never shown
81                SuggestionStyle::CompletelyHidden,
82                // subtle suggestion, never shown inline
83                SuggestionStyle::ShowAlways,
84            ].contains(&sugg.style)
85        {
86            let snippet = part.snippet.trim();
87            let msg = if snippet.is_empty() || sugg.style.hide_inline() {
88                // This substitution is only removal OR we explicitly don't want to show the
89                // code inline (`hide_inline`). Therefore, we don't show the substitution.
90                format!("help: {}", sugg.msg.as_str())
91            } else {
92                let confusion_type = self
93                    .source_map()
94                    .map(|sm| detect_confusion_type(sm, snippet, part.span))
95                    .unwrap_or(ConfusionType::None);
96                format!("help: {}{}: `{}`", sugg.msg.as_str(), confusion_type.label_text(), snippet)
97            };
98            primary_span.to_mut().push_span_label(part.span, msg);
99
100            // Since we only return the modified primary_span, we disable suggestions.
101            *suggestions.to_mut() = Suggestions::Disabled;
102        } else {
103            // Do nothing.
104        }
105    }
106}
107
108impl DynEmitter {
109    pub(crate) fn local_buffer(&self) -> Option<&str> {
110        (self as &dyn Any).downcast_ref::<HumanBufferEmitter>().map(HumanBufferEmitter::buffer)
111    }
112}
113
114/// Diagnostic emitter.
115///
116/// Emits fatal diagnostics by default, with `note` if set.
117pub struct SilentEmitter {
118    fatal_emitter: Option<Box<DynEmitter>>,
119    note: Option<String>,
120}
121
122impl SilentEmitter {
123    /// Creates a new `SilentEmitter`. Emits fatal diagnostics with `fatal_emitter`.
124    pub fn new(fatal_emitter: impl Emitter + Send) -> Self {
125        Self::new_boxed(Some(Box::new(fatal_emitter)))
126    }
127
128    /// Creates a new `SilentEmitter`. Emits fatal diagnostics with `fatal_emitter` if `Some`.
129    pub fn new_boxed(fatal_emitter: Option<Box<DynEmitter>>) -> Self {
130        Self { fatal_emitter, note: None }
131    }
132
133    /// Creates a new `SilentEmitter` that does not emit any diagnostics at all.
134    ///
135    /// Same as `new_boxed(None)`.
136    pub fn new_silent() -> Self {
137        Self::new_boxed(None)
138    }
139
140    /// Sets the note to be emitted for fatal diagnostics.
141    pub fn with_note(mut self, note: Option<String>) -> Self {
142        self.note = note;
143        self
144    }
145}
146
147impl Emitter for SilentEmitter {
148    fn emit_diagnostic(&mut self, diagnostic: &mut Diag) {
149        let Some(fatal_emitter) = self.fatal_emitter.as_deref_mut() else { return };
150        if diagnostic.level != Level::Fatal {
151            return;
152        }
153
154        if let Some(note) = &self.note {
155            let mut diagnostic = diagnostic.clone();
156            diagnostic.note(note.clone());
157            fatal_emitter.emit_diagnostic(&mut diagnostic);
158        } else {
159            fatal_emitter.emit_diagnostic(diagnostic);
160        }
161    }
162}
163
164/// Diagnostic emitter that only stores emitted diagnostics.
165#[derive(Clone, Debug)]
166pub struct LocalEmitter {
167    diagnostics: Vec<Diag>,
168}
169
170impl Default for LocalEmitter {
171    fn default() -> Self {
172        Self::new()
173    }
174}
175
176impl LocalEmitter {
177    /// Creates a new `LocalEmitter`.
178    pub fn new() -> Self {
179        Self { diagnostics: Vec::new() }
180    }
181
182    /// Returns a reference to the emitted diagnostics.
183    pub fn diagnostics(&self) -> &[Diag] {
184        &self.diagnostics
185    }
186
187    /// Consumes the emitter and returns the emitted diagnostics.
188    pub fn into_diagnostics(self) -> Vec<Diag> {
189        self.diagnostics
190    }
191}
192
193impl Emitter for LocalEmitter {
194    fn emit_diagnostic(&mut self, diagnostic: &mut Diag) {
195        self.diagnostics.push(diagnostic.clone());
196    }
197}
198
199#[cfg(feature = "json")]
200#[cold]
201#[inline(never)]
202fn io_panic(error: std::io::Error) -> ! {
203    panic!("failed to emit diagnostic: {error}");
204}
205
206// We replace some characters so the CLI output is always consistent and underlines aligned.
207// Keep the following list in sync with `rustc_span::char_width`.
208const OUTPUT_REPLACEMENTS: &[(char, &str)] = &[
209    // In terminals without Unicode support the following will be garbled, but in *all* terminals
210    // the underlying codepoint will be as well. We could gate this replacement behind a "unicode
211    // support" gate.
212    ('\0', "␀"),
213    ('\u{0001}', "␁"),
214    ('\u{0002}', "␂"),
215    ('\u{0003}', "␃"),
216    ('\u{0004}', "␄"),
217    ('\u{0005}', "␅"),
218    ('\u{0006}', "␆"),
219    ('\u{0007}', "␇"),
220    ('\u{0008}', "␈"),
221    ('\t', "    "), // We do our own tab replacement
222    ('\u{000b}', "␋"),
223    ('\u{000c}', "␌"),
224    ('\u{000d}', "␍"),
225    ('\u{000e}', "␎"),
226    ('\u{000f}', "␏"),
227    ('\u{0010}', "␐"),
228    ('\u{0011}', "␑"),
229    ('\u{0012}', "␒"),
230    ('\u{0013}', "␓"),
231    ('\u{0014}', "␔"),
232    ('\u{0015}', "␕"),
233    ('\u{0016}', "␖"),
234    ('\u{0017}', "␗"),
235    ('\u{0018}', "␘"),
236    ('\u{0019}', "␙"),
237    ('\u{001a}', "␚"),
238    ('\u{001b}', "␛"),
239    ('\u{001c}', "␜"),
240    ('\u{001d}', "␝"),
241    ('\u{001e}', "␞"),
242    ('\u{001f}', "␟"),
243    ('\u{007f}', "␡"),
244    ('\u{200d}', ""), // Replace ZWJ for consistent terminal output of grapheme clusters.
245    ('\u{202a}', "�"), // The following unicode text flow control characters are inconsistently
246    ('\u{202b}', "�"), // supported across CLIs and can cause confusion due to the bytes on disk
247    ('\u{202c}', "�"), // not corresponding to the visible source code, so we replace them always.
248    ('\u{202d}', "�"),
249    ('\u{202e}', "�"),
250    ('\u{2066}', "�"),
251    ('\u{2067}', "�"),
252    ('\u{2068}', "�"),
253    ('\u{2069}', "�"),
254];
255
256pub(crate) fn normalize_whitespace(s: &str) -> String {
257    const {
258        let mut i = 1;
259        while i < OUTPUT_REPLACEMENTS.len() {
260            assert!(
261                OUTPUT_REPLACEMENTS[i - 1].0 < OUTPUT_REPLACEMENTS[i].0,
262                "The OUTPUT_REPLACEMENTS array must be sorted (for binary search to work) \
263                and must contain no duplicate entries"
264            );
265            i += 1;
266        }
267    }
268    // Scan the input string for a character in the ordered table above.
269    // If it's present, replace it with its alternative string (it can be more than 1 char!).
270    // Otherwise, retain the input char.
271    s.chars().fold(String::with_capacity(s.len()), |mut s, c| {
272        match OUTPUT_REPLACEMENTS.binary_search_by_key(&c, |(k, _)| *k) {
273            Ok(i) => s.push_str(OUTPUT_REPLACEMENTS[i].1),
274            _ => s.push(c),
275        }
276        s
277    })
278}