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
use std::ops::Deref;
use std::path::Path;
use std::{fmt, vec};
use unicode_width::UnicodeWidthChar;
use super::span::{BytePos, ByteSpan, CharPos, Pos};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Location {
line: usize,
column: usize,
}
impl Location {
pub const fn line(&self) -> usize {
self.line
}
pub const fn column(&self) -> usize {
self.column
}
pub fn display(&self) -> String {
format!("{}:{}", self.line, self.column + 1)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SourceOrigin<'a> {
File(&'a Path),
Anonymous,
}
impl<'a> fmt::Display for SourceOrigin<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::File(path) => fmt::Display::fmt(&path.display(), f),
Self::Anonymous => f.write_str("anonymous"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MultiByteChar {
pos: BytePos,
bytes: u8,
}
impl MultiByteChar {
pub const fn pos(&self) -> &BytePos {
&self.pos
}
pub const fn width(&self) -> u8 {
self.bytes
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SpecialWidthChar {
ZeroWidth(BytePos),
Wide(BytePos),
Tab(BytePos),
}
impl SpecialWidthChar {
pub fn new(pos: BytePos, width: usize) -> Self {
match width {
0 => Self::ZeroWidth(pos),
2 => Self::Wide(pos),
4 => Self::Tab(pos),
_ => panic!("Unsupported width for SpecialWidthChar: {}", width),
}
}
pub const fn width(&self) -> usize {
match self {
Self::ZeroWidth(_) => 0,
Self::Wide(_) => 2,
Self::Tab(_) => 4,
}
}
pub const fn pos(&self) -> &BytePos {
match self {
Self::ZeroWidth(p) | Self::Wide(p) | Self::Tab(p) => p,
}
}
}
fn analyze_source(content: &'_ str) -> (Vec<BytePos>, Vec<SpecialWidthChar>, Vec<MultiByteChar>) {
let mut i = 0;
let mut lines = vec![BytePos::new(0)];
let mut special_width_chars = Vec::new();
let mut multi_byte_chars = Vec::new();
while i < content.len() {
let byte = content.as_bytes()[i];
let mut char_len = 1;
if byte < 32 {
match byte {
b'\n' => lines.push(BytePos::from_usize(i + 1)),
b'\t' => special_width_chars.push(SpecialWidthChar::Tab(BytePos::from_usize(i))),
_ => special_width_chars.push(SpecialWidthChar::ZeroWidth(BytePos::from_usize(i))),
}
} else if byte > 127 {
let chr = content[i..].chars().next().expect("A valid char");
char_len = chr.len_utf8();
let pos = BytePos::from_usize(i);
if char_len > 1 {
multi_byte_chars.push(MultiByteChar {
pos,
bytes: char_len as u8,
})
}
let char_width = UnicodeWidthChar::width(chr).unwrap_or(0);
if char_width != 1 {
special_width_chars.push(SpecialWidthChar::new(pos, char_width));
}
}
i += char_len;
}
(lines, special_width_chars, multi_byte_chars)
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Source<'a> {
pub(crate) origin: SourceOrigin<'a>,
pub(crate) content: &'a str,
pub(crate) lines: Vec<BytePos>,
pub(crate) special_width_chars: Vec<SpecialWidthChar>,
pub(crate) multi_byte_chars: Vec<MultiByteChar>,
}
impl<'a> Source<'a> {
pub fn new(origin: SourceOrigin<'a>, content: &'a str) -> Self {
let (lines, special_width_chars, multi_byte_chars) = analyze_source(content);
Self {
origin,
content,
lines,
special_width_chars,
multi_byte_chars,
}
}
pub fn anonymous(content: &'a str) -> Self {
Self::new(SourceOrigin::Anonymous, content)
}
pub fn file(path: &'a Path, content: &'a str) -> Self {
Self::new(SourceOrigin::File(path), content)
}
pub fn get_charpos(&self, pos: BytePos) -> CharPos {
let mut offset = 0;
let mut count = 0;
for swc in &self.special_width_chars {
if swc.pos() < &pos {
offset += swc.width();
count += 1;
} else {
break;
}
}
for mbc in &self.multi_byte_chars {
if mbc.pos() < &pos {
offset += 1;
count += mbc.width() as usize;
} else {
break;
}
}
let cpos = CharPos::from_usize((pos.as_usize() + offset) - count);
log::trace!("Translating pos: {} > {}", pos, cpos,);
cpos
}
pub fn get_pos_line_idx(&self, pos: BytePos) -> usize {
match self.lines.binary_search(&pos) {
Ok(idx) => idx,
Err(idx) => idx - 1,
}
}
pub fn get_pos_location(&self, pos: BytePos) -> Location {
let line_idx = self.get_pos_line_idx(pos);
let line_start = self.lines[line_idx];
let pos_cpos = self.get_charpos(pos);
let line_start_cpos = self.get_charpos(line_start);
Location {
line: line_idx + 1,
column: (pos_cpos.as_usize() - line_start_cpos.as_usize()),
}
}
pub fn get_idx_line(&self, idx: usize) -> &'a str {
let line_end_idx = self.lines.get(idx + 1);
let line_start = self.lines[idx];
let line_end = BytePos::from_usize(
line_end_idx.map_or_else(|| self.content.len(), |&idx| idx.as_usize() - 1),
);
&self.content[ByteSpan::new(line_start, line_end)]
}
pub fn get_pos_line(&self, pos: BytePos) -> &'a str {
self.get_idx_line(self.get_pos_line_idx(pos))
}
pub const fn origin(&self) -> &SourceOrigin<'_> {
&self.origin
}
pub const fn content(&self) -> &str {
self.content
}
}
impl Deref for Source<'_> {
type Target = str;
fn deref(&self) -> &Self::Target {
self.content
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn location_lines() {
crate::tests::setup_test_env();
let content = r#"Hello
World
Foo
Bar"#;
let src = Source::anonymous(content);
assert_eq!(
src.get_pos_location(BytePos::new(0)),
Location { line: 1, column: 0 }
);
assert_eq!(
src.get_pos_location(BytePos::new(6)),
Location { line: 2, column: 0 }
);
}
#[test]
fn location_special() {
crate::tests::setup_test_env();
let content = "\tA\r\n\t\tHello";
let src = Source::anonymous(content);
assert_eq!(
src.get_pos_location(BytePos::new(1)),
Location { line: 1, column: 4 }
);
assert_eq!(
src.get_pos_location(BytePos::new(6)),
Location { line: 2, column: 8 }
);
}
}