1use super::{Emitter, human::HumanBufferEmitter, io_panic};
7use crate::{
8 Span,
9 diagnostics::{
10 Applicability, CodeSuggestion, Diag, Level, MultiSpan, SpanLabel, SubDiagnostic,
11 },
12 source_map::{LineInfo, SourceFile, SourceMap},
13};
14use anstream::ColorChoice;
15use serde::{Deserialize, Serialize};
16use solar_config::HumanEmitterKind;
17use std::{borrow::Cow, io, sync::Arc};
18
19pub struct JsonEmitter {
21 writer: Box<dyn io::Write + Send>,
22 pretty: bool,
23 rustc_like: bool,
24
25 human_emitter: HumanBufferEmitter,
26}
27
28impl Emitter for JsonEmitter {
29 fn emit_diagnostic(&mut self, diagnostic: &mut Diag) {
30 self.emit_diagnostic_ref(diagnostic);
31 }
32
33 fn emit_diagnostic_ref(&mut self, diagnostic: &Diag) {
34 if self.rustc_like {
35 let diagnostic = self.diagnostic(diagnostic);
36 self.emit(&JsonDiagnosticMessage::Diagnostic(diagnostic))
37 } else {
38 let diagnostic = self.solc_diagnostic(diagnostic);
39 self.emit(&diagnostic)
40 }
41 .unwrap_or_else(|e| io_panic(e));
42 }
43
44 fn source_map(&self) -> Option<&Arc<SourceMap>> {
45 Emitter::source_map(&self.human_emitter)
46 }
47}
48
49impl JsonEmitter {
50 pub fn new(
52 writer: Box<dyn io::Write + Send>,
53 source_map: Arc<SourceMap>,
54 color_choice: ColorChoice,
55 ) -> Self {
56 let color_choice =
57 if color_choice == ColorChoice::Auto { ColorChoice::Never } else { color_choice };
58 Self {
59 writer,
60 pretty: false,
61 rustc_like: false,
62 human_emitter: HumanBufferEmitter::new(color_choice).source_map(Some(source_map)),
63 }
64 }
65
66 pub fn pretty(mut self, pretty: bool) -> Self {
68 self.pretty = pretty;
69 self
70 }
71
72 pub fn rustc_like(mut self, yes: bool) -> Self {
76 self.rustc_like = yes;
77 self
78 }
79
80 pub fn ui_testing(mut self, yes: bool) -> Self {
82 self.human_emitter = self.human_emitter.ui_testing(yes);
83 self
84 }
85
86 pub fn human_kind(mut self, kind: HumanEmitterKind) -> Self {
88 self.human_emitter = self.human_emitter.human_kind(kind);
89 self
90 }
91
92 pub fn terminal_width(mut self, width: Option<usize>) -> Self {
94 self.human_emitter = self.human_emitter.terminal_width(width);
95 self
96 }
97
98 fn source_map(&self) -> &Arc<SourceMap> {
99 Emitter::source_map(self).unwrap()
100 }
101
102 fn diagnostic(&mut self, diagnostic: &Diag) -> JsonDiagnostic<'static> {
103 let children = diagnostic
105 .children
106 .iter()
107 .map(|sub| self.sub_diagnostic(sub))
108 .chain(
109 diagnostic
110 .suggestions
111 .iter()
112 .flat_map(|suggestion| self.suggestion_to_diagnostics(suggestion)),
113 )
114 .collect();
115
116 JsonDiagnostic {
117 message: Cow::Owned(diagnostic.label().into_owned()),
118 code: diagnostic.id().map(|code| JsonDiagnosticCode {
119 code: Cow::Owned(code.to_string()),
120 explanation: None,
121 }),
122 level: Cow::Borrowed(diagnostic.level.to_str()),
123 spans: self.spans(&diagnostic.span),
124 children,
125 rendered: Some(Cow::Owned(self.emit_diagnostic_to_buffer(diagnostic))),
126 }
127 }
128
129 fn sub_diagnostic(&self, diagnostic: &SubDiagnostic) -> JsonDiagnostic<'static> {
130 JsonDiagnostic {
131 message: Cow::Owned(diagnostic.label().into_owned()),
132 code: None,
133 level: Cow::Borrowed(diagnostic.level.to_str()),
134 spans: self.spans(&diagnostic.span),
135 children: vec![],
136 rendered: None,
137 }
138 }
139
140 fn suggestion_to_diagnostics<'a>(
141 &'a self,
142 suggestion: &'a CodeSuggestion,
143 ) -> impl Iterator<Item = JsonDiagnostic<'static>> + 'a {
144 suggestion.substitutions.iter().map(move |substitution| {
145 let spans = substitution
146 .parts
147 .iter()
148 .map(|part| {
149 self.span_with_suggestion(
150 part.span,
151 part.snippet.to_string(),
152 suggestion.applicability,
153 )
154 })
155 .collect();
156 JsonDiagnostic {
157 message: Cow::Owned(suggestion.msg.as_str().to_string()),
158 code: None,
159 level: Cow::Borrowed("help"),
160 spans,
161 children: vec![],
162 rendered: None,
163 }
164 })
165 }
166
167 fn spans(&self, msp: &MultiSpan) -> Vec<JsonDiagnosticSpan<'static>> {
168 msp.span_labels().iter().map(|label| self.span(label)).collect()
169 }
170
171 fn span(&self, label: &SpanLabel) -> JsonDiagnosticSpan<'static> {
172 let sm = &**self.source_map();
173 let span = label.span;
174 let start = sm.lookup_char_pos(span.lo());
175 let end = sm.lookup_char_pos(span.hi());
176 JsonDiagnosticSpan {
177 file_name: Cow::Owned(sm.filename_for_diagnostics(&start.file.name).to_string()),
178 byte_start: start.file.original_relative_byte_pos(span.lo()).0,
179 byte_end: start.file.original_relative_byte_pos(span.hi()).0,
180 line_start: start.line,
181 line_end: end.line,
182 column_start: start.col.0 + 1,
183 column_end: end.col.0 + 1,
184 is_primary: label.is_primary,
185 text: self.span_lines(span),
186 label: label.label.as_ref().map(|msg| Cow::Owned(msg.as_str().to_string())),
187 suggested_replacement: None,
188 suggestion_applicability: None,
189 expansion: None,
190 }
191 }
192
193 fn span_with_suggestion(
194 &self,
195 span: Span,
196 replacement: String,
197 applicability: Applicability,
198 ) -> JsonDiagnosticSpan<'static> {
199 let sm = &**self.source_map();
200 let start = sm.lookup_char_pos(span.lo());
201 let span = if start.col.0 == 0
202 && replacement.is_empty()
203 && span.hi() < start.file.end_position()
204 && start.file.contains(span.hi())
205 && start
206 .file
207 .src
208 .get(start.file.relative_position(span.hi()).to_usize()..)
209 .is_some_and(|after| after.starts_with('\n'))
210 {
211 span.with_hi(span.hi() + crate::BytePos(1))
212 } else {
213 span
214 };
215 let start = sm.lookup_char_pos(span.lo());
216 let end = sm.lookup_char_pos(span.hi());
217 JsonDiagnosticSpan {
218 file_name: Cow::Owned(sm.filename_for_diagnostics(&start.file.name).to_string()),
219 byte_start: start.file.original_relative_byte_pos(span.lo()).0,
220 byte_end: start.file.original_relative_byte_pos(span.hi()).0,
221 line_start: start.line,
222 line_end: end.line,
223 column_start: start.col.0 + 1,
224 column_end: end.col.0 + 1,
225 is_primary: true,
226 text: self.span_lines(span),
227 label: None,
228 suggested_replacement: Some(Cow::Owned(replacement)),
229 suggestion_applicability: Some(applicability),
230 expansion: None,
231 }
232 }
233
234 fn span_lines(&self, span: Span) -> Vec<JsonDiagnosticSpanLine<'static>> {
235 let Ok(f) = self.source_map().span_to_lines(span) else { return Vec::new() };
236 let sf = &*f.file;
237 f.data.iter().map(|line| self.span_line(sf, line)).collect()
238 }
239
240 fn span_line(&self, sf: &SourceFile, line: &LineInfo) -> JsonDiagnosticSpanLine<'static> {
241 JsonDiagnosticSpanLine {
242 text: Cow::Owned(
243 sf.get_line(line.line_index).map_or_else(String::new, |l| l.to_string()),
244 ),
245 highlight_start: line.start_col.0 + 1,
246 highlight_end: line.end_col.0 + 1,
247 }
248 }
249
250 pub fn solc_diagnostic<'a>(
252 &mut self,
253 diagnostic: &'a crate::diagnostics::Diag,
254 ) -> SolcDiagnostic<'a> {
255 let primary = diagnostic.span.primary_span();
256 let file = primary
257 .map(|span| {
258 let sm = &**self.source_map();
259 let start = sm.lookup_char_pos(span.lo());
260 sm.filename_for_diagnostics(&start.file.name).to_string()
261 })
262 .unwrap_or_default();
263
264 let severity = to_severity(diagnostic.level);
265
266 SolcDiagnostic {
267 source_location: primary
268 .is_some()
269 .then(|| self.solc_span(&diagnostic.span, &file, None)),
270 secondary_source_locations: diagnostic
271 .children
272 .iter()
273 .map(|sub| self.solc_span(&sub.span, &file, Some(sub.label())))
274 .collect(),
275 r#type: Cow::Borrowed(match severity {
276 Severity::Error => match diagnostic.level {
277 Level::Bug => "InternalCompilerError",
278 Level::Fatal => "FatalError",
279 Level::Error => "Exception",
280 _ => unreachable!(),
281 },
282 Severity::Warning => "Warning",
283 Severity::Info => "Info",
284 }),
285 component: Cow::Borrowed("general"),
286 severity,
287 error_code: diagnostic.id().map(Cow::Borrowed),
288 message: diagnostic.label(),
289 formatted_message: Some(Cow::Owned(self.emit_diagnostic_to_buffer(diagnostic))),
290 }
291 }
292
293 fn solc_span<'a>(
294 &self,
295 span: &MultiSpan,
296 file: &str,
297 message: Option<Cow<'a, str>>,
298 ) -> SourceLocation<'a> {
299 let sm = &**self.source_map();
300 let sp = span.primary_span();
301 SourceLocation {
302 file: sp
303 .map(|span| {
304 let start = sm.lookup_char_pos(span.lo());
305 Cow::Owned(sm.filename_for_diagnostics(&start.file.name).to_string())
306 })
307 .unwrap_or_else(|| Cow::Owned(file.to_owned())),
308 start: sp
309 .map(|span| {
310 let start = sm.lookup_char_pos(span.lo());
311 start.file.original_relative_byte_pos(span.lo()).0
312 })
313 .unwrap_or(0),
314 end: sp
315 .map(|span| {
316 let end = sm.lookup_char_pos(span.hi());
317 end.file.original_relative_byte_pos(span.hi()).0
318 })
319 .unwrap_or(0),
320 message,
321 }
322 }
323
324 fn emit_diagnostic_to_buffer(&mut self, diagnostic: &crate::diagnostics::Diag) -> String {
325 self.human_emitter.emit_diagnostic_ref(diagnostic);
326 std::mem::take(self.human_emitter.buffer_mut())
327 }
328
329 fn emit<T: ?Sized + Serialize>(&mut self, value: &T) -> io::Result<()> {
330 if self.pretty {
331 serde_json::to_writer_pretty(&mut *self.writer, value)
332 } else {
333 serde_json::to_writer(&mut *self.writer, value)
334 }?;
335 self.writer.write_all(b"\n")?;
336 self.writer.flush()
337 }
338}
339
340#[derive(Debug, Serialize, Deserialize)]
344#[serde(tag = "$message_type", rename_all = "snake_case")]
345pub enum JsonDiagnosticMessage<'a> {
346 Diagnostic(#[serde(borrow)] JsonDiagnostic<'a>),
348}
349
350#[derive(Debug, Serialize, Deserialize)]
352pub struct JsonDiagnostic<'a> {
353 #[serde(borrow)]
355 pub message: Cow<'a, str>,
356 #[serde(borrow)]
358 pub code: Option<JsonDiagnosticCode<'a>>,
359 #[serde(borrow)]
361 pub level: Cow<'a, str>,
362 #[serde(borrow)]
364 pub spans: Vec<JsonDiagnosticSpan<'a>>,
365 #[serde(borrow)]
367 pub children: Vec<Self>,
368 #[serde(borrow)]
370 pub rendered: Option<Cow<'a, str>>,
371}
372
373#[derive(Debug, Serialize, Deserialize)]
375pub struct JsonDiagnosticSpan<'a> {
376 #[serde(borrow)]
378 pub file_name: Cow<'a, str>,
379 pub byte_start: u32,
381 pub byte_end: u32,
383 pub line_start: usize,
385 pub line_end: usize,
387 pub column_start: usize,
389 pub column_end: usize,
391 pub is_primary: bool,
394 #[serde(borrow)]
396 pub text: Vec<JsonDiagnosticSpanLine<'a>>,
397 #[serde(borrow)]
399 pub label: Option<Cow<'a, str>>,
400 #[serde(borrow)]
403 pub suggested_replacement: Option<Cow<'a, str>>,
404 pub suggestion_applicability: Option<Applicability>,
406 #[serde(borrow)]
408 pub expansion: Option<Box<JsonDiagnosticSpanMacroExpansion<'a>>>,
409}
410
411#[derive(Debug, Serialize, Deserialize)]
413pub struct JsonDiagnosticSpanMacroExpansion<'a> {
414 #[serde(borrow)]
416 pub span: JsonDiagnosticSpan<'a>,
417 #[serde(borrow)]
419 pub macro_decl_name: Cow<'a, str>,
420 #[serde(borrow)]
422 pub def_site_span: JsonDiagnosticSpan<'a>,
423}
424
425#[derive(Debug, Serialize, Deserialize)]
427pub struct JsonDiagnosticSpanLine<'a> {
428 #[serde(borrow)]
430 pub text: Cow<'a, str>,
431
432 pub highlight_start: usize,
434
435 pub highlight_end: usize,
437}
438
439#[derive(Debug, Serialize, Deserialize)]
441pub struct JsonDiagnosticCode<'a> {
442 #[serde(borrow)]
444 pub code: Cow<'a, str>,
445 #[serde(borrow)]
447 pub explanation: Option<Cow<'a, str>>,
448}
449
450#[derive(Debug, Serialize, Deserialize)]
453#[serde(rename_all = "camelCase")]
454pub struct SolcDiagnostic<'a> {
455 #[serde(borrow)]
456 pub source_location: Option<SourceLocation<'a>>,
457 #[serde(default, borrow)]
458 pub secondary_source_locations: Vec<SourceLocation<'a>>,
459 #[serde(borrow)]
460 pub r#type: Cow<'a, str>,
461 #[serde(borrow)]
462 pub component: Cow<'a, str>,
463 pub severity: Severity,
464 #[serde(borrow)]
465 pub error_code: Option<Cow<'a, str>>,
466 #[serde(borrow)]
467 pub message: Cow<'a, str>,
468 #[serde(borrow)]
469 pub formatted_message: Option<Cow<'a, str>>,
470}
471
472impl SolcDiagnostic<'_> {
473 pub fn is_error(&self) -> bool {
475 matches!(self.severity, Severity::Error)
476 }
477}
478
479#[derive(Debug, Serialize, Deserialize)]
480pub struct SourceLocation<'a> {
481 #[serde(borrow)]
482 pub file: Cow<'a, str>,
483 pub start: u32,
484 pub end: u32,
485 #[serde(default, skip_serializing_if = "Option::is_none")]
487 #[serde(borrow)]
488 pub message: Option<Cow<'a, str>>,
489}
490
491#[derive(Debug, Serialize, Deserialize)]
492#[serde(rename_all = "lowercase")]
493pub enum Severity {
494 Error,
495 Warning,
496 Info,
497}
498
499fn to_severity(level: Level) -> Severity {
500 match level {
501 Level::Bug | Level::Fatal | Level::Error => Severity::Error,
502 Level::Warning => Severity::Warning,
503 Level::Note
504 | Level::OnceNote
505 | Level::FailureNote
506 | Level::Help
507 | Level::OnceHelp
508 | Level::Allow => Severity::Info,
509 }
510}
511
512#[cfg(test)]
513mod tests {
514 use super::*;
515
516 #[test]
517 fn whole_line_deletion_includes_newline() {
518 let source_map = Arc::new(SourceMap::empty());
519 source_map
520 .new_source_file(crate::source_map::FileName::custom("test.sol"), "foo\nbar\n")
521 .unwrap();
522 let emitter = JsonEmitter::new(Box::new(io::sink()), source_map, ColorChoice::Never);
523
524 let span = emitter.span_with_suggestion(
525 Span::new(crate::BytePos(0), crate::BytePos(3)),
526 String::new(),
527 Applicability::MachineApplicable,
528 );
529
530 assert_eq!(span.byte_start, 0);
531 assert_eq!(span.byte_end, 4);
532 assert_eq!(span.line_start, 1);
533 assert_eq!(span.line_end, 2);
534 assert_eq!(span.column_end, 1);
535 assert!(span.expansion.is_none());
536 }
537
538 #[test]
539 fn solc_diagnostic_serializes_borrowed_strings() {
540 let start = 0_u32;
541 let end = 1_u32;
542 let diagnostic = SolcDiagnostic {
543 source_location: Some(SourceLocation {
544 file: Cow::Borrowed("input.sol"),
545 start,
546 end,
547 message: Some(Cow::Borrowed("borrowed \"message\"")),
548 }),
549 secondary_source_locations: Vec::new(),
550 r#type: Cow::Borrowed("Exception\nquoted"),
551 component: Cow::Borrowed("general"),
552 severity: Severity::Error,
553 error_code: Some(Cow::Borrowed("1234")),
554 message: Cow::Borrowed("borrowed message"),
555 formatted_message: None,
556 };
557
558 let json = serde_json::to_string(&diagnostic).unwrap();
559 assert!(json.contains(r#""type":"Exception\nquoted""#));
560 assert!(json.contains(r#""message":"borrowed \"message\"""#));
561
562 assert!(matches!(diagnostic.r#type, Cow::Borrowed(_)));
563 assert!(matches!(diagnostic.component, Cow::Borrowed("general")));
564 }
565}