naga/
span.rs

1use alloc::{
2    borrow::ToOwned,
3    format,
4    string::{String, ToString},
5    vec::Vec,
6};
7use core::{error::Error, fmt, ops::Range};
8
9use crate::{error::replace_control_chars, Arena, Handle, UniqueArena};
10
11/// A source code span, used for error reporting.
12#[derive(Clone, Copy, Debug, PartialEq, Default)]
13#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
14pub struct Span {
15    start: u32,
16    end: u32,
17}
18
19impl Span {
20    pub const UNDEFINED: Self = Self { start: 0, end: 0 };
21
22    /// Creates a new `Span` from a range of byte indices
23    ///
24    /// Note: end is exclusive, it doesn't belong to the `Span`
25    pub const fn new(start: u32, end: u32) -> Self {
26        Span { start, end }
27    }
28
29    /// Returns a new `Span` starting at `self` and ending at `other`
30    pub const fn until(&self, other: &Self) -> Self {
31        Span {
32            start: self.start,
33            end: other.end,
34        }
35    }
36
37    /// Modifies `self` to contain the smallest `Span` possible that
38    /// contains both `self` and `other`
39    pub fn subsume(&mut self, other: Self) {
40        *self = if !self.is_defined() {
41            // self isn't defined so use other
42            other
43        } else if !other.is_defined() {
44            // other isn't defined so don't try to subsume
45            *self
46        } else {
47            // Both self and other are defined so calculate the span that contains them both
48            Span {
49                start: self.start.min(other.start),
50                end: self.end.max(other.end),
51            }
52        }
53    }
54
55    /// Returns the smallest `Span` possible that contains all the `Span`s
56    /// defined in the `from` iterator
57    pub fn total_span<T: Iterator<Item = Self>>(from: T) -> Self {
58        let mut span: Self = Default::default();
59        for other in from {
60            span.subsume(other);
61        }
62        span
63    }
64
65    /// Converts `self` to a range if the span is not unknown
66    pub fn to_range(self) -> Option<Range<usize>> {
67        if self.is_defined() {
68            Some(self.start as usize..self.end as usize)
69        } else {
70            None
71        }
72    }
73
74    /// Check whether `self` was defined or is a default/unknown span
75    pub fn is_defined(&self) -> bool {
76        *self != Self::default()
77    }
78
79    /// Return a [`SourceLocation`] for this span in the provided source.
80    pub fn location(&self, source: &str) -> SourceLocation {
81        let prefix = &source[..self.start as usize];
82        let line_number = prefix.matches('\n').count() as u32 + 1;
83        let line_start = prefix.rfind('\n').map(|pos| pos + 1).unwrap_or(0) as u32;
84        let line_position = self.start - line_start + 1;
85
86        SourceLocation {
87            line_number,
88            line_position,
89            offset: self.start,
90            length: self.end - self.start,
91        }
92    }
93}
94
95impl From<Range<usize>> for Span {
96    fn from(range: Range<usize>) -> Self {
97        Span {
98            start: range.start as u32,
99            end: range.end as u32,
100        }
101    }
102}
103
104impl core::ops::Index<Span> for str {
105    type Output = str;
106
107    #[inline]
108    fn index(&self, span: Span) -> &str {
109        &self[span.start as usize..span.end as usize]
110    }
111}
112
113/// A human-readable representation for a span, tailored for text source.
114///
115/// Roughly corresponds to the positional members of [`GPUCompilationMessage`][gcm] from
116/// the WebGPU specification, except
117/// - `offset` and `length` are in bytes (UTF-8 code units), instead of UTF-16 code units.
118/// - `line_position` is in bytes (UTF-8 code units), instead of UTF-16 code units.
119///
120/// [gcm]: https://www.w3.org/TR/webgpu/#gpucompilationmessage
121#[derive(Copy, Clone, Debug, PartialEq, Eq)]
122pub struct SourceLocation {
123    /// 1-based line number.
124    pub line_number: u32,
125    /// 1-based column in code units (in bytes) of the start of the span.
126    pub line_position: u32,
127    /// 0-based Offset in code units (in bytes) of the start of the span.
128    pub offset: u32,
129    /// Length in code units (in bytes) of the span.
130    pub length: u32,
131}
132
133/// A source code span together with "context", a user-readable description of what part of the error it refers to.
134pub type SpanContext = (Span, String);
135
136/// Wrapper class for [`Error`], augmenting it with a list of [`SpanContext`]s.
137#[derive(Debug, Clone)]
138pub struct WithSpan<E> {
139    inner: E,
140    spans: Vec<SpanContext>,
141}
142
143impl<E> fmt::Display for WithSpan<E>
144where
145    E: fmt::Display,
146{
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        self.inner.fmt(f)
149    }
150}
151
152#[cfg(test)]
153impl<E> PartialEq for WithSpan<E>
154where
155    E: PartialEq,
156{
157    fn eq(&self, other: &Self) -> bool {
158        self.inner.eq(&other.inner)
159    }
160}
161
162impl<E> Error for WithSpan<E>
163where
164    E: Error,
165{
166    fn source(&self) -> Option<&(dyn Error + 'static)> {
167        self.inner.source()
168    }
169}
170
171impl<E> WithSpan<E> {
172    /// Create a new [`WithSpan`] from an [`Error`], containing no spans.
173    pub const fn new(inner: E) -> Self {
174        Self {
175            inner,
176            spans: Vec::new(),
177        }
178    }
179
180    /// Reverse of [`Self::new`], discards span information and returns an inner error.
181    pub fn into_inner(self) -> E {
182        self.inner
183    }
184
185    pub const fn as_inner(&self) -> &E {
186        &self.inner
187    }
188
189    /// Iterator over stored [`SpanContext`]s.
190    pub fn spans(&self) -> impl ExactSizeIterator<Item = &SpanContext> {
191        self.spans.iter()
192    }
193
194    /// Add a new span with description.
195    pub fn with_span<S>(mut self, span: Span, description: S) -> Self
196    where
197        S: ToString,
198    {
199        if span.is_defined() {
200            self.spans.push((span, description.to_string()));
201        }
202        self
203    }
204
205    /// Add a [`SpanContext`].
206    pub fn with_context(self, span_context: SpanContext) -> Self {
207        let (span, description) = span_context;
208        self.with_span(span, description)
209    }
210
211    /// Add a [`Handle`] from either [`Arena`] or [`UniqueArena`], borrowing its span information from there
212    /// and annotating with a type and the handle representation.
213    pub(crate) fn with_handle<T, A: SpanProvider<T>>(self, handle: Handle<T>, arena: &A) -> Self {
214        self.with_context(arena.get_span_context(handle))
215    }
216
217    /// Convert inner error using [`From`].
218    pub fn into_other<E2>(self) -> WithSpan<E2>
219    where
220        E2: From<E>,
221    {
222        WithSpan {
223            inner: self.inner.into(),
224            spans: self.spans,
225        }
226    }
227
228    /// Convert inner error into another type. Joins span information contained in `self`
229    /// with what is returned from `func`.
230    pub fn and_then<F, E2>(self, func: F) -> WithSpan<E2>
231    where
232        F: FnOnce(E) -> WithSpan<E2>,
233    {
234        let mut res = func(self.inner);
235        res.spans.extend(self.spans);
236        res
237    }
238
239    /// Return a [`SourceLocation`] for our first span, if we have one.
240    pub fn location(&self, source: &str) -> Option<SourceLocation> {
241        if self.spans.is_empty() || source.is_empty() {
242            return None;
243        }
244
245        Some(self.spans[0].0.location(source))
246    }
247
248    pub(crate) fn diagnostic(&self) -> codespan_reporting::diagnostic::Diagnostic<()>
249    where
250        E: Error,
251    {
252        use codespan_reporting::diagnostic::{Diagnostic, Label};
253        let diagnostic = Diagnostic::error()
254            .with_message(self.inner.to_string())
255            .with_labels(
256                self.spans()
257                    .map(|&(span, ref desc)| {
258                        Label::primary((), span.to_range().unwrap()).with_message(desc.to_owned())
259                    })
260                    .collect(),
261            )
262            .with_notes({
263                let mut notes = Vec::new();
264                let mut source: &dyn Error = &self.inner;
265                while let Some(next) = Error::source(source) {
266                    notes.push(next.to_string());
267                    source = next;
268                }
269                notes
270            });
271        diagnostic
272    }
273
274    /// Emits a summary of the error to standard error stream.
275    #[cfg(feature = "stderr")]
276    pub fn emit_to_stderr(&self, source: &str)
277    where
278        E: Error,
279    {
280        self.emit_to_stderr_with_path(source, "wgsl")
281    }
282
283    /// Emits a summary of the error to standard error stream.
284    #[cfg(feature = "stderr")]
285    pub fn emit_to_stderr_with_path(&self, source: &str, path: &str)
286    where
287        E: Error,
288    {
289        use codespan_reporting::{files, term};
290
291        let files = files::SimpleFile::new(path, replace_control_chars(source));
292        let config = term::Config::default();
293
294        cfg_if::cfg_if! {
295            if #[cfg(feature = "termcolor")] {
296                let writer = term::termcolor::StandardStream::stderr(term::termcolor::ColorChoice::Auto);
297                term::emit_to_write_style(&mut writer.lock(), &config, &files, &self.diagnostic())
298                    .expect("cannot write error");
299            } else {
300                let writer = std::io::stderr();
301                term::emit_to_io_write(&mut writer.lock(), &config, &files, &self.diagnostic())
302                    .expect("cannot write error");
303            }
304        }
305    }
306
307    /// Emits a summary of the error to a string.
308    pub fn emit_to_string(&self, source: &str) -> String
309    where
310        E: Error,
311    {
312        self.emit_to_string_with_path(source, "wgsl")
313    }
314
315    /// Emits a summary of the error to a string.
316    pub fn emit_to_string_with_path(&self, source: &str, path: &str) -> String
317    where
318        E: Error,
319    {
320        use codespan_reporting::{files, term};
321
322        let files = files::SimpleFile::new(path, replace_control_chars(source));
323        let config = term::Config::default();
324
325        let mut writer = crate::error::DiagnosticBuffer::new();
326        writer
327            .emit_to_self(&config, &files, &self.diagnostic())
328            .expect("cannot write error");
329        writer.into_string()
330    }
331}
332
333/// Convenience trait for [`Error`] to be able to apply spans to anything.
334pub(crate) trait AddSpan: Sized {
335    /// The returned output type.
336    type Output;
337
338    /// See [`WithSpan::new`].
339    fn with_span(self) -> Self::Output;
340    /// See [`WithSpan::with_span`].
341    fn with_span_static(self, span: Span, description: &'static str) -> Self::Output;
342    /// See [`WithSpan::with_context`].
343    fn with_span_context(self, span_context: SpanContext) -> Self::Output;
344    /// See [`WithSpan::with_handle`].
345    fn with_span_handle<T, A: SpanProvider<T>>(self, handle: Handle<T>, arena: &A) -> Self::Output;
346}
347
348impl<E> AddSpan for E {
349    type Output = WithSpan<Self>;
350
351    fn with_span(self) -> WithSpan<Self> {
352        WithSpan::new(self)
353    }
354
355    fn with_span_static(self, span: Span, description: &'static str) -> WithSpan<Self> {
356        WithSpan::new(self).with_span(span, description)
357    }
358
359    fn with_span_context(self, span_context: SpanContext) -> WithSpan<Self> {
360        WithSpan::new(self).with_context(span_context)
361    }
362
363    fn with_span_handle<T, A: SpanProvider<T>>(
364        self,
365        handle: Handle<T>,
366        arena: &A,
367    ) -> WithSpan<Self> {
368        WithSpan::new(self).with_handle(handle, arena)
369    }
370}
371
372/// Trait abstracting over getting a span from an [`Arena`] or a [`UniqueArena`].
373pub(crate) trait SpanProvider<T> {
374    fn get_span(&self, handle: Handle<T>) -> Span;
375    fn get_span_context(&self, handle: Handle<T>) -> SpanContext {
376        match self.get_span(handle) {
377            x if !x.is_defined() => (Default::default(), "".to_string()),
378            known => (
379                known,
380                format!("{} {:?}", core::any::type_name::<T>(), handle),
381            ),
382        }
383    }
384}
385
386impl<T> SpanProvider<T> for Arena<T> {
387    fn get_span(&self, handle: Handle<T>) -> Span {
388        self.get_span(handle)
389    }
390}
391
392impl<T> SpanProvider<T> for UniqueArena<T> {
393    fn get_span(&self, handle: Handle<T>) -> Span {
394        self.get_span(handle)
395    }
396}
397
398/// Convenience trait for [`Result`], adding a [`MapErrWithSpan::map_err_inner`]
399/// mapping to [`WithSpan::and_then`].
400pub(crate) trait MapErrWithSpan<E, E2>: Sized {
401    /// The returned output type.
402    type Output: Sized;
403
404    fn map_err_inner<F, E3>(self, func: F) -> Self::Output
405    where
406        F: FnOnce(E) -> WithSpan<E3>,
407        E2: From<E3>;
408}
409
410impl<T, E, E2> MapErrWithSpan<E, E2> for Result<T, WithSpan<E>> {
411    type Output = Result<T, WithSpan<E2>>;
412
413    fn map_err_inner<F, E3>(self, func: F) -> Result<T, WithSpan<E2>>
414    where
415        F: FnOnce(E) -> WithSpan<E3>,
416        E2: From<E3>,
417    {
418        self.map_err(|e| e.and_then(func).into_other::<E2>())
419    }
420}
421
422#[test]
423fn span_location() {
424    let source = "12\n45\n\n89\n";
425    assert_eq!(
426        Span { start: 0, end: 1 }.location(source),
427        SourceLocation {
428            line_number: 1,
429            line_position: 1,
430            offset: 0,
431            length: 1
432        }
433    );
434    assert_eq!(
435        Span { start: 1, end: 2 }.location(source),
436        SourceLocation {
437            line_number: 1,
438            line_position: 2,
439            offset: 1,
440            length: 1
441        }
442    );
443    assert_eq!(
444        Span { start: 2, end: 3 }.location(source),
445        SourceLocation {
446            line_number: 1,
447            line_position: 3,
448            offset: 2,
449            length: 1
450        }
451    );
452    assert_eq!(
453        Span { start: 3, end: 5 }.location(source),
454        SourceLocation {
455            line_number: 2,
456            line_position: 1,
457            offset: 3,
458            length: 2
459        }
460    );
461    assert_eq!(
462        Span { start: 4, end: 6 }.location(source),
463        SourceLocation {
464            line_number: 2,
465            line_position: 2,
466            offset: 4,
467            length: 2
468        }
469    );
470    assert_eq!(
471        Span { start: 5, end: 6 }.location(source),
472        SourceLocation {
473            line_number: 2,
474            line_position: 3,
475            offset: 5,
476            length: 1
477        }
478    );
479    assert_eq!(
480        Span { start: 6, end: 7 }.location(source),
481        SourceLocation {
482            line_number: 3,
483            line_position: 1,
484            offset: 6,
485            length: 1
486        }
487    );
488    assert_eq!(
489        Span { start: 7, end: 8 }.location(source),
490        SourceLocation {
491            line_number: 4,
492            line_position: 1,
493            offset: 7,
494            length: 1
495        }
496    );
497    assert_eq!(
498        Span { start: 8, end: 9 }.location(source),
499        SourceLocation {
500            line_number: 4,
501            line_position: 2,
502            offset: 8,
503            length: 1
504        }
505    );
506    assert_eq!(
507        Span { start: 9, end: 10 }.location(source),
508        SourceLocation {
509            line_number: 4,
510            line_position: 3,
511            offset: 9,
512            length: 1
513        }
514    );
515    assert_eq!(
516        Span { start: 10, end: 11 }.location(source),
517        SourceLocation {
518            line_number: 5,
519            line_position: 1,
520            offset: 10,
521            length: 1
522        }
523    );
524}