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
use std::{
cell::RefCell,
collections::hash_map::HashMap,
io,
path::{Path, PathBuf},
};
use crate::{node::Node, source::Source};
use super::context::Context;
pub struct FileCacheEntry {
pub occured: usize,
}
impl FileCacheEntry {
pub fn new() -> Self {
Self { occured: 1 }
}
}
pub type FileCache = HashMap<PathBuf, FileCacheEntry>;
pub type Flags = HashMap<String, bool>;
pub struct Parser {
source: Box<dyn Source>,
flags: Flags,
file_cache: RefCell<FileCache>,
}
pub struct ParserBuilder {
sources: Vec<Box<dyn Source>>,
flags: Flags,
}
impl Default for ParserBuilder {
fn default() -> Self {
Self {
sources: Vec::new(),
flags: Flags::new(),
}
}
}
impl ParserBuilder {
pub fn add_source<S: Source + 'static>(mut self, source: S) -> Self {
self.sources.push(Box::new(source));
self
}
pub fn add_flag(mut self, name: String, value: bool) -> Self {
self.flags.insert(name, value);
self
}
pub fn build(self) -> Parser {
Parser::new(Box::new(self.sources), self.flags)
}
}
impl Parser {
pub fn new(source: Box<dyn Source>, flags: Flags) -> Self {
Self {
source,
flags,
file_cache: RefCell::new(HashMap::new()),
}
}
pub fn builder() -> ParserBuilder {
ParserBuilder::default()
}
pub fn parse(&self, main: &Path) -> io::Result<Node> {
let mut file_cache = self.file_cache.borrow_mut();
let mut context = Context::new(self.source.as_ref(), &self.flags, &mut *file_cache);
context.build_tree(main, None).and_then(|root| {
root.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("Root file '{:?}' not found", main),
)
})
})
}
}