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
use std::collections::HashMap;
use std::sync::Arc;
use crate::{Doc, Error, Node};
pub struct RenderContext {
ichar: char,
iwidth: usize,
dict: HashMap<String, Arc<Doc>>
}
impl RenderContext {
pub fn new() -> Self {
RenderContext {
ichar: ' ',
iwidth: 2,
dict: HashMap::new()
}
}
pub fn doc<N: ToString>(&mut self, id: N, doc: Arc<Doc>) {
self.dict.insert(id.to_string(), Arc::clone(&doc));
}
pub fn render(&self, name: &str) -> Result<String, Error> {
struct IterNode<'a> {
lst: &'a Vec<Node>,
idx: usize
}
let mut iterstack = Vec::new();
let mut out = String::new();
let mut indent: usize = 0;
let istr = self.ichar.to_string().repeat(self.iwidth);
if let Some(dict) = self.dict.get(name) {
iterstack.push(IterNode {
lst: &dict.nodes,
idx: 0
});
} else {
return Err(Error::BadRef(format!("Missing root document '{}'", name)));
}
'outer: while !iterstack.is_empty() {
let mut it = iterstack.pop().unwrap();
while it.idx < it.lst.len() {
match &it.lst[it.idx] {
Node::BeginScope(s) => {
let is = istr.repeat(indent);
out.push_str(&is);
out.push_str(&s);
out.push('\n');
indent += 1;
}
Node::EndScope(s) => {
indent -= 1;
if let Some(s) = s {
let is = istr.repeat(indent);
out.push_str(&is);
out.push_str(&s);
out.push('\n');
}
}
Node::Line(s) => {
let is = istr.repeat(indent);
out.push_str(&is);
out.push_str(&s);
out.push('\n');
}
Node::OptRef(name) => {
if let Some(dict) = self.dict.get(name) {
iterstack.push(IterNode {
lst: it.lst,
idx: it.idx + 1
});
iterstack.push(IterNode {
lst: &dict.nodes,
idx: 0
});
continue 'outer;
}
}
Node::ReqRef(name) => {
if let Some(dict) = self.dict.get(name) {
iterstack.push(IterNode {
lst: it.lst,
idx: it.idx + 1
});
iterstack.push(IterNode {
lst: &dict.nodes,
idx: 0
});
continue 'outer;
} else {
return Err(Error::BadRef(format!(
"Missing required document '{}'",
name
)));
}
}
}
it.idx += 1;
}
}
Ok(out)
}
}