wgsl_parse/
span.rs

1use std::ops::Range;
2
3use derive_more::derive::{AsMut, AsRef, Deref, DerefMut, From};
4
5pub type Id = u32;
6
7#[cfg_attr(feature = "tokrepr", derive(tokrepr::TokRepr))]
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
10pub struct Span {
11    /// The lower bound of the span (inclusive).
12    pub start: usize,
13    /// The upper bound of the span (exclusive).
14    pub end: usize,
15}
16// Deref, DerefMut, AsRef, AsMut
17impl Span {
18    pub fn new(range: Range<usize>) -> Self {
19        Self {
20            start: range.start,
21            end: range.end,
22        }
23    }
24    pub fn range(&self) -> Range<usize> {
25        self.start..self.end
26    }
27    pub fn extend(&self, other: Span) -> Self {
28        Self {
29            start: self.start,
30            end: other.end,
31        }
32    }
33}
34
35impl From<Range<usize>> for Span {
36    fn from(value: Range<usize>) -> Self {
37        Span::new(value)
38    }
39}
40
41#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
42#[derive(Default, Clone, Debug, Deref, DerefMut, AsRef, AsMut, From)]
43pub struct Spanned<T> {
44    span: Span,
45    #[deref(forward)]
46    #[deref_mut(forward)]
47    #[as_ref(T)]
48    #[as_mut(T)]
49    #[from(T)]
50    node: Box<T>,
51}
52
53// we ignore the spans for equality comparison
54impl<T: PartialEq> PartialEq for Spanned<T> {
55    fn eq(&self, other: &Self) -> bool {
56        self.node.eq(&other.node)
57    }
58}
59
60impl<T> Spanned<T> {
61    pub fn new(node: T, span: Span) -> Self {
62        Self::new_boxed(Box::new(node), span)
63    }
64    pub fn new_boxed(node: Box<T>, span: Span) -> Self {
65        Self { span, node }
66    }
67    pub fn span(&self) -> Span {
68        self.span
69    }
70    pub fn node(&self) -> &T {
71        self
72    }
73    pub fn node_mut(&mut self) -> &mut T {
74        self
75    }
76    pub fn into_inner(self) -> T {
77        *self.node
78    }
79}
80
81impl<T> From<T> for Spanned<T> {
82    fn from(value: T) -> Self {
83        Self {
84            span: Default::default(),
85            node: Box::new(value),
86        }
87    }
88}