solar_interface/diagnostics/emitter/
mod.rs1use 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
24pub type DynEmitter = dyn Emitter + Send;
26
27pub trait Emitter: Any {
29 fn emit_diagnostic(&mut self, diagnostic: &mut Diag);
31
32 fn emit_diagnostic_ref(&mut self, diagnostic: &Diag) {
34 let mut diagnostic = diagnostic.clone();
35 self.emit_diagnostic(&mut diagnostic);
36 }
37
38 #[inline]
40 fn source_map(&self) -> Option<&Arc<SourceMap>> {
41 None
42 }
43
44 #[inline]
46 fn supports_color(&self) -> bool {
47 false
48 }
49
50 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 && rest.is_empty()
69 && let [substitution] = sugg.substitutions.as_slice()
71 && let [part] = substitution.parts.as_slice()
73 && sugg.msg.as_str().split_whitespace().count() < 10
75 && !part.snippet.contains('\n')
77 && ![
78 SuggestionStyle::HideCodeAlways,
80 SuggestionStyle::CompletelyHidden,
82 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 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 *suggestions.to_mut() = Suggestions::Disabled;
102 } else {
103 }
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
114pub struct SilentEmitter {
118 fatal_emitter: Option<Box<DynEmitter>>,
119 note: Option<String>,
120}
121
122impl SilentEmitter {
123 pub fn new(fatal_emitter: impl Emitter + Send) -> Self {
125 Self::new_boxed(Some(Box::new(fatal_emitter)))
126 }
127
128 pub fn new_boxed(fatal_emitter: Option<Box<DynEmitter>>) -> Self {
130 Self { fatal_emitter, note: None }
131 }
132
133 pub fn new_silent() -> Self {
137 Self::new_boxed(None)
138 }
139
140 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#[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 pub fn new() -> Self {
179 Self { diagnostics: Vec::new() }
180 }
181
182 pub fn diagnostics(&self) -> &[Diag] {
184 &self.diagnostics
185 }
186
187 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
206const OUTPUT_REPLACEMENTS: &[(char, &str)] = &[
209 ('\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', " "), ('\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}', ""), ('\u{202a}', "�"), ('\u{202b}', "�"), ('\u{202c}', "�"), ('\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 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}