mago_span/
lib.rs

1//! Provides fundamental types for source code location tracking.
2//!
3//! This crate defines the core primitives [`Position`] and [`Span`] used throughout
4//! mago to identify specific locations in source files. It also provides
5//! the generic traits [`HasPosition`] and [`HasSpan`] to abstract over any syntax
6//! tree node or token that has a location.
7
8use std::ops::Range;
9
10use serde::Deserialize;
11use serde::Serialize;
12
13use mago_database::file::FileId;
14use mago_database::file::HasFileId;
15
16/// Represents a specific byte offset within a single source file.
17#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
18#[repr(transparent)]
19pub struct Position {
20    pub offset: u32,
21}
22
23/// Represents a contiguous range of source code within a single file.
24///
25/// A `Span` is defined by a `start` and `end` [`Position`], marking the beginning
26/// (inclusive) and end (exclusive) of a source code segment.
27#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
28pub struct Span {
29    /// The unique identifier of the file this span belongs to.
30    pub file_id: FileId,
31    /// The start position is inclusive, meaning it includes the byte at this position.
32    pub start: Position,
33    /// The end position is exclusive, meaning it does not include the byte at this position.
34    pub end: Position,
35}
36
37/// A trait for types that have a single, defined source position.
38pub trait HasPosition {
39    /// Returns the source position.
40    fn position(&self) -> Position;
41
42    /// A convenience method to get the byte offset of the position.
43    #[inline]
44    fn offset(&self) -> u32 {
45        self.position().offset
46    }
47}
48
49/// A trait for types that cover a span of source code.
50pub trait HasSpan {
51    /// Returns the source span.
52    fn span(&self) -> Span;
53
54    /// A convenience method to get the starting position of the span.
55    fn start_position(&self) -> Position {
56        self.span().start
57    }
58
59    /// A convenience method to get the ending position of the span.
60    fn end_position(&self) -> Position {
61        self.span().end
62    }
63}
64
65impl Position {
66    /// Creates a new `Position` from a byte offset.
67    pub const fn new(offset: u32) -> Self {
68        Self { offset }
69    }
70
71    /// Creates a new `Position` with an offset of zero.
72    pub const fn zero() -> Self {
73        Self { offset: 0 }
74    }
75
76    /// Checks if this position is at the start of a file.
77    pub const fn is_zero(&self) -> bool {
78        self.offset == 0
79    }
80
81    /// Returns a new position moved forward by the given offset.
82    ///
83    /// Uses saturating arithmetic to prevent overflow.
84    pub const fn forward(&self, offset: u32) -> Self {
85        Self { offset: self.offset.saturating_add(offset) }
86    }
87
88    /// Returns a new position moved backward by the given offset.
89    ///
90    /// Uses saturating arithmetic to prevent underflow.
91    pub const fn backward(&self, offset: u32) -> Self {
92        Self { offset: self.offset.saturating_sub(offset) }
93    }
94
95    /// Creates a `Range<u32>` starting at this position's offset with a given length.
96    pub const fn range_for(&self, length: u32) -> Range<u32> {
97        self.offset..self.offset.saturating_add(length)
98    }
99}
100
101impl Span {
102    /// Creates a new `Span` from a start and end position.
103    ///
104    /// # Panics
105    ///
106    /// In debug builds, this will panic if the start and end positions are not
107    /// from the same file (unless one is a dummy position).
108    pub const fn new(file_id: FileId, start: Position, end: Position) -> Self {
109        Self { file_id, start, end }
110    }
111
112    /// Creates a new `Span` with a zero-length, starting and ending at the same position.
113    pub const fn zero() -> Self {
114        Self { file_id: FileId::zero(), start: Position::zero(), end: Position::zero() }
115    }
116
117    /// Creates a "dummy" span with a null file ID.
118    pub fn dummy(start_offset: u32, end_offset: u32) -> Self {
119        Self::new(FileId::zero(), Position::new(start_offset), Position::new(end_offset))
120    }
121
122    /// Creates a new span that starts at the beginning of the first span
123    /// and ends at the conclusion of the second span.
124    pub fn between(start: Span, end: Span) -> Self {
125        start.join(end)
126    }
127
128    /// Checks if this span is a zero-length span, meaning it starts and ends at the same position.
129    pub const fn is_zero(&self) -> bool {
130        self.start.is_zero() && self.end.is_zero()
131    }
132
133    /// Creates a new span that encompasses both `self` and `other`.
134    /// The new span starts at `self.start` and ends at `other.end`.
135    pub fn join(self, other: Span) -> Span {
136        Span::new(self.file_id, self.start, other.end)
137    }
138
139    /// Creates a new span that starts at the beginning of this span
140    /// and ends at the specified position.
141    pub fn to_end(&self, end: Position) -> Span {
142        Span::new(self.file_id, self.start, end)
143    }
144
145    /// Creates a new span that starts at the specified position
146    /// and ends at the end of this span.
147    pub fn from_start(&self, start: Position) -> Span {
148        Span::new(self.file_id, start, self.end)
149    }
150
151    /// Creates a new span that is a subspan of this span, defined by the given byte offsets.
152    /// The `start` and `end` parameters are relative to the start of this span.
153    pub fn subspan(&self, start: u32, end: u32) -> Span {
154        Span::new(self.file_id, self.start.forward(start), self.start.forward(end))
155    }
156
157    /// Checks if a position is contained within this span's byte offsets.
158    pub fn contains(&self, position: &impl HasPosition) -> bool {
159        self.has_offset(position.offset())
160    }
161
162    /// Checks if a raw byte offset is contained within this span.
163    pub fn has_offset(&self, offset: u32) -> bool {
164        self.start.offset <= offset && offset <= self.end.offset
165    }
166
167    /// Converts the span to a `Range<u32>` of its byte offsets.
168    pub fn to_range(&self) -> Range<u32> {
169        self.start.offset..self.end.offset
170    }
171
172    /// Converts the span to a `Range<usize>` of its byte offsets.
173    pub fn to_range_usize(&self) -> Range<usize> {
174        let start = self.start.offset as usize;
175        let end = self.end.offset as usize;
176
177        start..end
178    }
179
180    /// Converts the span to a tuple of byte offsets.
181    pub fn to_offset_tuple(&self) -> (u32, u32) {
182        (self.start.offset, self.end.offset)
183    }
184
185    /// Returns the length of the span in bytes.
186    pub fn length(&self) -> u32 {
187        self.end.offset.saturating_sub(self.start.offset)
188    }
189
190    pub fn is_before(&self, other: impl HasPosition) -> bool {
191        self.end.offset <= other.position().offset
192    }
193
194    pub fn is_after(&self, other: impl HasPosition) -> bool {
195        self.start.offset >= other.position().offset
196    }
197}
198
199impl HasPosition for Position {
200    fn position(&self) -> Position {
201        *self
202    }
203}
204
205impl HasSpan for Span {
206    fn span(&self) -> Span {
207        *self
208    }
209}
210
211/// A blanket implementation that allows any `HasSpan` type to also be treated
212/// as a `HasPosition` type, using the span's start as its position.
213impl<T: HasSpan> HasPosition for T {
214    fn position(&self) -> Position {
215        self.start_position()
216    }
217}
218
219impl HasFileId for Span {
220    fn file_id(&self) -> FileId {
221        self.file_id
222    }
223}
224
225/// Ergonomic blanket impl for references.
226impl<T: HasSpan> HasSpan for &T {
227    fn span(&self) -> Span {
228        (*self).span()
229    }
230}
231
232/// Ergonomic blanket impl for boxed values.
233impl<T: HasSpan> HasSpan for Box<T> {
234    fn span(&self) -> Span {
235        self.as_ref().span()
236    }
237}
238
239impl From<Span> for Range<u32> {
240    fn from(span: Span) -> Range<u32> {
241        span.to_range()
242    }
243}
244
245impl From<&Span> for Range<u32> {
246    fn from(span: &Span) -> Range<u32> {
247        span.to_range()
248    }
249}
250
251impl From<Span> for Range<usize> {
252    fn from(span: Span) -> Range<usize> {
253        let start = span.start.offset as usize;
254        let end = span.end.offset as usize;
255
256        start..end
257    }
258}
259
260impl From<&Span> for Range<usize> {
261    fn from(span: &Span) -> Range<usize> {
262        let start = span.start.offset as usize;
263        let end = span.end.offset as usize;
264
265        start..end
266    }
267}
268
269impl From<Position> for u32 {
270    fn from(position: Position) -> u32 {
271        position.offset
272    }
273}
274
275impl From<&Position> for u32 {
276    fn from(position: &Position) -> u32 {
277        position.offset
278    }
279}
280
281impl From<u32> for Position {
282    fn from(offset: u32) -> Self {
283        Position { offset }
284    }
285}
286
287impl std::ops::Add<u32> for Position {
288    type Output = Position;
289
290    fn add(self, rhs: u32) -> Self::Output {
291        self.forward(rhs)
292    }
293}
294
295impl std::ops::Sub<u32> for Position {
296    type Output = Position;
297
298    fn sub(self, rhs: u32) -> Self::Output {
299        self.backward(rhs)
300    }
301}
302
303impl std::ops::AddAssign<u32> for Position {
304    fn add_assign(&mut self, rhs: u32) {
305        self.offset = self.offset.saturating_add(rhs);
306    }
307}
308
309impl std::ops::SubAssign<u32> for Position {
310    /// Moves the position backward in-place.
311    fn sub_assign(&mut self, rhs: u32) {
312        self.offset = self.offset.saturating_sub(rhs);
313    }
314}
315
316impl std::fmt::Display for Position {
317    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
318        write!(f, "{}", self.offset)
319    }
320}
321
322impl std::fmt::Display for Span {
323    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
324        write!(f, "{}..{}", self.start.offset, self.end.offset)
325    }
326}