typst_syntax/
span.rs

1use std::fmt::{self, Debug, Formatter};
2use std::num::{NonZeroU16, NonZeroU64};
3use std::ops::Range;
4
5use ecow::EcoString;
6
7use crate::FileId;
8
9/// Defines a range in a file.
10///
11/// This is used throughout the compiler to track which source section an
12/// element stems from or an error applies to.
13///
14/// - The [`.id()`](Self::id) function can be used to get the `FileId` for the
15///   span and, by extension, its file system path.
16/// - The `WorldExt::range` function can be used to map the span to a
17///   `Range<usize>`.
18///
19/// This type takes up 8 bytes and is copyable and null-optimized (i.e.
20/// `Option<Span>` also takes 8 bytes).
21///
22/// Spans come in two flavors: Numbered spans and raw range spans. The
23/// `WorldExt::range` function automatically handles both cases, yielding a
24/// `Range<usize>`.
25///
26/// # Numbered spans
27/// Typst source files use _numbered spans._ Rather than using byte ranges,
28/// which shift a lot as you type, each AST node gets a unique number.
29///
30/// During editing, the span numbers stay mostly stable, even for nodes behind
31/// an insertion. This is not true for simple ranges as they would shift. Spans
32/// can be used as inputs to memoized functions without hurting cache
33/// performance when text is inserted somewhere in the document other than the
34/// end.
35///
36/// Span ids are ordered in the syntax tree to enable quickly finding the node
37/// with some id:
38/// - The id of a parent is always smaller than the ids of any of its children.
39/// - The id of a node is always greater than any id in the subtrees of any left
40///   sibling and smaller than any id in the subtrees of any right sibling.
41///
42/// # Raw range spans
43/// Non Typst-files use raw ranges instead of numbered spans. The maximum
44/// encodable value for start and end is 2^23. Larger values will be saturated.
45#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
46pub struct Span(NonZeroU64);
47
48impl Span {
49    /// The full range of numbers available for source file span numbering.
50    pub(crate) const FULL: Range<u64> = 2..(1 << 47);
51
52    /// The value reserved for the detached span.
53    const DETACHED: u64 = 1;
54
55    /// Data layout:
56    /// | 16 bits file id | 48 bits number |
57    ///
58    /// Number =
59    /// - 1 means detached
60    /// - 2..2^47-1 is a numbered span
61    /// - 2^47..2^48-1 is a raw range span. To retrieve it, you must subtract
62    ///   `RANGE_BASE` and then use shifting/bitmasking to extract the
63    ///   components.
64    const NUMBER_BITS: usize = 48;
65    const FILE_ID_SHIFT: usize = Self::NUMBER_BITS;
66    const NUMBER_MASK: u64 = (1 << Self::NUMBER_BITS) - 1;
67    const RANGE_BASE: u64 = Self::FULL.end;
68    const RANGE_PART_BITS: usize = 23;
69    const RANGE_PART_SHIFT: usize = Self::RANGE_PART_BITS;
70    const RANGE_PART_MASK: u64 = (1 << Self::RANGE_PART_BITS) - 1;
71
72    /// Create a span that does not point into any file.
73    pub const fn detached() -> Self {
74        Self(NonZeroU64::new(Self::DETACHED).unwrap())
75    }
76
77    /// Create a new span from a file id and a number.
78    ///
79    /// Returns `None` if `number` is not contained in `FULL`.
80    pub(crate) const fn from_number(id: FileId, number: u64) -> Option<Self> {
81        if number < Self::FULL.start || number >= Self::FULL.end {
82            return None;
83        }
84        Some(Self::pack(id, number))
85    }
86
87    /// Create a new span from a raw byte range instead of a span number.
88    ///
89    /// If one of the range's parts exceeds the maximum value (2^23), it is
90    /// saturated.
91    pub const fn from_range(id: FileId, range: Range<usize>) -> Self {
92        let max = 1 << Self::RANGE_PART_BITS;
93        let start = if range.start > max { max } else { range.start } as u64;
94        let end = if range.end > max { max } else { range.end } as u64;
95        let number = (start << Self::RANGE_PART_SHIFT) | end;
96        Self::pack(id, Self::RANGE_BASE + number)
97    }
98
99    /// Construct from a raw number.
100    ///
101    /// Should only be used with numbers retrieved via
102    /// [`into_raw`](Self::into_raw). Misuse may results in panics, but no
103    /// unsafety.
104    pub const fn from_raw(v: NonZeroU64) -> Self {
105        Self(v)
106    }
107
108    /// Pack a file ID and the low bits into a span.
109    const fn pack(id: FileId, low: u64) -> Self {
110        let bits = ((id.into_raw().get() as u64) << Self::FILE_ID_SHIFT) | low;
111
112        // The file ID is non-zero.
113        Self(NonZeroU64::new(bits).unwrap())
114    }
115
116    /// Whether the span is detached.
117    pub const fn is_detached(self) -> bool {
118        self.0.get() == Self::DETACHED
119    }
120
121    /// The id of the file the span points into.
122    ///
123    /// Returns `None` if the span is detached.
124    pub const fn id(self) -> Option<FileId> {
125        // Detached span has only zero high bits, so it will trigger the
126        // `None` case.
127        match NonZeroU16::new((self.0.get() >> Self::FILE_ID_SHIFT) as u16) {
128            Some(v) => Some(FileId::from_raw(v)),
129            None => None,
130        }
131    }
132
133    /// The unique number of the span within its [`Source`](crate::Source).
134    pub(crate) const fn number(self) -> u64 {
135        self.0.get() & Self::NUMBER_MASK
136    }
137
138    /// Extract a raw byte range from the span, if it is a raw range span.
139    ///
140    /// Typically, you should use `WorldExt::range` instead.
141    pub const fn range(self) -> Option<Range<usize>> {
142        let Some(number) = self.number().checked_sub(Self::RANGE_BASE) else {
143            return None;
144        };
145
146        let start = (number >> Self::RANGE_PART_SHIFT) as usize;
147        let end = (number & Self::RANGE_PART_MASK) as usize;
148        Some(start..end)
149    }
150
151    /// Extract the raw underlying number.
152    pub const fn into_raw(self) -> NonZeroU64 {
153        self.0
154    }
155
156    /// Return `other` if `self` is detached and `self` otherwise.
157    pub fn or(self, other: Self) -> Self {
158        if self.is_detached() { other } else { self }
159    }
160
161    /// Find the first non-detached span in the iterator.
162    pub fn find(iter: impl IntoIterator<Item = Self>) -> Self {
163        iter.into_iter()
164            .find(|span| !span.is_detached())
165            .unwrap_or(Span::detached())
166    }
167
168    /// Resolve a file location relative to this span's source.
169    pub fn resolve_path(self, path: &str) -> Result<FileId, EcoString> {
170        let Some(file) = self.id() else {
171            return Err("cannot access file system from here".into());
172        };
173        Ok(file.join(path))
174    }
175}
176
177/// A value with a span locating it in the source code.
178#[derive(Copy, Clone, Eq, PartialEq, Hash)]
179pub struct Spanned<T> {
180    /// The spanned value.
181    pub v: T,
182    /// The value's location in source code.
183    pub span: Span,
184}
185
186impl<T> Spanned<T> {
187    /// Create a new instance from a value and its span.
188    pub fn new(v: T, span: Span) -> Self {
189        Self { v, span }
190    }
191
192    /// Convert from `&Spanned<T>` to `Spanned<&T>`
193    pub fn as_ref(&self) -> Spanned<&T> {
194        Spanned { v: &self.v, span: self.span }
195    }
196
197    /// Map the value using a function.
198    pub fn map<F, U>(self, f: F) -> Spanned<U>
199    where
200        F: FnOnce(T) -> U,
201    {
202        Spanned { v: f(self.v), span: self.span }
203    }
204}
205
206impl<T: Debug> Debug for Spanned<T> {
207    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
208        self.v.fmt(f)
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    use std::num::NonZeroU16;
215    use std::ops::Range;
216
217    use crate::{FileId, Span};
218
219    #[test]
220    fn test_span_detached() {
221        let span = Span::detached();
222        assert!(span.is_detached());
223        assert_eq!(span.id(), None);
224        assert_eq!(span.range(), None);
225    }
226
227    #[test]
228    fn test_span_number_encoding() {
229        let id = FileId::from_raw(NonZeroU16::new(5).unwrap());
230        let span = Span::from_number(id, 10).unwrap();
231        assert_eq!(span.id(), Some(id));
232        assert_eq!(span.number(), 10);
233        assert_eq!(span.range(), None);
234    }
235
236    #[test]
237    fn test_span_range_encoding() {
238        let id = FileId::from_raw(NonZeroU16::new(u16::MAX).unwrap());
239        let roundtrip = |range: Range<usize>| {
240            let span = Span::from_range(id, range.clone());
241            assert_eq!(span.id(), Some(id));
242            assert_eq!(span.range(), Some(range));
243        };
244
245        roundtrip(0..0);
246        roundtrip(177..233);
247        roundtrip(0..8388607);
248        roundtrip(8388606..8388607);
249    }
250}