solar-interface 0.2.0

Source positions, diagnostics, and related helper functions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
use super::{Emitter, human::HumanBufferEmitter, io_panic};
use crate::{
    Span,
    diagnostics::{CodeSuggestion, Diag, Level, MultiSpan, SpanLabel, SubDiagnostic},
    source_map::{LineInfo, SourceFile, SourceMap},
};
use anstream::ColorChoice;
use serde::Serialize;
use solar_config::HumanEmitterKind;
use std::{borrow::Cow, io, sync::Arc};

/// Diagnostic emitter that emits diagnostics as JSON.
pub struct JsonEmitter {
    writer: Box<dyn io::Write + Send>,
    pretty: bool,
    rustc_like: bool,

    human_emitter: HumanBufferEmitter,
}

impl Emitter for JsonEmitter {
    fn emit_diagnostic(&mut self, diagnostic: &mut Diag) {
        self.emit_diagnostic_ref(diagnostic);
    }

    fn emit_diagnostic_ref(&mut self, diagnostic: &Diag) {
        if self.rustc_like {
            let diagnostic = self.diagnostic(diagnostic);
            self.emit(&EmitTyped::Diagnostic(diagnostic))
        } else {
            let diagnostic = self.solc_diagnostic(diagnostic);
            self.emit(&diagnostic)
        }
        .unwrap_or_else(|e| io_panic(e));
    }

    fn source_map(&self) -> Option<&Arc<SourceMap>> {
        Emitter::source_map(&self.human_emitter)
    }
}

impl JsonEmitter {
    /// Creates a new `JsonEmitter` that writes to given writer.
    pub fn new(writer: Box<dyn io::Write + Send>, source_map: Arc<SourceMap>) -> Self {
        Self {
            writer,
            pretty: false,
            rustc_like: false,
            human_emitter: HumanBufferEmitter::new(ColorChoice::Never).source_map(Some(source_map)),
        }
    }

    /// Sets whether to pretty print the JSON.
    pub fn pretty(mut self, pretty: bool) -> Self {
        self.pretty = pretty;
        self
    }

    /// Sets whether to emit diagnostics in a format that is compatible with rustc.
    ///
    /// Mainly used in UI testing.
    pub fn rustc_like(mut self, yes: bool) -> Self {
        self.rustc_like = yes;
        self
    }

    /// Sets whether to emit diagnostics in a way that is suitable for UI testing.
    pub fn ui_testing(mut self, yes: bool) -> Self {
        self.human_emitter = self.human_emitter.ui_testing(yes);
        self
    }

    /// Sets the human emitter kind for rendered messages.
    pub fn human_kind(mut self, kind: HumanEmitterKind) -> Self {
        self.human_emitter = self.human_emitter.human_kind(kind);
        self
    }

    /// Sets the terminal width for formatting.
    pub fn terminal_width(mut self, width: Option<usize>) -> Self {
        self.human_emitter = self.human_emitter.terminal_width(width);
        self
    }

    fn source_map(&self) -> &Arc<SourceMap> {
        Emitter::source_map(self).unwrap()
    }

    fn diagnostic(&mut self, diagnostic: &Diag) -> Diagnostic {
        // Unlike the human emitter, all suggestions are preserved as separate diagnostic children.
        let children = diagnostic
            .children
            .iter()
            .map(|sub| self.sub_diagnostic(sub))
            .chain(diagnostic.suggestions.iter().map(|sugg| self.suggestion_to_diagnostic(sugg)))
            .collect();

        Diagnostic {
            message: diagnostic.label().into_owned(),
            code: diagnostic
                .id()
                .map(|code| DiagnosticCode { code: code.to_string(), explanation: None }),
            level: diagnostic.level.to_str(),
            spans: self.spans(&diagnostic.span),
            children,
            rendered: Some(self.emit_diagnostic_to_buffer(diagnostic)),
        }
    }

    fn sub_diagnostic(&self, diagnostic: &SubDiagnostic) -> Diagnostic {
        Diagnostic {
            message: diagnostic.label().into_owned(),
            code: None,
            level: diagnostic.level.to_str(),
            spans: self.spans(&diagnostic.span),
            children: vec![],
            rendered: None,
        }
    }

    fn suggestion_to_diagnostic(&self, sugg: &CodeSuggestion) -> Diagnostic {
        // Collect all spans from all substitutions
        let spans = sugg
            .substitutions
            .iter()
            .flat_map(|sub| sub.parts.iter())
            .map(|part| self.span_with_suggestion(part.span, part.snippet.to_string()))
            .collect();

        Diagnostic {
            message: sugg.msg.as_str().to_string(),
            code: None,
            level: "help",
            spans,
            children: vec![],
            rendered: None,
        }
    }

    fn spans(&self, msp: &MultiSpan) -> Vec<DiagnosticSpan> {
        msp.span_labels().iter().map(|label| self.span(label)).collect()
    }

    fn span(&self, label: &SpanLabel) -> DiagnosticSpan {
        let sm = &**self.source_map();
        let span = label.span;
        let start = sm.lookup_char_pos(span.lo());
        let end = sm.lookup_char_pos(span.hi());
        DiagnosticSpan {
            file_name: sm.filename_for_diagnostics(&start.file.name).to_string(),
            byte_start: start.file.original_relative_byte_pos(span.lo()).0,
            byte_end: start.file.original_relative_byte_pos(span.hi()).0,
            line_start: start.line,
            line_end: end.line,
            column_start: start.col.0 + 1,
            column_end: end.col.0 + 1,
            is_primary: label.is_primary,
            text: self.span_lines(span),
            label: label.label.as_ref().map(|msg| msg.as_str().into()),
            suggested_replacement: None,
        }
    }

    fn span_with_suggestion(&self, span: Span, replacement: String) -> DiagnosticSpan {
        let sm = &**self.source_map();
        let start = sm.lookup_char_pos(span.lo());
        let end = sm.lookup_char_pos(span.hi());
        DiagnosticSpan {
            file_name: sm.filename_for_diagnostics(&start.file.name).to_string(),
            byte_start: start.file.original_relative_byte_pos(span.lo()).0,
            byte_end: start.file.original_relative_byte_pos(span.hi()).0,
            line_start: start.line,
            line_end: end.line,
            column_start: start.col.0 + 1,
            column_end: end.col.0 + 1,
            is_primary: true,
            text: self.span_lines(span),
            label: None,
            suggested_replacement: Some(replacement),
        }
    }

    fn span_lines(&self, span: Span) -> Vec<DiagnosticSpanLine> {
        let Ok(f) = self.source_map().span_to_lines(span) else { return Vec::new() };
        let sf = &*f.file;
        f.data.iter().map(|line| self.span_line(sf, line)).collect()
    }

    fn span_line(&self, sf: &SourceFile, line: &LineInfo) -> DiagnosticSpanLine {
        DiagnosticSpanLine {
            text: sf.get_line(line.line_index).map_or_else(String::new, |l| l.to_string()),
            highlight_start: line.start_col.0 + 1,
            highlight_end: line.end_col.0 + 1,
        }
    }

    /// Converts a diagnostic to a solc-compatible JSON diagnostic.
    pub fn solc_diagnostic<'a>(
        &mut self,
        diagnostic: &'a crate::diagnostics::Diag,
    ) -> SolcDiagnostic<'a> {
        let primary = diagnostic.span.primary_span();
        let file = primary
            .map(|span| {
                let sm = &**self.source_map();
                let start = sm.lookup_char_pos(span.lo());
                sm.filename_for_diagnostics(&start.file.name).to_string()
            })
            .unwrap_or_default();

        let severity = to_severity(diagnostic.level);

        SolcDiagnostic {
            source_location: primary
                .is_some()
                .then(|| self.solc_span(&diagnostic.span, &file, None)),
            secondary_source_locations: diagnostic
                .children
                .iter()
                .map(|sub| self.solc_span(&sub.span, &file, Some(sub.label())))
                .collect(),
            r#type: Cow::Borrowed(match severity {
                Severity::Error => match diagnostic.level {
                    Level::Bug => "InternalCompilerError",
                    Level::Fatal => "FatalError",
                    Level::Error => "Exception",
                    _ => unreachable!(),
                },
                Severity::Warning => "Warning",
                Severity::Info => "Info",
            }),
            component: Cow::Borrowed("general"),
            severity,
            error_code: diagnostic.id().map(Cow::Borrowed),
            message: diagnostic.label(),
            formatted_message: Some(Cow::Owned(self.emit_diagnostic_to_buffer(diagnostic))),
        }
    }

    fn solc_span<'a>(
        &self,
        span: &MultiSpan,
        file: &str,
        message: Option<Cow<'a, str>>,
    ) -> SourceLocation<'a> {
        let sm = &**self.source_map();
        let sp = span.primary_span();
        SourceLocation {
            file: sp
                .map(|span| {
                    let start = sm.lookup_char_pos(span.lo());
                    Cow::Owned(sm.filename_for_diagnostics(&start.file.name).to_string())
                })
                .unwrap_or_else(|| Cow::Owned(file.to_owned())),
            start: sp
                .map(|span| {
                    let start = sm.lookup_char_pos(span.lo());
                    start.file.original_relative_byte_pos(span.lo()).0
                })
                .unwrap_or(0),
            end: sp
                .map(|span| {
                    let end = sm.lookup_char_pos(span.hi());
                    end.file.original_relative_byte_pos(span.hi()).0
                })
                .unwrap_or(0),
            message,
        }
    }

    fn emit_diagnostic_to_buffer(&mut self, diagnostic: &crate::diagnostics::Diag) -> String {
        self.human_emitter.emit_diagnostic_ref(diagnostic);
        std::mem::take(self.human_emitter.buffer_mut())
    }

    fn emit<T: ?Sized + Serialize>(&mut self, value: &T) -> io::Result<()> {
        if self.pretty {
            serde_json::to_writer_pretty(&mut *self.writer, value)
        } else {
            serde_json::to_writer(&mut *self.writer, value)
        }?;
        self.writer.write_all(b"\n")?;
        self.writer.flush()
    }
}

// Rustc-like JSON format.

#[derive(Serialize)]
#[serde(tag = "$message_type", rename_all = "snake_case")]
enum EmitTyped {
    Diagnostic(Diagnostic),
}

#[derive(Serialize)]
struct Diagnostic {
    /// The primary error message.
    message: String,
    code: Option<DiagnosticCode>,
    /// "error", "warning", "note", "help".
    level: &'static str,
    spans: Vec<DiagnosticSpan>,
    /// Associated diagnostic messages.
    children: Vec<Self>,
    /// The message as the compiler would render it.
    rendered: Option<String>,
}

#[derive(Serialize)]
struct DiagnosticSpan {
    file_name: String,
    byte_start: u32,
    byte_end: u32,
    /// 1-based.
    line_start: usize,
    line_end: usize,
    /// 1-based, character offset.
    column_start: usize,
    column_end: usize,
    /// Is this a "primary" span -- meaning the point, or one of the points,
    /// where the error occurred?
    is_primary: bool,
    /// Source text from the start of line_start to the end of line_end.
    text: Vec<DiagnosticSpanLine>,
    /// Label that should be placed at this location (if any)
    label: Option<String>,
    /// If we are suggesting a replacement, this will contain text
    /// that should be sliced in atop this span.
    suggested_replacement: Option<String>,
}

#[derive(Serialize)]
struct DiagnosticSpanLine {
    text: String,

    /// 1-based, character offset in self.text.
    highlight_start: usize,

    highlight_end: usize,
}

#[derive(Serialize)]
struct DiagnosticCode {
    /// The code itself.
    code: String,
    /// An explanation for the code.
    explanation: Option<&'static str>,
}

// Solc JSON format.

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SolcDiagnostic<'a> {
    #[serde(borrow)]
    pub source_location: Option<SourceLocation<'a>>,
    #[serde(borrow)]
    pub secondary_source_locations: Vec<SourceLocation<'a>>,
    #[serde(borrow)]
    pub r#type: Cow<'a, str>,
    #[serde(borrow)]
    pub component: Cow<'a, str>,
    pub severity: Severity,
    #[serde(borrow)]
    pub error_code: Option<Cow<'a, str>>,
    #[serde(borrow)]
    pub message: Cow<'a, str>,
    #[serde(borrow)]
    pub formatted_message: Option<Cow<'a, str>>,
}

impl SolcDiagnostic<'_> {
    /// Returns `true` if this diagnostic has error severity.
    pub fn is_error(&self) -> bool {
        matches!(self.severity, Severity::Error)
    }
}

#[derive(Debug, Serialize)]
pub struct SourceLocation<'a> {
    #[serde(borrow)]
    pub file: Cow<'a, str>,
    pub start: u32,
    pub end: u32,
    // Some if it's a secondary source location.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub message: Option<Cow<'a, str>>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    Error,
    Warning,
    Info,
}

fn to_severity(level: Level) -> Severity {
    match level {
        Level::Bug | Level::Fatal | Level::Error => Severity::Error,
        Level::Warning => Severity::Warning,
        Level::Note
        | Level::OnceNote
        | Level::FailureNote
        | Level::Help
        | Level::OnceHelp
        | Level::Allow => Severity::Info,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn solc_diagnostic_serializes_borrowed_strings() {
        let diagnostic = SolcDiagnostic {
            source_location: Some(SourceLocation {
                file: Cow::Borrowed("input.sol"),
                start: 0,
                end: 1,
                message: Some(Cow::Borrowed("borrowed \"message\"")),
            }),
            secondary_source_locations: Vec::new(),
            r#type: Cow::Borrowed("Exception\nquoted"),
            component: Cow::Borrowed("general"),
            severity: Severity::Error,
            error_code: Some(Cow::Borrowed("1234")),
            message: Cow::Borrowed("borrowed message"),
            formatted_message: None,
        };

        let json = serde_json::to_string(&diagnostic).unwrap();
        assert!(json.contains(r#""type":"Exception\nquoted""#));
        assert!(json.contains(r#""message":"borrowed \"message\"""#));

        assert!(matches!(diagnostic.r#type, Cow::Borrowed(_)));
        assert!(matches!(diagnostic.component, Cow::Borrowed("general")));
    }
}