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
#![deny(missing_docs)]
#[macro_use]
extern crate nom;
#[macro_use]
extern crate log;
extern crate indextree;
extern crate mowl;
#[macro_use]
pub mod error;
pub mod parser;
pub mod example;
use std::{iter, fmt};
use std::collections::HashMap;
use log::LogLevel;
use indextree::{Arena, NodeId};
use nom::{IResult, generate_colors, prepare_errors, print_codes, print_offsets};
use prelude::*;
use parser::ParserBox;
pub mod prelude {
pub use super::Peel;
pub use error::{PeelResult, PeelError, ErrorType};
pub use parser::{Parser, ParserNode, ParserArena, ParserState};
}
pub struct Peel<R, V> {
pub arena: Arena<ParserBox<R, V>>,
pub root: Option<NodeId>,
}
impl<R, V> Peel<R, V> where V: fmt::Display {
pub fn new() -> Self {
Peel {
arena: Arena::new(),
root: None,
}
}
pub fn set_log_level(&mut self, level: LogLevel) {
if mowl::init_with_level(level).is_err() {
warn!("Logger already set.");
};
info!("Log level set to: {:?}", level);
}
pub fn new_parser<T>(&mut self, parser: T) -> NodeId
where T: Parser<Result = R, Variant = V> + Send + Sync + 'static
{
let new_node = self.arena.new_node(Box::new(parser));
if let None = self.root {
self.root = Some(new_node);
}
new_node
}
pub fn link(&mut self, left: NodeId, right: NodeId) {
left.append(right, &mut self.arena);
}
pub fn link_new_parser<T>(&mut self, left: NodeId, parser: T) -> NodeId
where T: Parser<Result = R, Variant = V> + Send + Sync + 'static
{
let new_parser = self.new_parser(parser);
left.append(new_parser, &mut self.arena);
new_parser
}
pub fn traverse(&self, input: &[u8], result: Vec<R>) -> PeelResult<Vec<R>> {
match self.root {
Some(node) => self.traverse_recursive(node, input, result),
None => bail!(ErrorType::NoTreeRoot, "No tree root found"),
}
}
pub fn traverse_recursive(&self, start_node: NodeId, input: &[u8], mut result: Vec<R>)
-> PeelResult<Vec<R>> {
for node_id in start_node.following_siblings(&self.arena) {
let ref node = self.arena[node_id];
let ref parser = node.data;
match parser.parse(input, Some(node), Some(&self.arena), Some(&result)) {
IResult::Done(input_left, (parser_result, state)) => {
debug!("{} parsing succeed, left input length: {}",
parser.variant(), input_left.len());
result.push(parser_result);
let next_node = match state {
ParserState::ContinueWithFirstChild => {
debug!("Continue traversal to first child of the parser");
node.first_child()
},
ParserState::ContinueWithNextSibling => {
debug!("Continue traversal to next sibling of the parser");
node.next_sibling()
},
ParserState::ContinueWithCurrent => {
debug!("Trying the current parser again");
Some(node_id)
},
ParserState::Stop => None,
};
if let Some(node) = next_node {
result = self.traverse_recursive(node, input_left, result)?;
}
break;
}
error @ _ => if log_enabled!(log::LogLevel::Trace) {
if Some(start_node) == self.root {
bail!(ErrorType::RootParserFailed, "No parser succeed at all");
}
debug!("Failed parser: {}", parser.variant());
self.display_error(input, error);
},
}
}
Ok(result)
}
fn display_children(&self, f: &mut fmt::Formatter, node: NodeId, mut level: usize)
-> fmt::Result {
level += 2;
for child in node.children(&self.arena) {
let indent = iter::repeat(' ').take(level).collect::<String>();
let ref parser = self.arena[child].data;
write!(f, "{}- {}: {:?}", indent, parser.variant(), child)?;
writeln!(f, " ({})", self.arena[child])?;
self.display_children(f, child, level)?;
}
Ok(())
}
pub fn display_error(&self, input: &[u8], res: IResult<&[u8], (R, ParserState)>) {
let mut h: HashMap<u32, &str> = HashMap::new();
let parsers = ["Custom", "Tag", "MapRes", "MapOpt", "Alt", "IsNot", "IsA", "SeparatedList",
"SeparatedNonEmptyList", "Many1", "Count", "TakeUntilAndConsume",
"TakeUntil", "TakeUntilEitherAndConsume", "TakeUntilEither", "LengthValue",
"TagClosure", "Alpha", "Digit", "AlphaNumeric", "Space", "MultiSpace",
"LengthValueFn", "Eof", "ExprOpt", "ExprRes", "CondReduce", "Switch",
"TagBits", "OneOf", "NoneOf", "Char", "CrLf", "RegexpMatch",
"RegexpMatches", "RegexpFind", "RegexpCapture", "RegexpCaptures",
"TakeWhile1", "Complete", "Fix", "Escaped", "EscapedTransform", "TagStr",
"IsNotStr", "IsAStr", "TakeWhile1Str", "NonEmpty", "ManyMN",
"TakeUntilAndConsumeStr", "HexDigit", "TakeUntilStr", "OctDigit", "Many0",
"Not", "Permutation", "ManyTill"];
for (i, literal) in parsers.iter().enumerate() {
h.insert(i as u32, literal);
}
if let Some(v) = prepare_errors(input, res) {
let colors = generate_colors(&v);
println!("Colors: {}", print_codes(colors, h));
println!("Dump: \n{}", print_offsets(input, 0, &v));
}
}
}
impl<K, V> fmt::Display for Peel<K, V> where V: fmt::Display {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.root {
Some(node) => {
write!(f, "- {}: {:?}", self.arena[node].data.variant(), node)?;
writeln!(f, " ({})", self.arena[node])?;
self.display_children(f, node, 0)
}
None => write!(f, "(no tree root available)"),
}
}
}