error_enum_core/
span.rs

1use crate::{Indexer, LineIndexer};
2use std::{fmt, ops::Range, sync::Arc};
3
4/// Trait for span types used in error enums.
5pub trait Span: Clone {
6    /// The URI type for the span.
7    type Uri: PartialEq + Clone + fmt::Display;
8    /// The source text type for the span.
9    type Source: AsRef<str> + Clone;
10    /// The index of the source text.
11    type Index: Indexer;
12
13    /// Get the start position of the span.
14    fn start(&self) -> usize;
15    /// Get the end position of the span.
16    fn end(&self) -> usize;
17    /// Get the range of the span.
18    fn range(&self) -> Range<usize> {
19        self.start()..self.end()
20    }
21    /// Get the source text of the span.
22    fn source_text(&self) -> &Self::Source;
23    /// Get the index of the source.
24    fn source_index(&self) -> &Self::Index;
25    /// Get the URI of the span.
26    fn uri(&self) -> &Self::Uri;
27}
28
29/// A simple implementation of [`Span`].
30#[derive(Clone, Debug, PartialEq, Eq)]
31pub struct SimpleSpan {
32    uri: Arc<str>,
33    source: Arc<str>,
34    indexer: Arc<LineIndexer>,
35    start: usize,
36    end: usize,
37}
38
39impl SimpleSpan {
40    /// Create a new [`SimpleSpan`].
41    pub fn new(
42        uri: impl Into<Arc<str>>,
43        source: impl Into<Arc<str>>,
44        start: usize,
45        end: usize,
46    ) -> Self {
47        let uri = uri.into();
48        let source = source.into();
49        let indexer = LineIndexer::new(&source).into();
50        Self {
51            uri,
52            source,
53            indexer,
54            start,
55            end,
56        }
57    }
58}
59
60impl Span for SimpleSpan {
61    type Uri = Arc<str>;
62    type Source = Arc<str>;
63    type Index = Arc<LineIndexer>;
64
65    fn start(&self) -> usize {
66        self.start
67    }
68    fn end(&self) -> usize {
69        self.end
70    }
71    fn source_text(&self) -> &Self::Source {
72        &self.source
73    }
74    fn source_index(&self) -> &Self::Index {
75        &self.indexer
76    }
77    fn uri(&self) -> &Self::Uri {
78        &self.uri
79    }
80}
81
82impl Default for SimpleSpan {
83    fn default() -> Self {
84        Self::new("", "", 0, 0)
85    }
86}
87
88impl From<&SimpleSpan> for SimpleSpan {
89    fn from(value: &SimpleSpan) -> Self {
90        value.clone()
91    }
92}