mago-span 1.29.0

Tracks exact character positions in source code, making it easier to report precise errors, warnings, and other diagnostics.
Documentation
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Provides fundamental types for source code location tracking.
//!
//! This crate defines the core primitives [`Position`] and [`Span`] used throughout
//! mago to identify specific locations in source files. It also provides
//! the generic traits [`HasPosition`] and [`HasSpan`] to abstract over any syntax
//! tree node or token that has a location.

use std::ops::Bound;
use std::ops::Range;
use std::ops::RangeBounds;

use serde::Deserialize;
use serde::Serialize;

use mago_database::file::FileId;
use mago_database::file::HasFileId;

/// Represents a specific byte offset within a single source file.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Position {
    pub offset: u32,
}

/// Represents a contiguous range of source code within a single file.
///
/// A `Span` is defined by a `start` and `end` [`Position`], marking the beginning
/// (inclusive) and end (exclusive) of a source code segment.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
pub struct Span {
    /// The unique identifier of the file this span belongs to.
    pub file_id: FileId,
    /// The start position is inclusive, meaning it includes the byte at this position.
    pub start: Position,
    /// The end position is exclusive, meaning it does not include the byte at this position.
    pub end: Position,
}

/// A trait for types that have a single, defined source position.
pub trait HasPosition {
    /// Returns the source position.
    fn position(&self) -> Position;

    /// A convenience method to get the byte offset of the position.
    #[inline]
    fn offset(&self) -> u32 {
        self.position().offset
    }
}

/// A trait for types that cover a span of source code.
pub trait HasSpan {
    /// Returns the source span.
    fn span(&self) -> Span;

    /// A convenience method to get the starting position of the span.
    #[inline]
    fn start_position(&self) -> Position {
        self.span().start
    }

    /// A convenience method to get the starting byte offset of the span.
    #[inline]
    fn start_offset(&self) -> u32 {
        self.start_position().offset
    }

    /// A convenience method to get the ending position of the span.
    #[inline]
    fn end_position(&self) -> Position {
        self.span().end
    }

    /// A convenience method to get the ending byte offset of the span.
    #[inline]
    fn end_offset(&self) -> u32 {
        self.end_position().offset
    }
}

impl Position {
    /// Creates a new `Position` from a byte offset.
    #[inline]
    #[must_use]
    pub const fn new(offset: u32) -> Self {
        Self { offset }
    }

    /// Creates a new `Position` with an offset of zero.
    #[inline]
    #[must_use]
    pub const fn zero() -> Self {
        Self { offset: 0 }
    }

    /// Checks if this position is at the start of a file.
    #[inline]
    #[must_use]
    pub const fn is_zero(&self) -> bool {
        self.offset == 0
    }

    /// Returns a new position moved forward by the given offset.
    ///
    /// Uses saturating arithmetic to prevent overflow.
    #[inline]
    #[must_use]
    pub const fn forward(&self, offset: u32) -> Self {
        Self { offset: self.offset.saturating_add(offset) }
    }

    /// Returns a new position moved backward by the given offset.
    ///
    /// Uses saturating arithmetic to prevent underflow.
    #[inline]
    #[must_use]
    pub const fn backward(&self, offset: u32) -> Self {
        Self { offset: self.offset.saturating_sub(offset) }
    }

    /// Creates a `Range<u32>` starting at this position's offset with a given length.
    #[inline]
    #[must_use]
    pub const fn range_for(&self, length: u32) -> Range<u32> {
        self.offset..self.offset.saturating_add(length)
    }
}

impl Span {
    /// Creates a new `Span` from a start and end position.
    ///
    /// # Panics
    ///
    /// In debug builds, this will panic if the start and end positions are not
    /// from the same file (unless one is a dummy position).
    #[inline]
    #[must_use]
    pub const fn new(file_id: FileId, start: Position, end: Position) -> Self {
        Self { file_id, start, end }
    }

    /// Creates a new `Span` with a zero-length, starting and ending at the same position.
    #[inline]
    #[must_use]
    pub const fn zero() -> Self {
        Self { file_id: FileId::zero(), start: Position::zero(), end: Position::zero() }
    }

    /// Creates a "dummy" span with a null file ID.
    #[inline]
    #[must_use]
    pub fn dummy(start_offset: u32, end_offset: u32) -> Self {
        Self::new(FileId::zero(), Position::new(start_offset), Position::new(end_offset))
    }

    /// Creates a new span that starts at the beginning of the first span
    /// and ends at the conclusion of the second span.
    #[inline]
    #[must_use]
    pub fn between(start: Span, end: Span) -> Self {
        start.join(end)
    }

    /// Checks if this span is a zero-length span, meaning it starts and ends at the same position.
    #[inline]
    #[must_use]
    pub const fn is_zero(&self) -> bool {
        self.start.is_zero() && self.end.is_zero()
    }

    /// Creates a new span that encompasses both `self` and `other`.
    /// The new span starts at `self.start` and ends at `other.end`.
    #[inline]
    #[must_use]
    pub fn join(self, other: Span) -> Span {
        Span::new(self.file_id, self.start, other.end)
    }

    /// Creates a new span that starts at the beginning of this span
    /// and ends at the specified position.
    #[inline]
    #[must_use]
    pub fn to_end(&self, end: Position) -> Span {
        Span::new(self.file_id, self.start, end)
    }

    /// Creates a new span that starts at the specified position
    /// and ends at the end of this span.
    #[inline]
    #[must_use]
    pub fn from_start(&self, start: Position) -> Span {
        Span::new(self.file_id, start, self.end)
    }

    /// Creates a new span that is a subspan of this span, defined by the given byte offsets.
    /// The `start` and `end` parameters are relative to the start of this span.
    #[inline]
    #[must_use]
    pub fn subspan(&self, start: u32, end: u32) -> Span {
        Span::new(self.file_id, self.start.forward(start), self.start.forward(end))
    }

    /// Checks if a position is contained within this span's byte offsets.
    #[inline]
    pub fn contains(&self, position: &impl HasPosition) -> bool {
        self.has_offset(position.offset())
    }

    /// Checks if a raw byte offset is contained within this span.
    #[inline]
    #[must_use]
    pub fn has_offset(&self, offset: u32) -> bool {
        self.start.offset <= offset && offset <= self.end.offset
    }

    /// Converts the span to a `Range<u32>` of its byte offsets.
    #[inline]
    #[must_use]
    pub fn to_range(&self) -> Range<u32> {
        self.start.offset..self.end.offset
    }

    /// Converts the span to a `Range<usize>` of its byte offsets.
    #[inline]
    #[must_use]
    pub fn to_range_usize(&self) -> Range<usize> {
        let start = self.start.offset as usize;
        let end = self.end.offset as usize;

        start..end
    }

    /// Converts the span to a tuple of byte offsets.
    #[inline]
    #[must_use]
    pub fn to_offset_tuple(&self) -> (u32, u32) {
        (self.start.offset, self.end.offset)
    }

    /// Returns the length of the span in bytes.
    #[inline]
    #[must_use]
    pub fn length(&self) -> u32 {
        self.end.offset.saturating_sub(self.start.offset)
    }

    #[inline]
    pub fn is_before(&self, other: &impl HasPosition) -> bool {
        self.end.offset <= other.position().offset
    }

    #[inline]
    pub fn is_after(&self, other: &impl HasPosition) -> bool {
        self.start.offset >= other.position().offset
    }
}

impl HasPosition for Position {
    #[inline]
    fn position(&self) -> Position {
        *self
    }
}

impl HasSpan for Span {
    #[inline]
    fn span(&self) -> Span {
        *self
    }
}

impl RangeBounds<u32> for Span {
    #[inline]
    fn start_bound(&self) -> Bound<&u32> {
        Bound::Included(&self.start.offset)
    }

    #[inline]
    fn end_bound(&self) -> Bound<&u32> {
        Bound::Excluded(&self.end.offset)
    }
}

/// A blanket implementation that allows any `HasSpan` type to also be treated
/// as a `HasPosition` type, using the span's start as its position.
impl<T: HasSpan> HasPosition for T {
    #[inline]
    fn position(&self) -> Position {
        self.start_position()
    }
}

impl HasFileId for Span {
    #[inline]
    fn file_id(&self) -> FileId {
        self.file_id
    }
}

/// Ergonomic blanket impl for references.
impl<T: HasSpan> HasSpan for &T {
    #[inline]
    fn span(&self) -> Span {
        (*self).span()
    }
}

/// Ergonomic blanket impl for boxed values.
impl<T: HasSpan> HasSpan for Box<T> {
    #[inline]
    fn span(&self) -> Span {
        self.as_ref().span()
    }
}

impl From<Span> for Range<u32> {
    #[inline]
    fn from(span: Span) -> Range<u32> {
        span.to_range()
    }
}

impl From<&Span> for Range<u32> {
    #[inline]
    fn from(span: &Span) -> Range<u32> {
        span.to_range()
    }
}

impl From<Span> for Range<usize> {
    #[inline]
    fn from(span: Span) -> Range<usize> {
        let start = span.start.offset as usize;
        let end = span.end.offset as usize;

        start..end
    }
}

impl From<&Span> for Range<usize> {
    #[inline]
    fn from(span: &Span) -> Range<usize> {
        let start = span.start.offset as usize;
        let end = span.end.offset as usize;

        start..end
    }
}

impl From<Position> for u32 {
    #[inline]
    fn from(position: Position) -> u32 {
        position.offset
    }
}

impl From<&Position> for u32 {
    #[inline]
    fn from(position: &Position) -> u32 {
        position.offset
    }
}

impl From<u32> for Position {
    #[inline]
    fn from(offset: u32) -> Self {
        Position { offset }
    }
}

impl std::ops::Add<u32> for Position {
    type Output = Position;

    #[inline]
    fn add(self, rhs: u32) -> Self::Output {
        self.forward(rhs)
    }
}

impl std::ops::Sub<u32> for Position {
    type Output = Position;

    #[inline]
    fn sub(self, rhs: u32) -> Self::Output {
        self.backward(rhs)
    }
}

impl std::ops::AddAssign<u32> for Position {
    #[inline]
    fn add_assign(&mut self, rhs: u32) {
        self.offset = self.offset.saturating_add(rhs);
    }
}

impl std::ops::SubAssign<u32> for Position {
    /// Moves the position backward in-place.
    #[inline]
    fn sub_assign(&mut self, rhs: u32) {
        self.offset = self.offset.saturating_sub(rhs);
    }
}

impl std::fmt::Display for Position {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.offset)
    }
}

impl std::fmt::Display for Span {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}..{}", self.start.offset, self.end.offset)
    }
}