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
use std::collections::HashMap;
use std::result;
use std::io::{Read, Write};
use std::slice;
use std::str;
use error::{TemplateWriteError, TemplateMatchError, At, FilePosition};
use Result;
use ast;
use tokens;
#[derive(Copy, Clone, Debug)]
pub struct Options<'a> {
pub skip_lines: &'a str,
pub marker: &'a str,
pub var_start: &'a str,
pub var_end: &'a str,
}
#[derive(Debug, Clone)]
pub struct Spec {
ast: ast::Spec,
}
impl<'a> IntoIterator for &'a Spec {
type Item = Item<'a>;
type IntoIter = ItemIter<'a>;
fn into_iter(self) -> Self::IntoIter {
ItemIter {
inner: self.ast.items.iter()
}
}
}
impl Spec {
pub fn parse<'a>(options: Options<'a>, contents: &'a [u8]) -> Result<Spec> {
Ok(Spec {
ast: ast::Parser::new(
tokens::tokenize(options.into(), contents).peekable()
).parse_spec()?
})
}
pub fn iter<'r>(&'r self) -> ItemIter<'r> {
self.into_iter()
}
pub fn iter_item_values<'r, 'p>(&'r self, key: &'p str) -> ItemValuesByKeyIter<'r, 'p> {
ItemValuesByKeyIter {
inner: self.iter(),
key: key,
}
}
}
#[derive(Debug)]
pub struct Item<'s> {
pub params: &'s [ast::Param],
pub template: &'s [ast::Match],
}
impl<'s> Item<'s> {
pub fn get_param(&self, key: &str) -> Option<&'s str> {
for p in self.params.iter() {
if p.key == key {
match p.value {
Some(ref v) => return Some(&v[..]),
None => continue,
}
}
}
None
}
pub fn write_contents<O: Write>(&'s self, output: &mut O, params: &HashMap<&str, &str>)
-> result::Result<(), TemplateWriteError> {
for s in self.template {
match *s {
ast::Match::MultipleLines =>
return Err(TemplateWriteError::CanNotWriteMatchAnySymbols),
ast::Match::Var(ref key) if !params.contains_key(&key[..]) =>
return Err(TemplateWriteError::MissingParam(key.to_owned())),
_ => continue,
}
}
for s in self.template {
match *s {
ast::Match::NewLine => { output.write(b"\n")?; },
ast::Match::Text(ref v) => write!(output, "{}", v)?,
ast::Match::Var(ref v) => write!(output, "{}", params.get(&v[..]).unwrap())?,
_ => unreachable!(),
}
}
Ok(())
}
fn get_multiline_match_groups(&'s self) -> Vec<MultilineMatchState<'s>> {
let mut results = Vec::new();
let mut prev_group: Option<Vec<&ast::Match>> = None;
for state in self.template {
match *state {
ast::Match::MultipleLines => {
if let Some(group) = prev_group {
results.push(MultilineMatchState::Line(LineGroup::new(group)));
}
prev_group = None;
results.push(MultilineMatchState::MultipleLines);
}
ast::Match::NewLine => {
if let Some(group) = prev_group {
results.push(MultilineMatchState::Line(LineGroup::new(group)));
} else {
results.push(MultilineMatchState::Line(LineGroup::new(vec![])));
}
prev_group = Some(Vec::new());
},
ref other => {
if let Some(ref mut matches) = prev_group {
matches.push(other);
} else {
prev_group = Some(vec![other]);
}
}
}
}
if let Some(group) = prev_group {
results.push(MultilineMatchState::Line(LineGroup::new(group)));
}
results
}
pub fn match_contents<I: Read>(&'s self, input: &mut I, params: &HashMap<&str, &str>)
-> result::Result<(), At<TemplateMatchError>> {
let mut pos = FilePosition::new();
let mut eol_pos = FilePosition::new();
let mut contents = Vec::new();
input.read_to_end(&mut contents).map_err(|e| TemplateMatchError::from(e).at(pos, pos))?;
let mut skip_lines_state = false;
let mut had_new_line = true;
update_eol(&pos, &mut eol_pos, &contents);
let line_groups = self.get_multiline_match_groups();
for state in line_groups {
match state {
MultilineMatchState::MultipleLines => {
skip_lines_state = true;
},
MultilineMatchState::Line(line) => {
'text: loop {
let pos_byte = pos.byte;
match line.matches(pos, &contents, params) {
Ok((bytes, end_bytes)) => {
if bytes == 0 && !had_new_line {
return Err(TemplateMatchError::ExpectedEol.at(pos, pos));
}
pos.advance(bytes);
pos.next_line(end_bytes);
had_new_line = end_bytes > 0;
skip_lines_state = false;
update_eol(&pos, &mut eol_pos, &contents);
break 'text;
}
Err(err_match) => if skip_lines_state {
if pos_byte >= contents.len() {
match err_match {
LineGroupMatchErr::Text { pos: err_pos, text } =>
return Err(
TemplateMatchError::ExpectedTextFoundEof(text.to_string())
.at(err_pos, eol_pos)
),
_ => (),
};
}
pos.advance(eol_pos.byte - pos_byte);
pos.next_line(matches_newline(&eol_pos, &contents).expect("expected newline"));
update_eol(&pos, &mut eol_pos, &contents);
continue 'text;
} else {
match err_match {
LineGroupMatchErr::Text { pos, text } =>
return Err(TemplateMatchError::ExpectedText {
expected: text.to_string(),
found: String::from_utf8_lossy(&contents[pos.byte..eol_pos.byte]).into_owned(),
}.at(pos, eol_pos)),
LineGroupMatchErr::ParamNotFound { pos, key } =>
return Err(TemplateMatchError::MissingParam(key.into())
.at(pos, pos)),
LineGroupMatchErr::NewLineOrEof { pos } =>
return Err(TemplateMatchError::ExpectedEol
.at(pos, pos)),
}
}
}
}
},
}
}
if !skip_lines_state {
if pos.byte < contents.len() || (had_new_line && contents.len() > 0) {
return Err(TemplateMatchError::ExpectedEof.at(pos, pos));
}
}
Ok(())
}
}
#[derive(Debug)]
enum MultilineMatchState<'a> {
MultipleLines,
Line(LineGroup<'a>),
}
#[derive(Debug)]
enum LineGroupMatchErr<'a> {
Text {
pos: FilePosition,
text: &'a str,
},
ParamNotFound {
pos: FilePosition,
key: &'a str,
},
NewLineOrEof {
pos: FilePosition,
}
}
#[derive(Debug)]
struct LineGroup<'a> {
tokens: Vec<&'a ast::Match>,
}
impl<'a> LineGroup<'a> {
pub fn new<'r>(tokens: Vec<&'r ast::Match>) -> LineGroup<'r> {
LineGroup {
tokens: tokens
}
}
pub fn matches<'o, 'r>(&'a self, mut pos: FilePosition, content: &'o [u8], params: &HashMap<&str, &'r str>)
-> result::Result<(usize, usize), LineGroupMatchErr<'r>>
where 'a: 'r
{
let start_pos = pos;
for token in &self.tokens {
match **token {
ast::Match::Text(ref text) => if let Some(bytes) = matches_content(&pos, content, text.as_bytes()) {
pos.advance(bytes);
} else {
return Err(LineGroupMatchErr::Text { pos: pos, text: text });
},
ast::Match::Var(ref key) => match params.get(&key[..]) {
Some(ref text) => if let Some(bytes) = matches_content(&pos, content, text.as_bytes()) {
pos.advance(bytes);
} else {
return Err(LineGroupMatchErr::Text { pos: pos, text: text });
},
None => return Err(LineGroupMatchErr::ParamNotFound { pos: pos, key: &key[..] }),
},
ast::Match::MultipleLines => unreachable!(),
ast::Match::NewLine => unreachable!(),
}
}
match matches_newline(&pos, content) {
Some(newline_bytes) => Ok((pos.byte - start_pos.byte, newline_bytes)),
None => Err(LineGroupMatchErr::NewLineOrEof { pos: pos }),
}
}
}
fn matches_content(pos: &FilePosition, content: &[u8], to_match: &[u8]) -> Option<usize> {
if content[pos.byte..].starts_with(to_match) {
return Some(to_match.len());
}
None
}
fn matches_newline(pos: &FilePosition, content: &[u8]) -> Option<usize> {
let end = &content[pos.byte..];
if end.is_empty() {
return Some(0);
} else if end.starts_with(b"\n") {
return Some(1);
} else if end.starts_with(b"\r\n") {
return Some(2);
}
None
}
fn update_eol(pos: &FilePosition, eol_pos: &mut FilePosition, contents: &[u8]) {
let mut eol = pos.byte;
loop {
if eol >= contents.len() {
break;
}
let slice = &contents[eol..];
if slice.starts_with(b"\n") || slice.starts_with(b"\r\n") {
break;
}
eol += 1;
}
*eol_pos = pos.advanced(eol - pos.byte);
}
pub struct ItemIter<'a> {
inner: slice::Iter<'a, ast::Item>,
}
impl<'a> Iterator for ItemIter<'a> {
type Item = Item<'a>;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|i| Item { params: &i.params, template: &i.template })
}
}
pub struct ItemValuesByKeyIter<'a, 'p> {
inner: ItemIter<'a>,
key: &'p str,
}
impl<'a, 'p> Iterator for ItemValuesByKeyIter<'a, 'p> {
type Item = (Item<'a>, &'a str);
fn next(&mut self) -> Option<Self::Item> {
loop {
match self.inner.next() {
Some(item) => match item.get_param(self.key) {
Some(value) => return Some((item, value)),
None => continue,
},
None => return None,
}
}
}
}