Skip to main content

runic_diagnostics/source/
span.rs

1use core::{
2    borrow::Borrow,
3    fmt,
4    hash::{Hash, Hasher},
5    ops::{Bound, Deref, DerefMut, Index, Range, RangeBounds},
6};
7
8#[cfg(feature = "serde")]
9use serde::{Deserialize, Serialize};
10
11use super::*;
12
13/// A validated, half-open byte range.
14#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
15pub struct TextRange {
16    start: u32,
17    end: u32,
18}
19
20impl TextRange {
21    pub const fn new(start: u32, end: u32) -> Result<Self, TextRangeError> {
22        if start > end {
23            Err(TextRangeError::Reversed { start, end })
24        } else {
25            Ok(Self { start, end })
26        }
27    }
28
29    pub fn try_from_usize(start: usize, end: usize) -> Result<Self, TextRangeError> {
30        let start =
31            u32::try_from(start).map_err(|_| TextRangeError::OffsetTooLarge { offset: start })?;
32        let end = u32::try_from(end).map_err(|_| TextRangeError::OffsetTooLarge { offset: end })?;
33        Self::new(start, end)
34    }
35
36    pub const fn start(self) -> u32 {
37        self.start
38    }
39
40    pub const fn end(self) -> u32 {
41        self.end
42    }
43
44    /// Gets the length of this text range in bytes.
45    pub const fn len(&self) -> usize {
46        self.end as usize - self.start as usize
47    }
48
49    /// Returns true if this text range is empty
50    pub const fn is_empty(&self) -> bool {
51        self.start == self.end
52    }
53
54    /// Converts this span into a [`Range<usize>`].
55    #[inline]
56    pub fn into_slice_index(self) -> Range<usize> {
57        (self.start as usize)..(self.end as usize)
58    }
59}
60
61impl Index<TextRange> for [u8] {
62    type Output = [u8];
63
64    #[inline]
65    fn index(&self, index: TextRange) -> &Self::Output {
66        &self[index.into_slice_index()]
67    }
68}
69
70impl RangeBounds<u32> for TextRange {
71    #[inline(always)]
72    fn start_bound(&self) -> Bound<&u32> {
73        Bound::Included(&self.start)
74    }
75
76    #[inline(always)]
77    fn end_bound(&self) -> Bound<&u32> {
78        Bound::Excluded(&self.end)
79    }
80}
81
82#[derive(Clone, Copy, Debug, Eq, PartialEq)]
83pub enum TextRangeError {
84    Reversed { start: u32, end: u32 },
85    OffsetTooLarge { offset: usize },
86}
87
88impl fmt::Display for TextRangeError {
89    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
90        match self {
91            Self::Reversed { start, end } => {
92                write!(formatter, "source range starts at {start} after ending at {end}")
93            }
94            Self::OffsetTooLarge { offset } => {
95                write!(formatter, "source offset {offset} does not fit in u32")
96            }
97        }
98    }
99}
100
101impl core::error::Error for TextRangeError {}
102
103/// A range together with exact source provenance and an optional revision.
104#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
105pub struct SourceSpan {
106    source: SourceKey,
107    revision: Option<SourceRevision>,
108    range: TextRange,
109}
110
111impl Default for SourceSpan {
112    fn default() -> Self {
113        Self::UNKNOWN
114    }
115}
116
117impl SourceSpan {
118    /// A sentinel [SourceSpan] that indicates compiler-generated/synthetic code
119    ///
120    /// This is used to distinguish between:
121    /// - UNKNOWN: debug info missing or failed to parse from DWARF
122    /// - SYNTHETIC: compiler-generated code that doesn't correspond to any user source
123    pub const SYNTHETIC: Self = Self {
124        source: SourceKey::Session(SourceId::UNKNOWN),
125        revision: None,
126        range: TextRange {
127            start: u32::MAX,
128            end: u32::MAX,
129        },
130    };
131    /// A sentinel [SourceSpan] that indicates the span is unknown/invalid
132    pub const UNKNOWN: Self = Self {
133        source: SourceKey::Session(SourceId::UNKNOWN),
134        revision: None,
135        range: TextRange { start: 0, end: 0 },
136    };
137
138    pub const fn new(
139        source: SourceKey,
140        revision: Option<SourceRevision>,
141        range: TextRange,
142    ) -> Self {
143        Self {
144            source,
145            revision,
146            range,
147        }
148    }
149
150    pub const fn session(id: SourceId, range: TextRange) -> Self {
151        Self::new(SourceKey::Session(id), None, range)
152    }
153
154    pub const fn attached(id: SourceId, range: TextRange) -> Self {
155        Self::new(SourceKey::Attached(id), None, range)
156    }
157
158    /// Creates a new [SourceSpan] for a specific offset.
159    pub fn at(source: SourceKey, revision: Option<SourceRevision>, offset: u32) -> Self {
160        Self {
161            source,
162            revision,
163            range: TextRange {
164                start: offset,
165                end: offset.saturating_add(1),
166            },
167        }
168    }
169
170    pub const fn with_revision(mut self, revision: SourceRevision) -> Self {
171        self.revision = Some(revision);
172        self
173    }
174
175    pub fn set_source_key(&mut self, source: SourceKey) {
176        self.source = source;
177    }
178
179    /// Try to create a new [SourceSpan] from the given range with `usize` bounds.
180    pub fn try_from_range(
181        source: SourceKey,
182        revision: Option<SourceRevision>,
183        range: Range<usize>,
184    ) -> Result<Self, TextRangeError> {
185        let range = TextRange::try_from_usize(range.start, range.end)?;
186
187        Ok(SourceSpan {
188            source,
189            revision,
190            range,
191        })
192    }
193
194    /// Try to create a new [SourceSpan] from the given [TextRange]
195    pub const fn from_text_range(
196        source: SourceKey,
197        revision: Option<SourceRevision>,
198        range: TextRange,
199    ) -> Self {
200        SourceSpan {
201            source,
202            revision,
203            range,
204        }
205    }
206
207    /// Returns `true` if this [SourceSpan] represents the unknown span
208    pub const fn is_unknown(&self) -> bool {
209        self.source.id().is_unknown() && self.range.start == 0 && self.range.end == 0
210    }
211
212    /// Returns `true` if this [SourceSpan] represents synthetic/compiler-generated code
213    pub const fn is_synthetic(&self) -> bool {
214        self.source.id().is_unknown() && self.range.start == u32::MAX && self.range.end == u32::MAX
215    }
216
217    pub const fn source(self) -> SourceKey {
218        self.source
219    }
220
221    pub const fn revision(self) -> Option<SourceRevision> {
222        self.revision
223    }
224
225    pub const fn range(self) -> TextRange {
226        self.range
227    }
228
229    /// Gets the length of this span in bytes.
230    pub const fn len(&self) -> usize {
231        self.range.len()
232    }
233
234    /// Returns true if this span is empty
235    pub const fn is_empty(&self) -> bool {
236        self.range.is_empty()
237    }
238}
239
240/// This trait should be implemented for any type that has an associated [SourceSpan].
241pub trait Spanned {
242    fn span(&self) -> SourceSpan;
243}
244
245impl Spanned for SourceSpan {
246    #[inline(always)]
247    fn span(&self) -> SourceSpan {
248        *self
249    }
250}
251
252impl<T: ?Sized + Spanned> Spanned for alloc::boxed::Box<T> {
253    fn span(&self) -> SourceSpan {
254        (**self).span()
255    }
256}
257
258impl<T: ?Sized + Spanned> Spanned for alloc::rc::Rc<T> {
259    fn span(&self) -> SourceSpan {
260        (**self).span()
261    }
262}
263
264impl<T: ?Sized + Spanned> Spanned for alloc::sync::Arc<T> {
265    fn span(&self) -> SourceSpan {
266        (**self).span()
267    }
268}
269
270// SPAN
271// ================================================================================================
272
273/// This type is used to wrap any `T` with a [SourceSpan], and is typically used when it is not
274/// convenient to add a [SourceSpan] to the type - most commonly because we don't control the type.
275#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
276pub struct Span<T> {
277    #[cfg_attr(feature = "serde", serde(skip, default))]
278    span: SourceSpan,
279    spanned: T,
280}
281
282impl<T> Spanned for Span<T> {
283    fn span(&self) -> SourceSpan {
284        self.span
285    }
286}
287
288impl<T: Copy> Copy for Span<T> {}
289
290impl<T: Clone> Clone for Span<T> {
291    fn clone(&self) -> Self {
292        Self {
293            span: self.span,
294            spanned: self.spanned.clone(),
295        }
296    }
297}
298
299impl<T: Default> Default for Span<T> {
300    fn default() -> Self {
301        Self {
302            span: SourceSpan::UNKNOWN,
303            spanned: T::default(),
304        }
305    }
306}
307
308impl<T> Span<T> {
309    /// Creates a span for `spanned` with `span`.
310    #[inline]
311    pub fn new(span: SourceSpan, spanned: T) -> Self {
312        Self { span, spanned }
313    }
314
315    /// Creates a [Span] from a value with an unknown/default location.
316    pub fn unknown(spanned: T) -> Self {
317        Self {
318            span: Default::default(),
319            spanned,
320        }
321    }
322
323    /// Consume this [Span] and get a new one with `span` as the underlying source span
324    #[inline]
325    pub fn with_span(mut self, span: SourceSpan) -> Self {
326        self.span = span;
327        self
328    }
329
330    /// Gets the associated [SourceSpan] for this spanned item.
331    #[inline(always)]
332    pub const fn span(&self) -> SourceSpan {
333        self.span
334    }
335
336    /// Gets a reference to the spanned item.
337    #[inline(always)]
338    pub const fn inner(&self) -> &T {
339        &self.spanned
340    }
341
342    /// Applies a transformation to the spanned value while retaining the same [SourceSpan].
343    #[inline]
344    pub fn map<U, F>(self, mut f: F) -> Span<U>
345    where
346        F: FnMut(T) -> U,
347    {
348        Span {
349            span: self.span,
350            spanned: f(self.spanned),
351        }
352    }
353
354    /// Like [`Option<T>::as_deref`], this constructs a [`Span<U>`] wrapping the result of
355    /// dereferencing the inner value of type `T` as a value of type `U`.
356    pub fn as_deref<U>(&self) -> Span<&U>
357    where
358        U: ?Sized,
359        T: Deref<Target = U>,
360    {
361        Span {
362            span: self.span,
363            spanned: &*self.spanned,
364        }
365    }
366
367    /// Gets a new [Span] that borrows the inner value.
368    pub fn as_ref(&self) -> Span<&T> {
369        Span {
370            span: self.span,
371            spanned: &self.spanned,
372        }
373    }
374
375    /// Manually set the source key for the span of this item
376    ///
377    /// See also [SourceSpan::set_source_key].
378    pub fn set_source_key(&mut self, id: SourceKey) {
379        self.span.set_source_key(id);
380    }
381
382    /// Shifts the span right by `count` units
383    ///
384    /// It is up to the caller to ensure that the shifted text range is valid within its document
385    #[inline]
386    pub fn shift(&mut self, count: u32) {
387        self.span.range.start += count;
388        self.span.range.end += count;
389    }
390
391    /// Extends the end of the span by `count` units.
392    ///
393    /// It is up to the caller to ensure that the extended text range is valid within its document
394    #[inline]
395    pub fn extend(&mut self, count: u32) {
396        self.span.range.end += count;
397    }
398
399    /// Consumes this span, returning the component parts, i.e. the [SourceSpan] and value of type
400    /// `T`.
401    #[inline]
402    pub fn into_parts(self) -> (SourceSpan, T) {
403        (self.span, self.spanned)
404    }
405
406    /// Unwraps the spanned value of type `T`.
407    #[inline]
408    pub fn into_inner(self) -> T {
409        self.spanned
410    }
411}
412
413impl<T> Borrow<T> for Span<T> {
414    fn borrow(&self) -> &T {
415        &self.spanned
416    }
417}
418
419impl<T: Borrow<str>> Borrow<str> for Span<T> {
420    fn borrow(&self) -> &str {
421        self.spanned.borrow()
422    }
423}
424
425impl<U, T: Borrow<[U]>> Borrow<[U]> for Span<T> {
426    fn borrow(&self) -> &[U] {
427        self.spanned.borrow()
428    }
429}
430
431impl<T> Deref for Span<T> {
432    type Target = T;
433
434    #[inline(always)]
435    fn deref(&self) -> &Self::Target {
436        &self.spanned
437    }
438}
439
440impl<T> DerefMut for Span<T> {
441    #[inline(always)]
442    fn deref_mut(&mut self) -> &mut Self::Target {
443        &mut self.spanned
444    }
445}
446
447impl<T: ?Sized, U: AsRef<T>> AsRef<T> for Span<U> {
448    fn as_ref(&self) -> &T {
449        self.spanned.as_ref()
450    }
451}
452
453impl<T: ?Sized, U: AsMut<T>> AsMut<T> for Span<U> {
454    fn as_mut(&mut self) -> &mut T {
455        self.spanned.as_mut()
456    }
457}
458
459impl<T: fmt::Debug> fmt::Debug for Span<T> {
460    #[inline]
461    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
462        fmt::Debug::fmt(&self.spanned, f)
463    }
464}
465
466impl<T: fmt::Display> fmt::Display for Span<T> {
467    #[inline]
468    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
469        fmt::Display::fmt(&self.spanned, f)
470    }
471}
472
473impl<T: Eq> Eq for Span<T> {}
474
475impl<T: PartialEq> PartialEq for Span<T> {
476    #[inline]
477    fn eq(&self, other: &Self) -> bool {
478        self.spanned.eq(&other.spanned)
479    }
480}
481
482impl<T: PartialEq> PartialEq<T> for Span<T> {
483    #[inline]
484    fn eq(&self, other: &T) -> bool {
485        self.spanned.eq(other)
486    }
487}
488
489impl<T: Ord> Ord for Span<T> {
490    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
491        self.spanned.cmp(&other.spanned)
492    }
493}
494
495impl<T: PartialOrd> PartialOrd for Span<T> {
496    #[inline]
497    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
498        self.spanned.partial_cmp(&other.spanned)
499    }
500}
501
502impl<T: Hash> Hash for Span<T> {
503    fn hash<H: Hasher>(&self, state: &mut H) {
504        self.spanned.hash(state);
505    }
506}