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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
use {Context, Contexts, Functions};
use serde_json::Value;
use eval::to_value;
use eval::Expr;
use node::{Node, NodeType};
use std::path::PathBuf;
use render::Render;
use error::Error;
use keyword::*;
use utils;
use Compiled;
use eval::ExecOptions;
pub struct Tree {
raw: String,
root: Option<PathBuf>,
extension: Option<String>,
}
impl Tree {
pub fn new(raw: String, root: Option<PathBuf>, extension: Option<String>) -> Tree {
Tree {
raw: raw,
root: root,
extension: extension,
}
}
fn parse_nodes(&self, raw: Option<&str>) -> Result<Vec<Node>, Error> {
let mut has_left_bracket = false;
let mut prev_char = ' ';
let mut prev_str = String::new();
let mut nodes = Vec::<Node>::new();
let mut is_escape = false;
for cur in if raw.is_some() {
raw.unwrap().chars()
} else {
self.raw.chars()
} {
match cur {
'\\' => {
is_escape = true;
}
'{' => {
if !is_escape && prev_char == '{' {
prev_str.pop();
if !has_left_bracket {
has_left_bracket = true;
let node = Node::new(parse_node_type(&prev_str)?);
if node.is_include() {
let mut absolute_path = utils::resolve(self.root.as_ref().unwrap(),
node.get_include_path());
if self.extension.is_some() {
absolute_path.set_extension(self.extension.as_ref().unwrap());
}
nodes.append(&mut self.parse_nodes(Some(&utils::read(absolute_path)?))?);
} else {
nodes.push(node);
}
prev_str.clear();
prev_str.push(cur);
continue;
} else {
return Err(Error::UnpairedBrackets);
}
}
}
'}' => {
if !is_escape && prev_char == '}' {
prev_str.pop();
if has_left_bracket {
has_left_bracket = false;
prev_str.push(cur);
let node = Node::new(parse_node_type(&prev_str)?);
if node.is_include() {
let mut absolute_path = utils::resolve(self.root.as_ref().unwrap(),
node.get_include_path());
if self.extension.is_some() {
absolute_path.set_extension(self.extension.as_ref().unwrap());
}
nodes.append(&mut self.parse_nodes(Some(&utils::read(absolute_path)?))?);
} else {
nodes.push(node);
}
prev_str.clear();
continue;
} else {
return Err(Error::UnpairedBrackets);
}
}
}
_ => {
is_escape = false;
}
}
prev_str.push(cur);
prev_char = cur;
}
if !prev_str.is_empty() {
nodes.push(Node::new(parse_node_type(&prev_str)?));
}
Ok(nodes)
}
pub fn parse_tree(&self, nodes: Vec<Node>) -> Result<Node, Error> {
let mut parsing_nodes = Vec::new();
parsing_nodes.push(Node::new(NodeType::Root(Root::new())));
for node in nodes {
match node.node_type {
NodeType::Raw(_) |
NodeType::Set(_) |
NodeType::Expression(_) => {
parsing_nodes.last_mut().unwrap().add_child(node);
}
NodeType::If(_) | NodeType::For(_) => {
parsing_nodes.push(node);
}
NodeType::Else(_) |
NodeType::ElseIf(_) => {
parsing_nodes.last_mut().unwrap().closed = true;
parsing_nodes.push(node);
}
NodeType::End => {
close_prev(&mut parsing_nodes)?;
}
_ => return Err(Error::UnexpectedNode),
}
}
Ok(parsing_nodes.pop().unwrap())
}
pub fn compile(self) -> Result<Compiled, Error> {
let node = Box::new(self.parse_tree(self.parse_nodes(None)?)?);
Ok(Box::new(move |mut contexts, functions| {
return render(&mut contexts, functions, &node);
fn render(contexts: &mut Contexts,
functions: &Functions,
node: &Box<Node>)
-> Result<String, Error> {
let mut result = String::new();
match node.node_type {
NodeType::Raw(ref raw) => {
result += raw;
}
NodeType::Expression(ref expr) => {
result += &render_expr(contexts, functions, expr)?;
}
NodeType::For(ref _for) => {
result += &exec_for(contexts, functions, _for)?;
}
NodeType::If(ref _if) => {
result += &exec_if(contexts, functions, _if)?;
}
NodeType::Else(ref _else) => {
result += &render_nodes(contexts, functions, &_else.nodes)?;
}
NodeType::ElseIf(ref else_if) => {
result += &render_nodes(contexts, functions, &else_if.nodes)?;
}
NodeType::Root(ref root) => {
result += &render_nodes(contexts, functions, &root.nodes)?;
}
NodeType::Set(ref set) => {
set_value(contexts, functions, set)?;
}
_ => return Err(Error::CanNotRender),
}
Ok(result)
}
fn set_value(contexts: &mut Contexts,
functions: &Functions,
set: &Set)
-> Result<(), Error> {
let value = ExecOptions::new(&set.expr).contexts(contexts)
.functions(functions)
.exec()?;
contexts.last_mut().unwrap().insert(set.name.clone(), value);
Ok(())
}
fn render_nodes(contexts: &mut Contexts,
functions: &Functions,
nodes: &[Box<Node>])
-> Result<String, Error> {
let mut result = String::new();
for child in nodes {
result += &render(contexts, functions, child)?;
}
Ok(result)
}
fn render_expr(contexts: &mut Contexts,
functions: &Functions,
expr: &Expr)
-> Result<String, Error> {
Ok(ExecOptions::new(expr)
.contexts(contexts)
.functions(functions)
.exec()?
.render())
}
fn exec_if(contexts: &mut Contexts,
functions: &Functions,
_if: &If)
-> Result<String, Error> {
let mut result = String::new();
let value = ExecOptions::new(&_if.expr).contexts(contexts)
.functions(functions)
.exec()?;
let boolean = match value {
Value::Bool(_) | Value::Null => {
if let Value::Bool(boolean) = value {
boolean
} else {
false
}
}
_ => return Err(Error::ExpectedBoolean),
};
if boolean {
result += &render_nodes(contexts, functions, &_if.nodes)?;
} else {
let mut end = false;
for node in &_if._else_ifs {
let value = ExecOptions::new(node.get_expr()).contexts(contexts)
.functions(functions)
.exec()?;
match value {
Value::Bool(boolean) => {
if boolean {
result += &render(contexts, functions, node)?;
end = true;
break;
}
}
Value::Null => (),
_ => return Err(Error::ExpectedBoolean),
}
}
if !end && _if._else.is_some() {
result += &render(contexts, functions, _if._else.as_ref().unwrap())?
}
}
Ok(result)
}
fn exec_for(contexts: &mut Contexts,
functions: &Functions,
_for: &For)
-> Result<String, Error> {
let mut result = String::new();
let value = ExecOptions::new(&_for.expr).contexts(contexts)
.functions(functions)
.exec()?;
match value {
Value::Array(ref array) => {
for (index, value) in array.iter().enumerate() {
{
let mut context = Context::new();
context.insert(_for.value.clone(), value.clone());
if _for.index.is_some() {
context.insert(_for.index.clone().unwrap(), to_value(index));
}
contexts.push(context);
}
for child in &_for.nodes {
result += &render(contexts, functions, child)?
}
{
contexts.pop();
}
}
}
Value::Object(ref object) => {
for (key, value) in object {
{
let mut context = Context::new();
context.insert(_for.value.clone(), value.clone());
if _for.index.is_some() {
context.insert(_for.index.clone().unwrap(), to_value(key));
}
contexts.push(context);
}
for child in &_for.nodes {
result += &render(contexts, functions, child)?
}
{
contexts.pop();
}
}
}
Value::Null => (),
_ => {
return Err(Error::ExpectArrayOrObject);
}
}
Ok(result)
}
}))
}
}
fn parse_node_type(content: &str) -> Result<NodeType, Error> {
let mut raw = content.to_string();
let mut is_dynamic_content = false;
if raw.starts_with('{') && raw.ends_with('}') {
is_dynamic_content = true;
raw.remove(0);
raw.pop();
raw = raw.trim().to_string();
}
let supported_keywords = vec!["if", "elseif", "for", "include", "set"];
let mut found_keyword = false;
let mut found_not_whitespace = false;
let mut found_alpha = false;
let mut found_second_whitespace = false;
let mut found_maybe_keyword = false;
let mut prev_chars = String::new();
let mut keyword = String::new();
if is_dynamic_content {
for keyword in &supported_keywords {
if raw.as_str() == *keyword {
return Ok(NodeType::End);
}
}
if raw.as_str() == "else" {
return Ok(NodeType::Else(Else::new()));
}
for (index, cur) in raw.chars().collect::<Vec<char>>().iter().enumerate() {
if found_keyword {
match &keyword[..] {
"if" => {
let (_, expression_str) = raw.split_at(index);
return Ok(NodeType::If(If::new(expression_str.trim()
.to_owned())));
}
"elseif" => {
let (_, expression_str) = raw.split_at(index);
return Ok(NodeType::ElseIf(ElseIf::new(expression_str.trim().to_owned())));
}
"include" => {
let (_, path_str) = raw.split_at(index);
let path = path_str.trim().to_owned();
return Ok(NodeType::Include(Include::new(path)));
}
"set" => {
let (_, setter) = raw.split_at(index);
let segments = setter.trim().split('=').collect::<Vec<_>>();
if segments.len() != 2 {
return Err(Error::InvalidSetBlock);
}
return Ok(NodeType::Set(Set::new(segments[0].to_owned(),
segments[1].to_owned())));
}
"for" => {
let (_, for_expression_str) = raw.split_at(index);
return parse_for_block(for_expression_str.trim().to_owned());
}
_ => {
panic!("keyword is not supported");
}
}
}
match *cur {
' ' => {
if found_maybe_keyword {
found_keyword = true;
keyword = prev_chars.clone();
continue;
}
if found_not_whitespace {
found_second_whitespace = true;
}
}
'(' => {
if found_not_whitespace && found_alpha {
return Ok(NodeType::Expression(Expr::new(raw.clone()).compile().unwrap()));
}
}
_ => {
if found_second_whitespace {
return Ok(NodeType::Expression(Expr::new(raw.clone()).compile().unwrap()));
}
if cur.is_alphabetic() {
found_alpha = true;
}
found_not_whitespace = true;
}
}
if found_not_whitespace {
prev_chars.push(*cur);
}
if supported_keywords.contains(&&prev_chars[..]) {
found_maybe_keyword = true;
}
}
Ok(NodeType::Expression(Expr::new(raw).compile().unwrap()))
} else {
Ok(NodeType::Raw(raw))
}
}
fn parse_for_block(for_expression: String) -> Result<NodeType, Error> {
let mut prev_chars = String::new();
let mut is_whitespace = false;
let mut is_i = false;
let mut is_n = false;
let mut value_name = String::new();
let mut index_name = String::new();
let mut has_index = false;
let mut index_start = false;
let mut expression_start = false;
for (index, cur) in for_expression.chars()
.collect::<Vec<char>>()
.iter()
.enumerate() {
match *cur {
',' => {
value_name = prev_chars.trim().to_owned();
prev_chars.clear();
has_index = true;
continue;
}
' ' => {
if index_start {
index_name = prev_chars.trim().to_owned();
index_start = false;
has_index = false;
expression_start = true;
is_whitespace = true;
continue;
}
if is_i && is_n && expression_start {
let (_, expression) = for_expression.split_at(index);
return Ok(NodeType::For(For::new(expression.trim()
.to_owned(),
value_name,
Some(index_name))));
}
if is_i && is_n {
value_name = prev_chars.trim().to_owned();
let (_, expression) = for_expression.split_at(index);
return Ok(NodeType::For(For::new(expression.trim()
.to_owned(),
value_name,
None)));
}
is_whitespace = true;
}
'i' => {
if has_index {
index_start = true;
} else if is_whitespace {
is_i = true;
continue;
} else {
is_i = false;
is_whitespace = false;
}
}
'n' => {
if has_index {
index_start = true;
} else if is_i {
is_n = true;
continue;
} else {
is_n = false;
is_whitespace = false;
}
}
_ => {
if has_index {
index_start = true;
}
is_i = false;
is_n = false;
is_whitespace = false;
}
}
prev_chars.push(*cur);
}
Err(Error::InvalidForBlock)
}
fn close_prev(parsing_nodes: &mut Vec<Node>) -> Result<(), Error> {
loop {
let mut current = parsing_nodes.pop().unwrap();
current.closed = true;
match current.node_type {
NodeType::Else(_) => {
let mut else_ifs = Vec::new();
loop {
if parsing_nodes.is_empty() {
return Err(Error::ExpectIf);
}
let mut prev = parsing_nodes.pop().unwrap();
if prev.is_if() {
prev.get_if_mut().set_else(current);
prev.get_if_mut().append_else_ifs(&mut else_ifs);
prev.closed = true;
parsing_nodes.push(prev);
break;
} else if prev.is_else_if() {
else_ifs.push(Box::new(prev));
} else {
return Err(Error::ExpectIf);
}
}
}
NodeType::ElseIf(_) => {
let mut else_ifs = vec![Box::new(current)];
loop {
if parsing_nodes.is_empty() {
return Err(Error::ExpectIf);
}
let mut prev = parsing_nodes.pop().unwrap();
if prev.is_if() {
prev.get_if_mut().append_else_ifs(&mut else_ifs);
prev.closed = true;
parsing_nodes.push(prev);
break;
} else if prev.is_else_if() {
else_ifs.push(Box::new(prev));
} else {
return Err(Error::ExpectIf);
}
}
}
NodeType::If(_) | NodeType::For(_) => {
let mut prev = parsing_nodes.pop().unwrap();
if prev.closed {
break;
} else {
prev.add_child(current);
parsing_nodes.push(prev);
break;
}
}
_ => return Err(Error::CanNotClose),
}
}
Ok(())
}