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
use errors::Result;
use std::cell::{BorrowError, Ref, RefCell};
use std::path::Path;
use std::rc::Rc;
use std::result;
use {Diagnostics, Filesystem, Handle};
#[derive(Debug)]
pub enum ContextItem {
Diagnostics { diagnostics: Diagnostics },
}
#[derive(Clone)]
pub struct Context {
filesystem: Rc<Box<Filesystem>>,
items: Rc<RefCell<Vec<ContextItem>>>,
}
impl Context {
pub fn new(filesystem: Box<Filesystem>) -> Context {
Context {
filesystem: Rc::new(filesystem),
items: Rc::new(RefCell::new(vec![])),
}
}
pub fn with_items(self, items: Rc<RefCell<Vec<ContextItem>>>) -> Context {
Context { items, ..self }
}
pub fn map_filesystem<F>(self, map: F) -> Self
where
F: FnOnce(Rc<Box<Filesystem>>) -> Box<Filesystem>,
{
Context {
filesystem: Rc::new(map(self.filesystem)),
..self
}
}
pub fn filesystem(&self, root: Option<&Path>) -> Result<Box<Handle>> {
self.filesystem.open_root(root)
}
pub fn diagnostics(&self, diagnostics: Diagnostics) -> Result<()> {
self.items
.try_borrow_mut()
.map_err(|_| "no mutable access to context")?
.push(ContextItem::Diagnostics { diagnostics });
Ok(())
}
pub fn items(&self) -> result::Result<Ref<Vec<ContextItem>>, BorrowError> {
self.items.try_borrow()
}
pub fn has_diagnostics(&self) -> Result<bool> {
Ok(self.items
.try_borrow()
.map_err(|_| "immutable access to context")?
.iter()
.any(|item| match *item {
ContextItem::Diagnostics { ref diagnostics } => diagnostics.has_errors(),
}))
}
pub fn clear(&self) -> Result<()> {
self.items
.try_borrow_mut()
.map_err(|_| "no mutable access to context")?
.clear();
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use {CapturingFilesystem, Diagnostics, Source, Span};
#[test]
fn test_handle() {
let ctx = Context::new(Box::new(CapturingFilesystem::new()));
let mut diag = Diagnostics::new(Source::empty("test"));
diag.err(Span::empty(), "nope");
diag.err(Span::empty(), "previously reported here");
ctx.diagnostics(diag).expect("bad diagnostic");
assert_eq!(1, ctx.items().unwrap().len());
}
}