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
use crate::sources::source_file::SourceFile;
use miette::{MietteError, SourceCode, SourceSpan, SpanContents};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Span {
pub position: usize,
pub length: usize,
pub source: SourceFile,
}
impl Span {
pub fn from_length(source: &SourceFile, position: usize, length: usize) -> Self {
Self {
source: source.clone(),
position,
length,
}
}
pub fn from_end(source: &SourceFile, position: usize, end: usize) -> Self {
assert!(end >= position);
Self {
source: source.clone(),
position,
length: end - position,
}
}
pub fn end(&self) -> usize {
self.position + self.length
}
pub fn as_str(&self) -> &str {
&self.source.contents()[self.position..self.position + self.length]
}
pub fn merge(&self, other: &Span) -> Self {
Self::from_end(
&self.source,
self.position.min(other.position),
self.end().max(other.end()),
)
}
}
impl SourceCode for Span {
fn read_span<'a>(
&'a self,
span: &SourceSpan,
context_lines_before: usize,
context_lines_after: usize,
) -> Result<Box<dyn SpanContents<'a> + 'a>, MietteError> {
<str as SourceCode>::read_span(
self.source.contents_for_display(),
span,
context_lines_before,
context_lines_after,
)
}
}
impl From<Span> for SourceSpan {
fn from(span: Span) -> Self {
SourceSpan::from((span.position, span.length))
}
}