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
use super::Loc;
use crate::source::DecodedInput;
use std::convert::TryInto;
crate::use_native_or_external!(MaybeLoc);
impl Loc {
pub fn to_range(&self) -> std::ops::Range<usize> {
self.begin()..self.end()
}
}
impl Loc {
pub fn size(&self) -> usize {
self.end() - self.begin()
}
pub fn with_begin(&self, begin: usize) -> Loc {
Self::new(begin, self.end())
}
pub fn with_end(&self, end: usize) -> Loc {
Self::new(self.begin(), end)
}
pub fn adjust_begin(&self, delta: i32) -> Loc {
let begin: i32 = self
.begin()
.try_into()
.expect("failed to convert location to i32 (is it too big?)");
let begin: usize = (begin + delta)
.try_into()
.expect("failed to convert location to usize (is it negative?)");
Self::new(begin, self.end())
}
pub fn adjust_end(&self, d: i32) -> Loc {
let end: i32 = self
.end()
.try_into()
.expect("failed to convert location to i32 (is it too big?)");
let end: usize = (end + d)
.try_into()
.expect("failed to convert location to usize (is it negative?)");
Self::new(self.begin(), end)
}
pub fn resize(&self, new_size: usize) -> Loc {
self.with_end(self.begin() + new_size)
}
pub fn join(&self, other: &Self) -> Loc {
Self::new(
std::cmp::min(self.begin(), other.begin()),
std::cmp::max(self.end(), other.end()),
)
}
pub(crate) fn maybe_join(&self, other: &MaybeLoc) -> Loc {
match other.as_ref() {
Some(other) => self.join(other),
None => self.clone(),
}
}
pub fn is_empty(&self) -> bool {
self.begin() == self.end()
}
pub(crate) fn begin_line_col(&self, input: &DecodedInput) -> Option<(usize, usize)> {
input.line_col_for_pos(self.begin())
}
#[allow(dead_code)]
pub(crate) fn end_line_col(&self, input: &DecodedInput) -> Option<(usize, usize)> {
input.line_col_for_pos(self.end())
}
pub(crate) fn expand_to_line(&self, input: &DecodedInput) -> Option<(usize, Loc)> {
let (begin_line, _) = self.begin_line_col(input)?;
let line_no = begin_line;
let line = input.line_at(line_no);
Some((line_no, Self::new(line.start(), line.line_end())))
}
pub fn source(&self, input: &DecodedInput) -> Option<String> {
let bytes = input.substr_at(self.begin(), self.end())?;
Some(String::from_utf8_lossy(bytes).into_owned())
}
pub(crate) fn print(&self, name: &str) {
println!(
"{}{} {}",
" ".repeat(self.begin()),
"~".repeat(self.size()),
name
)
}
}
impl std::fmt::Debug for Loc {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&format!("{}...{}", self.begin(), self.end()))
}
}