swc_error_reporters/
diagnostic.rs

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
use std::{fmt, mem::transmute};

use miette::{GraphicalReportHandler, Severity, SourceOffset, SourceSpan};
use swc_common::{
    errors::{Diagnostic, DiagnosticId, Level, SubDiagnostic},
    BytePos, FileName, SourceMap, Span,
};

pub struct PrettyDiagnostic<'a> {
    source_code: PrettySourceCode<'a>,
    d: &'a Diagnostic,

    children: Vec<PrettySubDiagnostic<'a>>,
}

impl<'a> PrettyDiagnostic<'a> {
    pub fn new(d: &'a Diagnostic, cm: &'a SourceMap, skip_filename: bool) -> Self {
        let source_code = PrettySourceCode { cm, skip_filename };

        let children = d
            .children
            .iter()
            .filter(|d| !matches!(d.level, Level::Help))
            .map(|d| PrettySubDiagnostic { source_code, d })
            .collect();
        Self {
            source_code,
            d,
            children,
        }
    }
}

impl miette::Diagnostic for PrettyDiagnostic<'_> {
    fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
        self.d
            .code
            .as_ref()
            .map(|v| match v {
                DiagnosticId::Error(v) => v,
                DiagnosticId::Lint(v) => v,
            })
            .map(|code| Box::new(code) as Box<dyn fmt::Display>)
    }

    fn severity(&self) -> Option<Severity> {
        level_to_severity(self.d.level)
    }

    fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
        self.d
            .children
            .iter()
            .filter(|s| s.level == Level::Help)
            .map(|s| Box::new(&s.message[0].0) as Box<_>)
            .next()
    }

    fn source_code(&self) -> Option<&dyn miette::SourceCode> {
        if let Some(span) = self.d.span.primary_span() {
            if span.lo.is_dummy() || span.hi.is_dummy() {
                return None;
            }
        } else {
            return None;
        }

        Some(&self.source_code as &dyn miette::SourceCode)
    }

    fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
        let iter = self.d.span.span_labels().into_iter().map(|span_label| {
            miette::LabeledSpan::new_with_span(span_label.label, convert_span(span_label.span))
        });

        Some(Box::new(iter))
    }

    fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn miette::Diagnostic> + 'a>> {
        if self.children.is_empty() {
            None
        } else {
            Some(Box::new(
                self.children.iter().map(|d| d as &dyn miette::Diagnostic),
            ))
        }
    }
}

impl<'a> PrettyDiagnostic<'a> {
    pub fn to_pretty_string(&self, handler: &'a GraphicalReportHandler) -> String {
        let mut wr = String::new();
        handler.render_report(&mut wr, self).unwrap();
        wr
    }
}

impl std::error::Error for PrettyDiagnostic<'_> {}

/// Delegates to `Diagnostics`
impl fmt::Debug for PrettyDiagnostic<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.d, f)
    }
}

impl fmt::Display for PrettyDiagnostic<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.d.message[0].0.fmt(f)
    }
}

#[derive(Clone, Copy)]
pub struct PrettySourceCode<'a> {
    cm: &'a SourceMap,
    skip_filename: bool,
}

impl miette::SourceCode for PrettySourceCode<'_> {
    fn read_span<'a>(
        &'a self,
        span: &SourceSpan,
        context_lines_before: usize,
        context_lines_after: usize,
    ) -> Result<Box<dyn miette::SpanContents<'a> + 'a>, miette::MietteError> {
        let lo = span.offset();
        let hi = lo + span.len();

        let mut span = Span::new(BytePos(lo as _), BytePos(hi as _));

        span = self
            .cm
            .with_span_to_prev_source(span, |src| {
                let len = src
                    .rsplit('\n')
                    .take(context_lines_before + 1)
                    .map(|s| s.len() + 1)
                    .sum::<usize>();

                span.lo.0 -= (len as u32) - 1;
                span
            })
            .unwrap_or(span);

        span = self
            .cm
            .with_span_to_next_source(span, |src| {
                let len = src
                    .split('\n')
                    .take(context_lines_after + 1)
                    .map(|s| s.len() + 1)
                    .sum::<usize>();

                span.hi.0 += (len as u32) - 1;
                span
            })
            .unwrap_or(span);

        span = self
            .cm
            .with_snippet_of_span(span, |src| {
                if src.lines().next().is_some() {
                    return span;
                }
                let lo = src.len() - src.trim_start().len();
                let hi = src.len() - src.trim_end().len();

                span.lo.0 += lo as u32;
                span.hi.0 -= hi as u32;

                span
            })
            .unwrap_or(span);

        let mut src = self
            .cm
            .with_snippet_of_span(span, |s| unsafe { transmute::<&str, &str>(s) })
            .unwrap_or(" ");

        if span.lo == span.hi {
            src = " ";
        }

        let loc = self.cm.lookup_char_pos(span.lo());
        let line_count = loc.file.analyze().lines.len();

        let name = if self.skip_filename {
            None
        } else {
            match &*loc.file.name {
                FileName::Real(ref path) => Some(path.to_string_lossy().into_owned()),
                FileName::Custom(ref name) => Some(name.clone()),
                FileName::Anon => None,
                _ => Some(loc.file.name.to_string()),
            }
        };

        Ok(Box::new(SpanContentsImpl {
            _cm: self.cm,
            data: src,
            span: convert_span(span),
            line: loc.line.saturating_sub(1),
            column: loc.col_display,
            line_count,
            name,
        }))
    }
}

pub fn to_pretty_source_code(cm: &SourceMap, skip_filename: bool) -> PrettySourceCode<'_> {
    PrettySourceCode { cm, skip_filename }
}
struct PrettySubDiagnostic<'a> {
    source_code: PrettySourceCode<'a>,
    d: &'a SubDiagnostic,
}

impl std::error::Error for PrettySubDiagnostic<'_> {}

/// Delegates to `Diagnostics`
impl fmt::Debug for PrettySubDiagnostic<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.d, f)
    }
}

impl fmt::Display for PrettySubDiagnostic<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.d.message[0].0, f)
    }
}

impl miette::Diagnostic for PrettySubDiagnostic<'_> {
    fn severity(&self) -> Option<Severity> {
        level_to_severity(self.d.level)
    }

    fn source_code(&self) -> Option<&dyn miette::SourceCode> {
        Some(&self.source_code)
    }

    fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
        let iter = self.d.span.span_labels().into_iter().map(|span_label| {
            miette::LabeledSpan::new_with_span(span_label.label, convert_span(span_label.span))
        });

        Some(Box::new(iter))
    }
}

struct SpanContentsImpl<'a> {
    /// This ensures that the underlying sourcemap is not dropped.
    _cm: &'a SourceMap,

    // Data from a [`SourceCode`], in bytes.
    data: &'a str,
    // span actually covered by this SpanContents.
    span: SourceSpan,
    // The 0-indexed line where the associated [`SourceSpan`] _starts_.
    line: usize,
    // The 0-indexed column where the associated [`SourceSpan`] _starts_.
    column: usize,
    // Number of line in this snippet.
    line_count: usize,
    // Optional filename
    name: Option<String>,
}

impl<'a> miette::SpanContents<'a> for SpanContentsImpl<'a> {
    fn data(&self) -> &'a [u8] {
        self.data.as_bytes()
    }

    fn span(&self) -> &SourceSpan {
        &self.span
    }

    fn line(&self) -> usize {
        self.line
    }

    fn column(&self) -> usize {
        self.column
    }

    fn line_count(&self) -> usize {
        self.line_count
    }

    fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }
}

fn level_to_severity(level: Level) -> Option<Severity> {
    match level {
        Level::FailureNote | Level::Bug | Level::Fatal | Level::PhaseFatal | Level::Error => {
            Some(Severity::Error)
        }
        Level::Warning => Some(Severity::Warning),
        Level::Note | Level::Help => Some(Severity::Advice),
        Level::Cancelled => None,
    }
}

pub fn convert_span(span: Span) -> SourceSpan {
    let len = span.hi - span.lo;
    let start = SourceOffset::from(span.lo.0 as usize);
    SourceSpan::new(start, len.0 as usize)
}

pub trait ToPrettyDiagnostic {
    fn to_pretty_diagnostic<'a>(
        &'a self,
        cm: &'a SourceMap,
        skip_filename: bool,
    ) -> PrettyDiagnostic<'a>;

    fn to_pretty_string<'a>(
        &self,
        cm: &'a SourceMap,
        skip_filename: bool,
        handler: &'a GraphicalReportHandler,
    ) -> String;
}

// For readable diagnostic, then render by miette
impl ToPrettyDiagnostic for Diagnostic {
    /// Returns a pretty-printed of the diagnostic.
    fn to_pretty_diagnostic<'a>(
        &'a self,
        cm: &'a SourceMap,
        skip_filename: bool,
    ) -> PrettyDiagnostic<'a> {
        PrettyDiagnostic::new(self, cm, skip_filename)
    }

    /// Converts the diagnostic into a pretty-printed string, suitable for
    /// display.
    ///
    /// This method is used to generate a human-readable string representation
    /// of the diagnostic. It utilizes the `PrettyDiagnostic` struct to
    /// format the diagnostic information.
    ///
    /// # Parameters
    ///
    /// - `cm`: A reference to the `SourceMap` used for mapping source code
    ///   locations.
    /// - `skip_filename`: A boolean indicating whether to skip including
    ///   filenames in the output.
    /// - `handler`: A reference to the `GraphicalReportHandler` used for
    ///   handling graphical reports.
    ///
    /// # Returns
    ///
    /// A `String` containing the pretty-printed diagnostic information.
    fn to_pretty_string<'a>(
        &self,
        cm: &'a SourceMap,
        skip_filename: bool,
        handler: &'a GraphicalReportHandler,
    ) -> String {
        let pretty_diagnostic = PrettyDiagnostic::new(self, cm, skip_filename);
        pretty_diagnostic.to_pretty_string(handler)
    }
}