-
-
Notifications
You must be signed in to change notification settings - Fork 264
/
Copy pathparser.rs
1770 lines (1599 loc) · 56.8 KB
/
parser.rs
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// pest. The Elegant Parser
// Copyright (c) 2018 Dragoș Tiselice
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
//! Types and helpers for the pest's own grammar parser.
use std::char;
use std::iter::Peekable;
use pest::error::{Error, ErrorVariant};
use pest::iterators::{Pair, Pairs};
use pest::pratt_parser::{Assoc, Op, PrattParser};
use pest::{Parser, Position, Span};
use crate::ast::{Expr, Rule as AstRule, RuleType};
use crate::validator;
/// TODO: fix the generator to at least add explicit lifetimes
#[allow(missing_docs, unused_qualifications)]
mod grammar {
include!("grammar.rs");
}
pub use self::grammar::*;
/// A helper that will parse using the pest grammar
#[allow(clippy::perf)]
pub fn parse(rule: Rule, data: &str) -> Result<Pairs<'_, Rule>, Error<Rule>> {
PestParser::parse(rule, data)
}
/// The pest grammar rule
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParserRule<'i> {
/// The rule's name
pub name: String,
/// The rule's span
pub span: Span<'i>,
/// The rule's type
pub ty: RuleType,
/// The rule's parser node
pub node: ParserNode<'i>,
}
/// The pest grammar node
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParserNode<'i> {
/// The node's expression
pub expr: ParserExpr<'i>,
/// The node's span
pub span: Span<'i>,
}
impl<'i> ParserNode<'i> {
/// will remove nodes that do not match `f`
pub fn filter_map_top_down<F, T>(self, mut f: F) -> Vec<T>
where
F: FnMut(ParserNode<'i>) -> Option<T>,
{
pub fn filter_internal<'i, F, T>(node: ParserNode<'i>, f: &mut F, result: &mut Vec<T>)
where
F: FnMut(ParserNode<'i>) -> Option<T>,
{
if let Some(value) = f(node.clone()) {
result.push(value);
}
match node.expr {
// TODO: Use box syntax when it gets stabilized.
ParserExpr::PosPred(node) => {
filter_internal(*node, f, result);
}
ParserExpr::NegPred(node) => {
filter_internal(*node, f, result);
}
ParserExpr::Seq(lhs, rhs) => {
filter_internal(*lhs, f, result);
filter_internal(*rhs, f, result);
}
ParserExpr::Choice(lhs, rhs) => {
filter_internal(*lhs, f, result);
filter_internal(*rhs, f, result);
}
ParserExpr::Rep(node) => {
filter_internal(*node, f, result);
}
ParserExpr::RepOnce(node) => {
filter_internal(*node, f, result);
}
ParserExpr::RepExact(node, _) => {
filter_internal(*node, f, result);
}
ParserExpr::RepMin(node, _) => {
filter_internal(*node, f, result);
}
ParserExpr::RepMax(node, _) => {
filter_internal(*node, f, result);
}
ParserExpr::RepMinMax(node, ..) => {
filter_internal(*node, f, result);
}
ParserExpr::Opt(node) => {
filter_internal(*node, f, result);
}
ParserExpr::Push(node) => {
filter_internal(*node, f, result);
}
_ => (),
}
}
let mut result = vec![];
filter_internal(self, &mut f, &mut result);
result
}
}
/// All possible parser expressions
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ParserExpr<'i> {
/// Matches an exact string, e.g. `"a"`
Str(String),
/// Matches an exact string, case insensitively (ASCII only), e.g. `^"a"`
Insens(String),
/// Matches one character in the range, e.g. `'a'..'z'`
Range(String, String),
/// Matches the rule with the given name, e.g. `a`
Ident(String),
/// Matches a custom part of the stack, e.g. `PEEK[..]`
PeekSlice(i32, Option<i32>),
/// Positive lookahead; matches expression without making progress, e.g. `&e`
PosPred(Box<ParserNode<'i>>),
/// Negative lookahead; matches if expression doesn't match, without making progress, e.g. `!e`
NegPred(Box<ParserNode<'i>>),
/// Matches a sequence of two expressions, e.g. `e1 ~ e2`
Seq(Box<ParserNode<'i>>, Box<ParserNode<'i>>),
/// Matches either of two expressions, e.g. `e1 | e2`
Choice(Box<ParserNode<'i>>, Box<ParserNode<'i>>),
/// Optionally matches an expression, e.g. `e?`
Opt(Box<ParserNode<'i>>),
/// Matches an expression zero or more times, e.g. `e*`
Rep(Box<ParserNode<'i>>),
/// Matches an expression one or more times, e.g. `e+`
RepOnce(Box<ParserNode<'i>>),
/// Matches an expression an exact number of times, e.g. `e{n}`
RepExact(Box<ParserNode<'i>>, u32),
/// Matches an expression at least a number of times, e.g. `e{n,}`
RepMin(Box<ParserNode<'i>>, u32),
/// Matches an expression at most a number of times, e.g. `e{,n}`
RepMax(Box<ParserNode<'i>>, u32),
/// Matches an expression a number of times within a range, e.g. `e{m, n}`
RepMinMax(Box<ParserNode<'i>>, u32, u32),
/// Matches an expression and pushes it to the stack, e.g. `push(e)`
Push(Box<ParserNode<'i>>),
/// Matches an expression and assigns a label to it, e.g. #label = exp
NodeTag(Box<ParserNode<'i>>, String),
}
fn convert_rule(rule: ParserRule<'_>) -> AstRule {
let ParserRule { name, ty, node, .. } = rule;
let expr = convert_node(node);
AstRule { name, ty, expr }
}
fn convert_node(node: ParserNode<'_>) -> Expr {
match node.expr {
ParserExpr::Str(string) => Expr::Str(string),
ParserExpr::Insens(string) => Expr::Insens(string),
ParserExpr::Range(start, end) => Expr::Range(start, end),
ParserExpr::Ident(ident) => Expr::Ident(ident),
ParserExpr::PeekSlice(start, end) => Expr::PeekSlice(start, end),
ParserExpr::PosPred(node) => Expr::PosPred(Box::new(convert_node(*node))),
ParserExpr::NegPred(node) => Expr::NegPred(Box::new(convert_node(*node))),
ParserExpr::Seq(node1, node2) => Expr::Seq(
Box::new(convert_node(*node1)),
Box::new(convert_node(*node2)),
),
ParserExpr::Choice(node1, node2) => Expr::Choice(
Box::new(convert_node(*node1)),
Box::new(convert_node(*node2)),
),
ParserExpr::Opt(node) => Expr::Opt(Box::new(convert_node(*node))),
ParserExpr::Rep(node) => Expr::Rep(Box::new(convert_node(*node))),
ParserExpr::RepOnce(node) => Expr::RepOnce(Box::new(convert_node(*node))),
ParserExpr::RepExact(node, num) => Expr::RepExact(Box::new(convert_node(*node)), num),
ParserExpr::RepMin(node, max) => Expr::RepMin(Box::new(convert_node(*node)), max),
ParserExpr::RepMax(node, max) => Expr::RepMax(Box::new(convert_node(*node)), max),
ParserExpr::RepMinMax(node, min, max) => {
Expr::RepMinMax(Box::new(convert_node(*node)), min, max)
}
ParserExpr::Push(node) => Expr::Push(Box::new(convert_node(*node))),
ParserExpr::NodeTag(node, tag) => Expr::NodeTag(Box::new(convert_node(*node)), tag),
}
}
/// Converts a parser's result (`Pairs`) to an AST
pub fn consume_rules(pairs: Pairs<'_, Rule>) -> Result<Vec<AstRule>, Vec<Error<Rule>>> {
let rules = consume_rules_with_spans(pairs)?;
let errors = validator::validate_ast(&rules);
if errors.is_empty() {
Ok(rules.into_iter().map(convert_rule).collect())
} else {
Err(errors)
}
}
/// A helper function to rename verbose rules
/// for the sake of better error messages
#[inline]
pub fn rename_meta_rule(rule: &Rule) -> String {
match *rule {
Rule::grammar_rule => "rule".to_owned(),
Rule::_push => "PUSH".to_owned(),
Rule::assignment_operator => "`=`".to_owned(),
Rule::silent_modifier => "`_`".to_owned(),
Rule::atomic_modifier => "`@`".to_owned(),
Rule::compound_atomic_modifier => "`$`".to_owned(),
Rule::non_atomic_modifier => "`!`".to_owned(),
Rule::opening_brace => "`{`".to_owned(),
Rule::closing_brace => "`}`".to_owned(),
Rule::opening_brack => "`[`".to_owned(),
Rule::closing_brack => "`]`".to_owned(),
Rule::opening_paren => "`(`".to_owned(),
Rule::positive_predicate_operator => "`&`".to_owned(),
Rule::negative_predicate_operator => "`!`".to_owned(),
Rule::sequence_operator => "`&`".to_owned(),
Rule::choice_operator => "`|`".to_owned(),
Rule::optional_operator => "`?`".to_owned(),
Rule::repeat_operator => "`*`".to_owned(),
Rule::repeat_once_operator => "`+`".to_owned(),
Rule::comma => "`,`".to_owned(),
Rule::closing_paren => "`)`".to_owned(),
Rule::quote => "`\"`".to_owned(),
Rule::insensitive_string => "`^`".to_owned(),
Rule::range_operator => "`..`".to_owned(),
Rule::single_quote => "`'`".to_owned(),
Rule::grammar_doc => "//!".to_owned(),
Rule::line_doc => "///".to_owned(),
other_rule => format!("{:?}", other_rule),
}
}
fn consume_rules_with_spans(
pairs: Pairs<'_, Rule>,
) -> Result<Vec<ParserRule<'_>>, Vec<Error<Rule>>> {
let pratt = PrattParser::new()
.op(Op::infix(Rule::choice_operator, Assoc::Left))
.op(Op::infix(Rule::sequence_operator, Assoc::Left));
pairs
.filter(|pair| pair.as_rule() == Rule::grammar_rule)
.filter(|pair| {
// To ignore `grammar_rule > line_doc` pairs
let mut pairs = pair.clone().into_inner();
let pair = pairs.next().unwrap();
pair.as_rule() != Rule::line_doc
})
.map(|pair| {
let mut pairs = pair.into_inner().peekable();
let span = pairs.next().unwrap().as_span();
let name = span.as_str().to_owned();
pairs.next().unwrap(); // assignment_operator
let ty = if pairs.peek().unwrap().as_rule() != Rule::opening_brace {
match pairs.next().unwrap().as_rule() {
Rule::silent_modifier => RuleType::Silent,
Rule::atomic_modifier => RuleType::Atomic,
Rule::compound_atomic_modifier => RuleType::CompoundAtomic,
Rule::non_atomic_modifier => RuleType::NonAtomic,
_ => unreachable!(),
}
} else {
RuleType::Normal
};
pairs.next().unwrap(); // opening_brace
// skip initial infix operators
let mut inner_nodes = pairs.next().unwrap().into_inner().peekable();
if inner_nodes.peek().unwrap().as_rule() == Rule::choice_operator {
inner_nodes.next().unwrap();
}
let node = consume_expr(inner_nodes, &pratt)?;
Ok(ParserRule {
name,
span,
ty,
node,
})
})
.collect()
}
fn get_node_tag<'i>(
pairs: &mut Peekable<Pairs<'i, Rule>>,
) -> (Pair<'i, Rule>, Option<(String, Position<'i>)>) {
let pair_or_tag = pairs.next().unwrap();
if let Some(next_pair) = pairs.peek() {
if next_pair.as_rule() == Rule::assignment_operator {
pairs.next().unwrap();
let pair = pairs.next().unwrap();
(
pair,
Some((
pair_or_tag.as_str()[1..].to_string(),
pair_or_tag.as_span().start_pos(),
)),
)
} else {
(pair_or_tag, None)
}
} else {
(pair_or_tag, None)
}
}
fn consume_expr<'i>(
pairs: Peekable<Pairs<'i, Rule>>,
pratt: &PrattParser<Rule>,
) -> Result<ParserNode<'i>, Vec<Error<Rule>>> {
fn unaries<'i>(
mut pairs: Peekable<Pairs<'i, Rule>>,
pratt: &PrattParser<Rule>,
) -> Result<ParserNode<'i>, Vec<Error<Rule>>> {
let (pair, tag_start) = get_node_tag(&mut pairs);
let node = match pair.as_rule() {
Rule::opening_paren => {
let node = unaries(pairs, pratt)?;
let end = node.span.end_pos();
ParserNode {
expr: node.expr,
span: pair.as_span().start_pos().span(&end),
}
}
Rule::positive_predicate_operator => {
let node = unaries(pairs, pratt)?;
let end = node.span.end_pos();
ParserNode {
expr: ParserExpr::PosPred(Box::new(node)),
span: pair.as_span().start_pos().span(&end),
}
}
Rule::negative_predicate_operator => {
let node = unaries(pairs, pratt)?;
let end = node.span.end_pos();
ParserNode {
expr: ParserExpr::NegPred(Box::new(node)),
span: pair.as_span().start_pos().span(&end),
}
}
other_rule => {
let node = match other_rule {
Rule::expression => consume_expr(pair.into_inner().peekable(), pratt)?,
Rule::_push => {
let start = pair.clone().as_span().start_pos();
let mut pairs = pair.into_inner();
pairs.next().unwrap(); // opening_paren
let pair = pairs.next().unwrap();
let node = consume_expr(pair.into_inner().peekable(), pratt)?;
let end = node.span.end_pos();
ParserNode {
expr: ParserExpr::Push(Box::new(node)),
span: start.span(&end),
}
}
Rule::peek_slice => {
let mut pairs = pair.clone().into_inner();
pairs.next().unwrap(); // opening_brack
let pair_start = pairs.next().unwrap(); // .. or integer
let start: i32 = match pair_start.as_rule() {
Rule::range_operator => 0,
Rule::integer => {
pairs.next().unwrap(); // ..
pair_start.as_str().parse().unwrap()
}
_ => unreachable!("peek start"),
};
let pair_end = pairs.next().unwrap(); // integer or }
let end: Option<i32> = match pair_end.as_rule() {
Rule::closing_brack => None,
Rule::integer => {
pairs.next().unwrap(); // }
Some(pair_end.as_str().parse().unwrap())
}
_ => unreachable!("peek end"),
};
ParserNode {
expr: ParserExpr::PeekSlice(start, end),
span: pair.as_span(),
}
}
Rule::identifier => ParserNode {
expr: ParserExpr::Ident(pair.as_str().to_owned()),
span: pair.clone().as_span(),
},
Rule::string => {
let string = unescape(pair.as_str()).expect("incorrect string literal");
ParserNode {
expr: ParserExpr::Str(string[1..string.len() - 1].to_owned()),
span: pair.clone().as_span(),
}
}
Rule::insensitive_string => {
let string = unescape(pair.as_str()).expect("incorrect string literal");
ParserNode {
expr: ParserExpr::Insens(string[2..string.len() - 1].to_owned()),
span: pair.clone().as_span(),
}
}
Rule::range => {
let mut pairs = pair.into_inner();
let pair = pairs.next().unwrap();
let start = unescape(pair.as_str()).expect("incorrect char literal");
let start_pos = pair.clone().as_span().start_pos();
pairs.next();
let pair = pairs.next().unwrap();
let end = unescape(pair.as_str()).expect("incorrect char literal");
let end_pos = pair.clone().as_span().end_pos();
ParserNode {
expr: ParserExpr::Range(
start[1..start.len() - 1].to_owned(),
end[1..end.len() - 1].to_owned(),
),
span: start_pos.span(&end_pos),
}
}
x => unreachable!("other rule: {:?}", x),
};
pairs.fold(
Ok(node),
|node: Result<ParserNode<'i>, Vec<Error<Rule>>>, pair| {
let node = node?;
let node = match pair.as_rule() {
Rule::optional_operator => {
let start = node.span.start_pos();
ParserNode {
expr: ParserExpr::Opt(Box::new(node)),
span: start.span(&pair.as_span().end_pos()),
}
}
Rule::repeat_operator => {
let start = node.span.start_pos();
ParserNode {
expr: ParserExpr::Rep(Box::new(node)),
span: start.span(&pair.as_span().end_pos()),
}
}
Rule::repeat_once_operator => {
let start = node.span.start_pos();
ParserNode {
expr: ParserExpr::RepOnce(Box::new(node)),
span: start.span(&pair.as_span().end_pos()),
}
}
Rule::repeat_exact => {
let mut inner = pair.clone().into_inner();
inner.next().unwrap(); // opening_brace
let number = inner.next().unwrap();
let num = if let Ok(num) = number.as_str().parse::<u32>() {
num
} else {
return Err(vec![Error::new_from_span(
ErrorVariant::CustomError {
message: "number cannot overflow u32".to_owned(),
},
number.as_span(),
)]);
};
if num == 0 {
let error: Error<Rule> = Error::new_from_span(
ErrorVariant::CustomError {
message: "cannot repeat 0 times".to_owned(),
},
number.as_span(),
);
return Err(vec![error]);
}
let start = node.span.start_pos();
ParserNode {
expr: ParserExpr::RepExact(Box::new(node), num),
span: start.span(&pair.as_span().end_pos()),
}
}
Rule::repeat_min => {
let mut inner = pair.clone().into_inner();
inner.next().unwrap(); // opening_brace
let min_number = inner.next().unwrap();
let min = if let Ok(min) = min_number.as_str().parse::<u32>() {
min
} else {
return Err(vec![Error::new_from_span(
ErrorVariant::CustomError {
message: "number cannot overflow u32".to_owned(),
},
min_number.as_span(),
)]);
};
let start = node.span.start_pos();
ParserNode {
expr: ParserExpr::RepMin(Box::new(node), min),
span: start.span(&pair.as_span().end_pos()),
}
}
Rule::repeat_max => {
let mut inner = pair.clone().into_inner();
inner.next().unwrap(); // opening_brace
inner.next().unwrap(); // comma
let max_number = inner.next().unwrap();
let max = if let Ok(max) = max_number.as_str().parse::<u32>() {
max
} else {
return Err(vec![Error::new_from_span(
ErrorVariant::CustomError {
message: "number cannot overflow u32".to_owned(),
},
max_number.as_span(),
)]);
};
if max == 0 {
let error: Error<Rule> = Error::new_from_span(
ErrorVariant::CustomError {
message: "cannot repeat 0 times".to_owned(),
},
max_number.as_span(),
);
return Err(vec![error]);
}
let start = node.span.start_pos();
ParserNode {
expr: ParserExpr::RepMax(Box::new(node), max),
span: start.span(&pair.as_span().end_pos()),
}
}
Rule::repeat_min_max => {
let mut inner = pair.clone().into_inner();
inner.next().unwrap(); // opening_brace
let min_number = inner.next().unwrap();
let min = if let Ok(min) = min_number.as_str().parse::<u32>() {
min
} else {
return Err(vec![Error::new_from_span(
ErrorVariant::CustomError {
message: "number cannot overflow u32".to_owned(),
},
min_number.as_span(),
)]);
};
inner.next().unwrap(); // comma
let max_number = inner.next().unwrap();
let max = if let Ok(max) = max_number.as_str().parse::<u32>() {
max
} else {
return Err(vec![Error::new_from_span(
ErrorVariant::CustomError {
message: "number cannot overflow u32".to_owned(),
},
max_number.as_span(),
)]);
};
if max == 0 {
let error: Error<Rule> = Error::new_from_span(
ErrorVariant::CustomError {
message: "cannot repeat 0 times".to_owned(),
},
max_number.as_span(),
);
return Err(vec![error]);
}
let start = node.span.start_pos();
ParserNode {
expr: ParserExpr::RepMinMax(Box::new(node), min, max),
span: start.span(&pair.as_span().end_pos()),
}
}
Rule::closing_paren => {
let start = node.span.start_pos();
ParserNode {
expr: node.expr,
span: start.span(&pair.as_span().end_pos()),
}
}
rule => unreachable!("node: {:?}", rule),
};
Ok(node)
},
)?
}
};
if let Some((tag, start)) = tag_start {
let span = start.span(&node.span.end_pos());
Ok(ParserNode {
expr: ParserExpr::NodeTag(Box::new(node), tag),
span,
})
} else {
Ok(node)
}
}
let term = |pair: Pair<'i, Rule>| unaries(pair.into_inner().peekable(), pratt);
let infix = |lhs: Result<ParserNode<'i>, Vec<Error<Rule>>>,
op: Pair<'i, Rule>,
rhs: Result<ParserNode<'i>, Vec<Error<Rule>>>| match op.as_rule() {
Rule::sequence_operator => {
let lhs = lhs?;
let rhs = rhs?;
let start = lhs.span.start_pos();
let end = rhs.span.end_pos();
Ok(ParserNode {
expr: ParserExpr::Seq(Box::new(lhs), Box::new(rhs)),
span: start.span(&end),
})
}
Rule::choice_operator => {
let lhs = lhs?;
let rhs = rhs?;
let start = lhs.span.start_pos();
let end = rhs.span.end_pos();
Ok(ParserNode {
expr: ParserExpr::Choice(Box::new(lhs), Box::new(rhs)),
span: start.span(&end),
})
}
_ => unreachable!("infix"),
};
pratt.map_primary(term).map_infix(infix).parse(pairs)
}
fn unescape(string: &str) -> Option<String> {
let mut result = String::new();
let mut chars = string.chars();
loop {
match chars.next() {
Some('\\') => match chars.next()? {
'"' => result.push('"'),
'\\' => result.push('\\'),
'r' => result.push('\r'),
'n' => result.push('\n'),
't' => result.push('\t'),
'0' => result.push('\0'),
'\'' => result.push('\''),
'x' => {
let string: String = chars.clone().take(2).collect();
if string.len() != 2 {
return None;
}
for _ in 0..string.len() {
chars.next()?;
}
let value = u8::from_str_radix(&string, 16).ok()?;
result.push(char::from(value));
}
'u' => {
if chars.next()? != '{' {
return None;
}
let string: String = chars.clone().take_while(|c| *c != '}').collect();
if string.len() < 2 || 6 < string.len() {
return None;
}
for _ in 0..string.len() + 1 {
chars.next()?;
}
let value = u32::from_str_radix(&string, 16).ok()?;
result.push(char::from_u32(value)?);
}
_ => return None,
},
Some(c) => result.push(c),
None => return Some(result),
};
}
}
#[cfg(test)]
mod tests {
use std::convert::TryInto;
use super::super::unwrap_or_report;
use super::*;
#[test]
fn rules() {
parses_to! {
parser: PestParser,
input: "a = { b } c = { d }",
rule: Rule::grammar_rules,
tokens: [
grammar_rule(0, 9, [
identifier(0, 1),
assignment_operator(2, 3),
opening_brace(4, 5),
expression(6, 8, [
term(6, 8, [
identifier(6, 7)
])
]),
closing_brace(8, 9)
]),
grammar_rule(10, 19, [
identifier(10, 11),
assignment_operator(12, 13),
opening_brace(14, 15),
expression(16, 18, [
term(16, 18, [
identifier(16, 17)
])
]),
closing_brace(18, 19)
])
]
};
}
#[test]
fn rule() {
parses_to! {
parser: PestParser,
input: "a = ! { b ~ c }",
rule: Rule::grammar_rule,
tokens: [
grammar_rule(0, 15, [
identifier(0, 1),
assignment_operator(2, 3),
non_atomic_modifier(4, 5),
opening_brace(6, 7),
expression(8, 14, [
term(8, 10, [
identifier(8, 9)
]),
sequence_operator(10, 11),
term(12, 14, [
identifier(12, 13)
])
]),
closing_brace(14, 15)
])
]
};
}
#[test]
fn expression() {
parses_to! {
parser: PestParser,
input: "_a | 'a'..'b' ~ !^\"abc\" ~ (d | e)*?",
rule: Rule::expression,
tokens: [
expression(0, 35, [
term(0, 3, [
identifier(0, 2)
]),
choice_operator(3, 4),
term(5, 14, [
range(5, 13, [
character(5, 8, [
single_quote(5, 6),
inner_chr(6, 7),
single_quote(7, 8)
]),
range_operator(8, 10),
character(10, 13, [
single_quote(10, 11),
inner_chr(11, 12),
single_quote(12, 13)
])
])
]),
sequence_operator(14, 15),
term(16, 24, [
negative_predicate_operator(16, 17),
insensitive_string(17, 23, [
string(18, 23, [
quote(18, 19),
inner_str(19, 22),
quote(22, 23)
])
])
]),
sequence_operator(24, 25),
term(26, 35, [
opening_paren(26, 27),
expression(27, 32, [
term(27, 29, [
identifier(27, 28)
]),
choice_operator(29, 30),
term(31, 32, [
identifier(31, 32)
])
]),
closing_paren(32, 33),
repeat_operator(33, 34),
optional_operator(34, 35)
])
])
]
};
}
#[test]
fn repeat_exact() {
parses_to! {
parser: PestParser,
input: "{1}",
rule: Rule::repeat_exact,
tokens: [
repeat_exact(0, 3, [
opening_brace(0, 1),
number(1, 2),
closing_brace(2, 3)
])
]
};
}
#[test]
fn repeat_min() {
parses_to! {
parser: PestParser,
input: "{2,}",
rule: Rule::repeat_min,
tokens: [
repeat_min(0, 4, [
opening_brace(0,1),
number(1,2),
comma(2,3),
closing_brace(3,4)
])
]
}
}
#[test]
fn repeat_max() {
parses_to! {
parser: PestParser,
input: "{, 3}",
rule: Rule::repeat_max,
tokens: [
repeat_max(0, 5, [
opening_brace(0,1),
comma(1,2),
number(3,4),
closing_brace(4,5)
])
]
}
}
#[test]
fn repeat_min_max() {
parses_to! {
parser: PestParser,
input: "{1, 2}",
rule: Rule::repeat_min_max,
tokens: [
repeat_min_max(0, 6, [
opening_brace(0, 1),
number(1, 2),
comma(2, 3),
number(4, 5),
closing_brace(5, 6)
])
]
};
}
#[test]
fn push() {
parses_to! {
parser: PestParser,
input: "PUSH ( a )",
rule: Rule::_push,
tokens: [
_push(0, 10, [
opening_paren(5, 6),
expression(7, 9, [
term(7, 9, [
identifier(7, 8)
])
]),
closing_paren(9, 10)
])
]
};
}
#[test]
fn peek_slice_all() {
parses_to! {
parser: PestParser,
input: "PEEK[..]",
rule: Rule::peek_slice,
tokens: [
peek_slice(0, 8, [
opening_brack(4, 5),
range_operator(5, 7),
closing_brack(7, 8)
])
]
};
}
#[test]
fn peek_slice_start() {
parses_to! {
parser: PestParser,
input: "PEEK[1..]",
rule: Rule::peek_slice,
tokens: [
peek_slice(0, 9, [
opening_brack(4, 5),
integer(5, 6),
range_operator(6, 8),
closing_brack(8, 9)
])
]
};
}
#[test]
fn peek_slice_end() {
parses_to! {
parser: PestParser,
input: "PEEK[ ..-1]",
rule: Rule::peek_slice,
tokens: [
peek_slice(0, 11, [
opening_brack(4, 5),
range_operator(6, 8),
integer(8, 10),
closing_brack(10, 11)
])
]
};
}
#[test]
fn peek_slice_start_end() {
parses_to! {
parser: PestParser,