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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
use crate::name::RcStr;
use memmap::Mmap;
use once_cell::sync::OnceCell;
use std;
use std::borrow::Borrow;
use std::cell::RefCell;
use std::cmp::{max, min};
use std::collections::HashMap;
use std::fmt;
use std::fs::File;
use std::hash::{Hash, Hasher};
use std::path::Path;
use std::rc::Rc;
pub const INVALID_SOURCE: Source = Source(0);
pub const INVALID_LOCATION: Location = Location {
source: INVALID_SOURCE,
offset: 0,
};
pub const INVALID_SPAN: Span = Span {
source: INVALID_SOURCE,
begin: 0,
end: 0,
};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Source(pub u32);
impl Source {
pub fn get_path(self) -> RcStr {
get_source_manager().with(self, |x| x.get_path())
}
pub fn get_content(self) -> Rc<dyn SourceContent> {
get_source_manager().with(self, |x| x.get_content())
}
pub fn extract(self, begin: usize, end: usize) -> String {
get_source_manager().with(self, |x| x.extract(begin, end))
}
}
impl fmt::Debug for Source {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.0 > 0 {
write!(f, "Source({}; \"{}\")", self.0, self.get_path())
} else {
write!(f, "Source(INVALID)")
}
}
}
impl fmt::Display for Source {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.get_path(), f)
}
}
pub trait SourceFile {
fn get_id(&self) -> Source;
fn get_path(&self) -> RcStr;
fn get_content(&self) -> Rc<dyn SourceContent>;
fn extract(&self, begin: usize, end: usize) -> String {
self.get_content().extract(begin, end)
}
}
pub trait SourceContent {
fn iter(&self) -> Box<CharIter>;
fn iter_from(&self, offset: usize) -> Box<CharIter>;
fn extract(&self, begin: usize, end: usize) -> String;
fn extract_iter(&self, begin: usize, end: usize) -> Box<CharIter>;
fn bytes(&self) -> &[u8];
fn lines(&self) -> &[usize];
}
pub struct SourceManager {
map: RefCell<HashMap<RcStr, Source>>,
vect: RefCell<Vec<Box<dyn SourceFile>>>,
}
impl SourceManager {
fn new() -> SourceManager {
SourceManager {
map: RefCell::new(HashMap::new()),
vect: RefCell::new(Vec::new()),
}
}
pub fn with<F, R>(&self, id: Source, f: F) -> R
where
F: FnOnce(&dyn SourceFile) -> R,
{
let ref vect = *self.vect.borrow();
assert!(id.0 > 0, "invalid source");
assert!(
(id.0 as usize - 1) < vect.len(),
"unknown source file: Source({}) >= {}",
id.0,
vect.len()
);
f(&*vect[id.0 as usize - 1])
}
pub fn find<Q: ?Sized>(&self, filename: &Q) -> Option<Source>
where
RcStr: Borrow<Q>,
Q: Eq + Hash,
{
(*self.map.borrow()).get(filename).map(|v| *v)
}
pub fn open(&self, filename: &str) -> Option<Source> {
let mut map = self.map.borrow_mut();
if let Some(&id) = map.get(filename) {
return Some(id);
}
if Path::new(filename).exists() {
let mut vect = self.vect.borrow_mut();
let new_id = Source(vect.len() as u32 + 1);
let v = RcStr::new(filename);
map.insert(v.clone(), new_id);
vect.push(Box::new(DiskSourceFile {
id: new_id,
filename: v,
content: RefCell::new(None),
}));
Some(new_id)
} else {
None
}
}
pub fn add(&self, filename: &str, content: &str) -> Source {
let mut map = self.map.borrow_mut();
assert!(
!map.contains_key(filename),
"add failed: source \"{}\" already exists",
filename
);
let mut vect = self.vect.borrow_mut();
let new_id = Source(vect.len() as u32 + 1);
let v = RcStr::new(filename);
map.insert(v.clone(), new_id);
vect.push(Box::new(VirtualSourceFile {
id: new_id,
filename: v,
content: Rc::new(VirtualSourceContent(content.to_string(), OnceCell::new())),
}));
new_id
}
pub fn add_anonymous<S>(&self, content: S) -> Source
where
S: Into<String>,
{
let mut vect = self.vect.borrow_mut();
let new_id = Source(vect.len() as u32 + 1);
vect.push(Box::new(VirtualSourceFile {
id: new_id,
filename: RcStr::new("<anonymous>"),
content: Rc::new(VirtualSourceContent(content.into(), OnceCell::new())),
}));
new_id
}
}
pub fn get_source_manager() -> Rc<SourceManager> {
thread_local!(static MNGR: Rc<SourceManager> = {
Rc::new(SourceManager::new())
});
MNGR.with(|x| x.clone())
}
fn line_starts(iter: impl Iterator<Item = (usize, char)>) -> impl Iterator<Item = usize> {
Some(0)
.into_iter()
.chain(iter.filter(|(_i, c)| *c == '\n').map(|(i, _c)| i + 1))
}
struct VirtualSourceFile {
id: Source,
filename: RcStr,
content: Rc<VirtualSourceContent>,
}
struct VirtualSourceContent(pub String, OnceCell<Vec<usize>>);
impl SourceFile for VirtualSourceFile {
fn get_id(&self) -> Source {
self.id
}
fn get_path(&self) -> RcStr {
self.filename.clone()
}
fn get_content(&self) -> Rc<dyn SourceContent> {
self.content.clone()
}
}
impl SourceContent for VirtualSourceContent {
fn iter(&self) -> Box<CharIter> {
Box::new(self.0.char_indices())
}
fn iter_from(&self, offset: usize) -> Box<CharIter> {
Box::new(self.0[offset..].char_indices())
}
fn extract(&self, begin: usize, end: usize) -> String {
self.0[begin..end].to_string()
}
fn extract_iter(&self, begin: usize, end: usize) -> Box<CharIter> {
Box::new(self.0[begin..end].char_indices())
}
fn bytes(&self) -> &[u8] {
self.0.as_bytes()
}
fn lines(&self) -> &[usize] {
self.1.get_or_init(|| line_starts(self.iter()).collect())
}
}
struct DiskSourceFile {
id: Source,
filename: RcStr,
content: RefCell<Option<Rc<DiskSourceContent>>>,
}
#[derive(Debug)]
struct DiskSourceContent(pub Mmap, OnceCell<Vec<usize>>);
impl SourceFile for DiskSourceFile {
fn get_id(&self) -> Source {
self.id
}
fn get_path(&self) -> RcStr {
self.filename.clone()
}
fn get_content(&self) -> Rc<dyn SourceContent> {
let is_none = self.content.borrow().is_none();
if is_none {
let c = Rc::new(DiskSourceContent(
unsafe { Mmap::map(&File::open(&*self.filename).unwrap()).unwrap() },
OnceCell::new(),
));
*self.content.borrow_mut() = Some(c.clone());
c
} else {
self.content.borrow().clone().unwrap()
}
}
}
impl SourceContent for DiskSourceContent {
fn iter(&self) -> Box<CharIter> {
use std::str;
Box::new(str::from_utf8(&self.0[..]).unwrap().char_indices())
}
fn iter_from(&self, offset: usize) -> Box<CharIter> {
use std::str;
Box::new(str::from_utf8(&self.0[offset..]).unwrap().char_indices())
}
fn extract(&self, begin: usize, end: usize) -> String {
use std::str;
str::from_utf8(&self.0[begin..end]).unwrap().to_string()
}
fn extract_iter(&self, begin: usize, end: usize) -> Box<CharIter> {
use std::str;
Box::new(str::from_utf8(&self.0[begin..end]).unwrap().char_indices())
}
fn bytes(&self) -> &[u8] {
&self.0[..]
}
fn lines(&self) -> &[usize] {
self.1.get_or_init(|| line_starts(self.iter()).collect())
}
}
pub type CharIter<'a> = dyn DoubleEndedIterator<Item = (usize, char)> + 'a;
#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Location {
pub source: Source,
pub offset: usize,
}
impl Location {
pub fn new(source: Source, offset: usize) -> Location {
Location {
source: source,
offset: offset,
}
}
pub fn with_line_and_column(source: Source, line: usize, column: usize) -> Location {
let c = source.get_content();
let lines = c.lines();
if line > 0 && line <= lines.len() {
Location::new(source, lines[line - 1] + column - 1)
} else {
Location::new(source, 0)
}
}
pub fn iter<'a>(self, content: &'a Rc<dyn SourceContent>) -> Box<CharIter<'a>> {
content.iter_from(self.offset)
}
pub fn human(self) -> (usize, usize, usize) {
let c = self.source.get_content();
let lines = c.lines();
let index = lines.partition_point(|&x| x <= self.offset) - 1;
let line = index + 1;
let line_offset = lines[index];
assert!(line_offset <= self.offset);
let col = self.offset - line_offset + 1;
(line, col, line_offset)
}
pub fn human_line(self) -> usize {
self.human().0
}
pub fn human_column(self) -> usize {
self.human().1
}
pub fn human_line_offset(self) -> usize {
self.human().2
}
}
impl fmt::Debug for Location {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}:{}", self.source, self.offset)
}
}
impl From<Location> for Span {
fn from(l: Location) -> Span {
Span::new(l.source, l.offset, l.offset)
}
}
#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Span {
pub source: Source,
pub begin: usize,
pub end: usize,
}
impl Span {
pub fn new(source: Source, begin: usize, end: usize) -> Span {
Span {
source: source,
begin: begin,
end: end,
}
}
pub fn union<S: Into<Span>>(a: S, b: S) -> Span {
let sa = a.into();
let sb = b.into();
if sa.source != sb.source {
return sa;
}
Span {
source: sa.source,
begin: min(sa.begin, sb.begin),
end: max(sa.end, sb.end),
}
}
pub fn expand<S: Into<Span>>(&mut self, other: S) -> &mut Self {
let o = other.into();
if self.source == o.source {
self.begin = min(self.begin, o.begin);
self.end = max(self.end, o.end);
}
self
}
pub fn begin(&self) -> Location {
Location::new(self.source, self.begin)
}
pub fn end(&self) -> Location {
Location::new(self.source, self.end)
}
pub fn extract(&self) -> String {
self.source.get_content().extract(self.begin, self.end)
}
pub fn iter<'a>(self, content: &'a Rc<dyn SourceContent>) -> Box<CharIter<'a>> {
content.extract_iter(self.begin, self.end)
}
}
impl fmt::Debug for Span {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}:{}-{}", self.source, self.begin, self.end)
}
}
#[derive(PartialOrd, Ord, PartialEq, Eq)]
pub struct Spanned<T> {
pub value: T,
pub span: Span,
}
impl<T> Spanned<T> {
pub fn new(value: T, span: Span) -> Spanned<T> {
Spanned {
value: value,
span: span,
}
}
pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Spanned<U> {
Spanned::new(f(self.value), self.span)
}
pub fn map_into<U>(self) -> Spanned<U>
where
T: Into<U>,
{
Spanned::new(self.value.into(), self.span)
}
pub fn as_ref(&self) -> Spanned<&T> {
Spanned::new(&self.value, self.span)
}
}
impl<T> std::fmt::Debug for Spanned<T>
where
T: std::fmt::Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.value.fmt(f)
}
}
impl<T> std::fmt::Display for Spanned<T>
where
T: std::fmt::Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.value.fmt(f)
}
}
impl<T> Copy for Spanned<T> where T: Copy {}
impl<T> Clone for Spanned<T>
where
T: Clone,
{
fn clone(&self) -> Self {
Spanned {
value: self.value.clone(),
span: self.span,
}
}
}
impl<T> Hash for Spanned<T>
where
T: Hash,
{
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
self.value.hash(state)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = "invalid source")]
fn invalid_source_id() {
get_source_manager().with(Source(0), |_| ());
}
#[test]
#[should_panic(expected = "unknown source file")]
fn unknown_source_id() {
get_source_manager().with(Source(1), |_| ());
}
#[test]
fn inject_file() {
let sm = get_source_manager();
let id = sm.add("flabberghasted.txt", "Hello\nWorld\n");
let source = sm.open("flabberghasted.txt").expect("file should exist");
assert_eq!(source, id);
}
#[test]
fn inexistent_file() {
let sm = get_source_manager();
assert_eq!(sm.open("/this/path/points/nowhere"), None);
}
#[test]
fn chars() {
let sm = get_source_manager();
let source = sm.add("test.txt", "老虎.");
let content = source.get_content();
let elements: Vec<(usize, char)> = content.iter().collect();
assert_eq!(elements, vec![(0, '老'), (3, '虎'), (6, '.')]);
}
#[test]
fn file() {
use std::fs::File;
use std::io::Write;
use std::path::Path;
let path = Path::new("/tmp/moore-test");
let data = "Löwe 老虎 Léopard\n";
File::create(path)
.unwrap()
.write_all(data.as_bytes())
.unwrap();
let sm = get_source_manager();
let source = sm.open(path.to_str().unwrap()).expect("file should exist");
let content = source.get_content();
let expected: Vec<_> = data.char_indices().collect();
let actual: Vec<_> = content.iter().collect();
assert_eq!(expected, actual);
}
}