-
-
Notifications
You must be signed in to change notification settings - Fork 255
/
validator.rs
1790 lines (1603 loc) · 55.7 KB
/
validator.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.
//! Helpers for validating pest grammars that could help with debugging
//! and provide a more user-friendly error message.
use once_cell::sync::Lazy;
use std::collections::{HashMap, HashSet};
use pest::error::{Error, ErrorVariant, InputLocation};
use pest::iterators::Pairs;
use pest::unicode::unicode_property_names;
use pest::Span;
use crate::parser::{ParserExpr, ParserNode, ParserRule, Rule};
static RUST_KEYWORDS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
[
"abstract", "alignof", "as", "become", "box", "break", "const", "continue", "crate", "do",
"else", "enum", "extern", "false", "final", "fn", "for", "if", "impl", "in", "let", "loop",
"macro", "match", "mod", "move", "mut", "offsetof", "override", "priv", "proc", "pure",
"pub", "ref", "return", "Self", "self", "sizeof", "static", "struct", "super", "trait",
"true", "type", "typeof", "unsafe", "unsized", "use", "virtual", "where", "while", "yield",
]
.iter()
.cloned()
.collect()
});
static PEST_KEYWORDS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
[
"_", "ANY", "DROP", "EOI", "PEEK", "PEEK_ALL", "POP", "POP_ALL", "PUSH", "SOI",
]
.iter()
.cloned()
.collect()
});
static BUILTINS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
[
"ANY",
"DROP",
"EOI",
"PEEK",
"PEEK_ALL",
"POP",
"POP_ALL",
"SOI",
"ASCII_DIGIT",
"ASCII_NONZERO_DIGIT",
"ASCII_BIN_DIGIT",
"ASCII_OCT_DIGIT",
"ASCII_HEX_DIGIT",
"ASCII_ALPHA_LOWER",
"ASCII_ALPHA_UPPER",
"ASCII_ALPHA",
"ASCII_ALPHANUMERIC",
"ASCII",
"NEWLINE",
]
.iter()
.cloned()
.chain(unicode_property_names())
.collect::<HashSet<&str>>()
});
/// It checks the parsed grammar for common mistakes:
/// - using Pest keywords
/// - duplicate rules
/// - undefined rules
///
/// It returns a `Result` with a `Vec` of `Error`s if any of the above is found.
/// If no errors are found, it returns the vector of names of used builtin rules.
pub fn validate_pairs(pairs: Pairs<'_, Rule>) -> Result<Vec<&str>, Vec<Error<Rule>>> {
let definitions: Vec<_> = pairs
.clone()
.filter(|pair| pair.as_rule() == Rule::grammar_rule)
.map(|pair| pair.into_inner().next().unwrap())
.filter(|pair| pair.as_rule() != Rule::line_doc)
.map(|pair| pair.as_span())
.collect();
let called_rules: Vec<_> = pairs
.clone()
.filter(|pair| pair.as_rule() == Rule::grammar_rule)
.flat_map(|pair| {
pair.into_inner()
.flatten()
.skip(1)
.filter(|pair| pair.as_rule() == Rule::identifier)
.map(|pair| pair.as_span())
})
.collect();
let mut errors = vec![];
errors.extend(validate_pest_keywords(&definitions));
errors.extend(validate_already_defined(&definitions));
errors.extend(validate_undefined(&definitions, &called_rules));
if !errors.is_empty() {
return Err(errors);
}
let definitions: HashSet<_> = definitions.iter().map(|span| span.as_str()).collect();
let called_rules: HashSet<_> = called_rules.iter().map(|span| span.as_str()).collect();
let defaults = called_rules.difference(&definitions);
Ok(defaults.cloned().collect())
}
/// Validates that the given `definitions` do not contain any Rust keywords.
#[allow(clippy::ptr_arg)]
#[deprecated = "Rust keywords are no longer restricted from the pest grammar"]
pub fn validate_rust_keywords(definitions: &Vec<Span<'_>>) -> Vec<Error<Rule>> {
let mut errors = vec![];
for definition in definitions {
let name = definition.as_str();
if RUST_KEYWORDS.contains(name) {
errors.push(Error::new_from_span(
ErrorVariant::CustomError {
message: format!("{} is a rust keyword", name),
},
*definition,
))
}
}
errors
}
/// Validates that the given `definitions` do not contain any Pest keywords.
#[allow(clippy::ptr_arg)]
pub fn validate_pest_keywords(definitions: &Vec<Span<'_>>) -> Vec<Error<Rule>> {
let mut errors = vec![];
for definition in definitions {
let name = definition.as_str();
if PEST_KEYWORDS.contains(name) {
errors.push(Error::new_from_span(
ErrorVariant::CustomError {
message: format!("{} is a pest keyword", name),
},
*definition,
))
}
}
errors
}
/// Validates that the given `definitions` do not contain any duplicate rules.
#[allow(clippy::ptr_arg)]
pub fn validate_already_defined(definitions: &Vec<Span<'_>>) -> Vec<Error<Rule>> {
let mut errors = vec![];
let mut defined = HashSet::new();
for definition in definitions {
let name = definition.as_str();
if defined.contains(&name) {
errors.push(Error::new_from_span(
ErrorVariant::CustomError {
message: format!("rule {} already defined", name),
},
*definition,
))
} else {
defined.insert(name);
}
}
errors
}
/// Validates that the given `definitions` do not contain any undefined rules.
#[allow(clippy::ptr_arg)]
pub fn validate_undefined<'i>(
definitions: &Vec<Span<'i>>,
called_rules: &Vec<Span<'i>>,
) -> Vec<Error<Rule>> {
let mut errors = vec![];
let definitions: HashSet<_> = definitions.iter().map(|span| span.as_str()).collect();
for rule in called_rules {
let name = rule.as_str();
if !definitions.contains(name) && !BUILTINS.contains(name) {
errors.push(Error::new_from_span(
ErrorVariant::CustomError {
message: format!("rule {} is undefined", name),
},
*rule,
))
}
}
errors
}
/// Validates the abstract syntax tree for common mistakes:
/// - infinite repetitions
/// - choices that cannot be reached
/// - left recursion
#[allow(clippy::ptr_arg)]
pub fn validate_ast<'a, 'i: 'a>(rules: &'a Vec<ParserRule<'i>>) -> Vec<Error<Rule>> {
let mut errors = vec![];
// WARNING: validate_{repetition,choice,whitespace_comment}
// use is_non_failing and is_non_progressing breaking assumptions:
// - for every `ParserExpr::RepMinMax(inner,min,max)`,
// `min<=max` was not checked
// - left recursion was not checked
// - Every expression might not be checked
errors.extend(validate_repetition(rules));
errors.extend(validate_choices(rules));
errors.extend(validate_whitespace_comment(rules));
errors.extend(validate_left_recursion(rules));
errors.sort_by_key(|error| match error.location {
InputLocation::Span(span) => span,
_ => unreachable!(),
});
errors
}
/// Checks if `expr` is non-progressing, that is the expression does not
/// consume any input or any stack. This includes expressions matching the empty input,
/// `SOI` and ̀ `EOI`, predicates and repetitions.
///
/// # Example
///
/// ```pest
/// not_progressing_1 = { "" }
/// not_progressing_2 = { "a"? }
/// not_progressing_3 = { !"a" }
/// ```
///
/// # Assumptions
/// - In `ParserExpr::RepMinMax(inner,min,max)`, `min<=max`
/// - All rules identiers have a matching definition
/// - There is no left-recursion (if only this one is broken returns false)
/// - Every expression is being checked
fn is_non_progressing<'i>(
expr: &ParserExpr<'i>,
rules: &HashMap<String, &ParserNode<'i>>,
trace: &mut Vec<String>,
) -> bool {
match *expr {
ParserExpr::Str(ref string) | ParserExpr::Insens(ref string) => string.is_empty(),
ParserExpr::Ident(ref ident) => {
if ident == "SOI" || ident == "EOI" {
return true;
}
if !trace.contains(ident) {
if let Some(node) = rules.get(ident) {
trace.push(ident.clone());
let result = is_non_progressing(&node.expr, rules, trace);
trace.pop().unwrap();
return result;
}
// else
// the ident is
// - "POP","PEEK" => false
// the slice being checked is not non_progressing since every
// PUSH is being checked (assumption 4) and the expr
// of a PUSH has to be non_progressing.
// - "POPALL", "PEEKALL" => false
// same as "POP", "PEEK" unless the following:
// BUG: if the stack is empty they are non_progressing
// - "DROP" => false doesn't consume the input but consumes the stack,
// - "ANY", "ASCII_*", UNICODE categories, "NEWLINE" => false
// - referring to another rule that is undefined (breaks assumption)
}
// else referring to another rule that was already seen.
// this happens only if there is a left-recursion
// that is only if an assumption is broken,
// WARNING: we can choose to return false, but that might
// cause bugs into the left_recursion check
false
}
ParserExpr::Seq(ref lhs, ref rhs) => {
is_non_progressing(&lhs.expr, rules, trace)
&& is_non_progressing(&rhs.expr, rules, trace)
}
ParserExpr::Choice(ref lhs, ref rhs) => {
is_non_progressing(&lhs.expr, rules, trace)
|| is_non_progressing(&rhs.expr, rules, trace)
}
// WARNING: the predicate indeed won't make progress on input but it
// might progress on the stack
// ex: @{ PUSH(ANY) ~ (&(DROP))* ~ ANY }, input="AA"
// Notice that this is ex not working as of now, the debugger seems
// to run into an infinite loop on it
ParserExpr::PosPred(_) | ParserExpr::NegPred(_) => true,
ParserExpr::Rep(_) | ParserExpr::Opt(_) | ParserExpr::RepMax(_, _) => true,
// it either always fail (failing is progressing)
// or always match at least a character
ParserExpr::Range(_, _) => false,
ParserExpr::PeekSlice(_, _) => {
// the slice being checked is not non_progressing since every
// PUSH is being checked (assumption 4) and the expr
// of a PUSH has to be non_progressing.
// BUG: if the slice is of size 0, or the stack is not large
// enough it might be non-progressing
false
}
ParserExpr::RepExact(ref inner, min)
| ParserExpr::RepMin(ref inner, min)
| ParserExpr::RepMinMax(ref inner, min, _) => {
min == 0 || is_non_progressing(&inner.expr, rules, trace)
}
ParserExpr::Push(ref inner) => is_non_progressing(&inner.expr, rules, trace),
ParserExpr::RepOnce(ref inner) | ParserExpr::NodeTag(ref inner, _) => {
is_non_progressing(&inner.expr, rules, trace)
}
}
}
/// Checks if `expr` is non-failing, that is it matches any input.
///
/// # Example
///
/// ```pest
/// non_failing_1 = { "" }
/// ```
///
/// # Assumptions
/// - In `ParserExpr::RepMinMax(inner,min,max)`, `min<=max`
/// - In `ParserExpr::PeekSlice(max,Some(min))`, `max>=min`
/// - All rules identiers have a matching definition
/// - There is no left-recursion
/// - All rules are being checked
fn is_non_failing<'i>(
expr: &ParserExpr<'i>,
rules: &HashMap<String, &ParserNode<'i>>,
trace: &mut Vec<String>,
) -> bool {
match *expr {
ParserExpr::Str(ref string) | ParserExpr::Insens(ref string) => string.is_empty(),
ParserExpr::Ident(ref ident) => {
if !trace.contains(ident) {
if let Some(node) = rules.get(ident) {
trace.push(ident.clone());
let result = is_non_failing(&node.expr, rules, trace);
trace.pop().unwrap();
result
} else {
// else
// the ident is
// - "POP","PEEK" => false
// the slice being checked is not non_failing since every
// PUSH is being checked (assumption 4) and the expr
// of a PUSH has to be non_failing.
// - "POP_ALL", "PEEK_ALL" => false
// same as "POP", "PEEK" unless the following:
// BUG: if the stack is empty they are non_failing
// - "DROP" => false
// - "ANY", "ASCII_*", UNICODE categories, "NEWLINE",
// "SOI", "EOI" => false
// - referring to another rule that is undefined (breaks assumption)
// WARNING: might want to introduce a panic or report the error
false
}
} else {
// referring to another rule R that was already seen
// WARNING: this might mean there is a circular non-failing path
// it's not obvious wether this can happen without left-recursion
// and thus breaking the assumption. Until there is answer to
// this, to avoid changing behaviour we return:
false
}
}
ParserExpr::Opt(_) => true,
ParserExpr::Rep(_) => true,
ParserExpr::RepMax(_, _) => true,
ParserExpr::Seq(ref lhs, ref rhs) => {
is_non_failing(&lhs.expr, rules, trace) && is_non_failing(&rhs.expr, rules, trace)
}
ParserExpr::Choice(ref lhs, ref rhs) => {
is_non_failing(&lhs.expr, rules, trace) || is_non_failing(&rhs.expr, rules, trace)
}
// it either always fail
// or always match at least a character
ParserExpr::Range(_, _) => false,
ParserExpr::PeekSlice(_, _) => {
// the slice being checked is not non_failing since every
// PUSH is being checked (assumption 4) and the expr
// of a PUSH has to be non_failing.
// BUG: if the slice is of size 0, or the stack is not large
// enough it might be non-failing
false
}
ParserExpr::RepExact(ref inner, min)
| ParserExpr::RepMin(ref inner, min)
| ParserExpr::RepMinMax(ref inner, min, _) => {
min == 0 || is_non_failing(&inner.expr, rules, trace)
}
// BUG: the predicate may always fail, resulting in this expr non_failing
// ex of always failing predicates :
// @{EOI ~ ANY | ANY ~ SOI | &("A") ~ &("B") | 'z'..'a'}
ParserExpr::NegPred(_) => false,
ParserExpr::RepOnce(ref inner) => is_non_failing(&inner.expr, rules, trace),
ParserExpr::Push(ref inner)
| ParserExpr::NodeTag(ref inner, _)
| ParserExpr::PosPred(ref inner) => is_non_failing(&inner.expr, rules, trace),
}
}
fn validate_repetition<'a, 'i: 'a>(rules: &'a [ParserRule<'i>]) -> Vec<Error<Rule>> {
let mut result = vec![];
let map = to_hash_map(rules);
for rule in rules {
let mut errors = rule.node
.clone()
.filter_map_top_down(|node| match node.expr {
ParserExpr::Rep(ref other)
| ParserExpr::RepOnce(ref other)
| ParserExpr::RepMin(ref other, _) => {
if is_non_failing(&other.expr, &map, &mut vec![]) {
Some(Error::new_from_span(
ErrorVariant::CustomError {
message:
"expression inside repetition cannot fail and will repeat \
infinitely"
.to_owned()
},
node.span
))
} else if is_non_progressing(&other.expr, &map, &mut vec![]) {
Some(Error::new_from_span(
ErrorVariant::CustomError {
message:
"expression inside repetition is non-progressing and will repeat \
infinitely"
.to_owned(),
},
node.span
))
} else {
None
}
}
_ => None
});
result.append(&mut errors);
}
result
}
fn validate_choices<'a, 'i: 'a>(rules: &'a [ParserRule<'i>]) -> Vec<Error<Rule>> {
let mut result = vec![];
let map = to_hash_map(rules);
for rule in rules {
let mut errors = rule
.node
.clone()
.filter_map_top_down(|node| match node.expr {
ParserExpr::Choice(ref lhs, _) => {
let node = match lhs.expr {
ParserExpr::Choice(_, ref rhs) => rhs,
_ => lhs,
};
if is_non_failing(&node.expr, &map, &mut vec![]) {
Some(Error::new_from_span(
ErrorVariant::CustomError {
message:
"expression cannot fail; following choices cannot be reached"
.to_owned(),
},
node.span,
))
} else {
None
}
}
_ => None,
});
result.append(&mut errors);
}
result
}
fn validate_whitespace_comment<'a, 'i: 'a>(rules: &'a [ParserRule<'i>]) -> Vec<Error<Rule>> {
let map = to_hash_map(rules);
rules
.iter()
.filter_map(|rule| {
if rule.name == "WHITESPACE" || rule.name == "COMMENT" {
if is_non_failing(&rule.node.expr, &map, &mut vec![]) {
Some(Error::new_from_span(
ErrorVariant::CustomError {
message: format!(
"{} cannot fail and will repeat infinitely",
&rule.name
),
},
rule.node.span,
))
} else if is_non_progressing(&rule.node.expr, &map, &mut vec![]) {
Some(Error::new_from_span(
ErrorVariant::CustomError {
message: format!(
"{} is non-progressing and will repeat infinitely",
&rule.name
),
},
rule.node.span,
))
} else {
None
}
} else {
None
}
})
.collect()
}
fn validate_left_recursion<'a, 'i: 'a>(rules: &'a [ParserRule<'i>]) -> Vec<Error<Rule>> {
left_recursion(to_hash_map(rules))
}
fn to_hash_map<'a, 'i: 'a>(rules: &'a [ParserRule<'i>]) -> HashMap<String, &'a ParserNode<'i>> {
rules.iter().map(|r| (r.name.clone(), &r.node)).collect()
}
fn left_recursion<'a, 'i: 'a>(rules: HashMap<String, &'a ParserNode<'i>>) -> Vec<Error<Rule>> {
fn check_expr<'a, 'i: 'a>(
node: &'a ParserNode<'i>,
rules: &'a HashMap<String, &ParserNode<'i>>,
trace: &mut Vec<String>,
) -> Option<Error<Rule>> {
match node.expr.clone() {
ParserExpr::Ident(other) => {
if trace[0] == other {
trace.push(other);
let chain = trace
.iter()
.map(|ident| ident.as_ref())
.collect::<Vec<_>>()
.join(" -> ");
return Some(Error::new_from_span(
ErrorVariant::CustomError {
message: format!(
"rule {} is left-recursive ({}); pest::pratt_parser might be useful \
in this case",
node.span.as_str(),
chain
)
},
node.span
));
}
if !trace.contains(&other) {
if let Some(node) = rules.get(&other) {
trace.push(other);
let result = check_expr(node, rules, trace);
trace.pop().unwrap();
return result;
}
}
None
}
ParserExpr::Seq(ref lhs, ref rhs) => {
if is_non_failing(&lhs.expr, rules, &mut vec![trace.last().unwrap().clone()]) {
check_expr(rhs, rules, trace)
} else {
check_expr(lhs, rules, trace)
}
}
ParserExpr::Choice(ref lhs, ref rhs) => {
check_expr(lhs, rules, trace).or_else(|| check_expr(rhs, rules, trace))
}
ParserExpr::Rep(ref node) => check_expr(node, rules, trace),
ParserExpr::RepOnce(ref node) => check_expr(node, rules, trace),
ParserExpr::Opt(ref node) => check_expr(node, rules, trace),
ParserExpr::PosPred(ref node) => check_expr(node, rules, trace),
ParserExpr::NegPred(ref node) => check_expr(node, rules, trace),
ParserExpr::Push(ref node) => check_expr(node, rules, trace),
_ => None,
}
}
let mut errors = vec![];
for (name, node) in &rules {
let name = name.clone();
if let Some(error) = check_expr(node, &rules, &mut vec![name]) {
errors.push(error);
}
}
errors
}
#[cfg(test)]
mod tests {
use super::super::parser::{consume_rules, PestParser};
use super::super::unwrap_or_report;
use super::*;
use pest::Parser;
#[test]
#[should_panic(expected = "grammar error
--> 1:1
|
1 | ANY = { \"a\" }
| ^-^
|
= ANY is a pest keyword")]
fn pest_keyword() {
let input = "ANY = { \"a\" }";
unwrap_or_report(validate_pairs(
PestParser::parse(Rule::grammar_rules, input).unwrap(),
));
}
#[test]
#[should_panic(expected = "grammar error
--> 1:13
|
1 | a = { \"a\" } a = { \"a\" }
| ^
|
= rule a already defined")]
fn already_defined() {
let input = "a = { \"a\" } a = { \"a\" }";
unwrap_or_report(validate_pairs(
PestParser::parse(Rule::grammar_rules, input).unwrap(),
));
}
#[test]
#[should_panic(expected = "grammar error
--> 1:7
|
1 | a = { b }
| ^
|
= rule b is undefined")]
fn undefined() {
let input = "a = { b }";
unwrap_or_report(validate_pairs(
PestParser::parse(Rule::grammar_rules, input).unwrap(),
));
}
#[test]
fn valid_recursion() {
let input = "a = { \"\" ~ \"a\"? ~ \"a\"* ~ (\"a\" | \"b\") ~ a }";
unwrap_or_report(consume_rules(
PestParser::parse(Rule::grammar_rules, input).unwrap(),
));
}
#[test]
#[should_panic(expected = "grammar error
--> 1:16
|
1 | WHITESPACE = { \"\" }
| ^^
|
= WHITESPACE cannot fail and will repeat infinitely")]
fn non_failing_whitespace() {
let input = "WHITESPACE = { \"\" }";
unwrap_or_report(consume_rules(
PestParser::parse(Rule::grammar_rules, input).unwrap(),
));
}
#[test]
#[should_panic(expected = "grammar error
--> 1:13
|
1 | COMMENT = { SOI }
| ^-^
|
= COMMENT is non-progressing and will repeat infinitely")]
fn non_progressing_comment() {
let input = "COMMENT = { SOI }";
unwrap_or_report(consume_rules(
PestParser::parse(Rule::grammar_rules, input).unwrap(),
));
}
#[test]
fn non_progressing_empty_string() {
assert!(is_non_failing(
&ParserExpr::Insens("".into()),
&HashMap::new(),
&mut Vec::new()
));
assert!(is_non_progressing(
&ParserExpr::Str("".into()),
&HashMap::new(),
&mut Vec::new()
));
}
#[test]
fn progressing_non_empty_string() {
assert!(!is_non_progressing(
&ParserExpr::Insens("non empty".into()),
&HashMap::new(),
&mut Vec::new()
));
assert!(!is_non_progressing(
&ParserExpr::Str("non empty".into()),
&HashMap::new(),
&mut Vec::new()
));
}
#[test]
fn non_progressing_soi_eoi() {
assert!(is_non_progressing(
&ParserExpr::Ident("SOI".into()),
&HashMap::new(),
&mut Vec::new()
));
assert!(is_non_progressing(
&ParserExpr::Ident("EOI".into()),
&HashMap::new(),
&mut Vec::new()
));
}
#[test]
fn non_progressing_predicates() {
let progressing = ParserExpr::Str("A".into());
assert!(is_non_progressing(
&ParserExpr::PosPred(Box::new(ParserNode {
expr: progressing.clone(),
span: Span::new(" ", 0, 1).unwrap(),
})),
&HashMap::new(),
&mut Vec::new()
));
assert!(is_non_progressing(
&ParserExpr::NegPred(Box::new(ParserNode {
expr: progressing,
span: Span::new(" ", 0, 1).unwrap(),
})),
&HashMap::new(),
&mut Vec::new()
));
}
#[test]
fn non_progressing_0_length_repetitions() {
let input_progressing_node = Box::new(ParserNode {
expr: ParserExpr::Str("A".into()),
span: Span::new(" ", 0, 1).unwrap(),
});
assert!(!is_non_progressing(
&input_progressing_node.clone().expr,
&HashMap::new(),
&mut Vec::new()
));
assert!(is_non_progressing(
&ParserExpr::Rep(input_progressing_node.clone()),
&HashMap::new(),
&mut Vec::new()
));
assert!(is_non_progressing(
&ParserExpr::Opt(input_progressing_node.clone()),
&HashMap::new(),
&mut Vec::new()
));
assert!(is_non_progressing(
&ParserExpr::RepExact(input_progressing_node.clone(), 0),
&HashMap::new(),
&mut Vec::new()
));
assert!(is_non_progressing(
&ParserExpr::RepMin(input_progressing_node.clone(), 0),
&HashMap::new(),
&mut Vec::new()
));
assert!(is_non_progressing(
&ParserExpr::RepMax(input_progressing_node.clone(), 0),
&HashMap::new(),
&mut Vec::new()
));
assert!(is_non_progressing(
&ParserExpr::RepMax(input_progressing_node.clone(), 17),
&HashMap::new(),
&mut Vec::new()
));
assert!(is_non_progressing(
&ParserExpr::RepMinMax(input_progressing_node.clone(), 0, 12),
&HashMap::new(),
&mut Vec::new()
));
}
#[test]
fn non_progressing_nonzero_repetitions_with_non_progressing_expr() {
let a = "";
let non_progressing_node = Box::new(ParserNode {
expr: ParserExpr::Str(a.into()),
span: Span::new(a, 0, 0).unwrap(),
});
let exact = ParserExpr::RepExact(non_progressing_node.clone(), 7);
let min = ParserExpr::RepMin(non_progressing_node.clone(), 23);
let minmax = ParserExpr::RepMinMax(non_progressing_node.clone(), 12, 13);
let reponce = ParserExpr::RepOnce(non_progressing_node);
assert!(is_non_progressing(&exact, &HashMap::new(), &mut Vec::new()));
assert!(is_non_progressing(&min, &HashMap::new(), &mut Vec::new()));
assert!(is_non_progressing(
&minmax,
&HashMap::new(),
&mut Vec::new()
));
assert!(is_non_progressing(
&reponce,
&HashMap::new(),
&mut Vec::new()
));
}
#[test]
fn progressing_repetitions() {
let a = "A";
let input_progressing_node = Box::new(ParserNode {
expr: ParserExpr::Str(a.into()),
span: Span::new(a, 0, 1).unwrap(),
});
let exact = ParserExpr::RepExact(input_progressing_node.clone(), 1);
let min = ParserExpr::RepMin(input_progressing_node.clone(), 2);
let minmax = ParserExpr::RepMinMax(input_progressing_node.clone(), 4, 5);
let reponce = ParserExpr::RepOnce(input_progressing_node);
assert!(!is_non_progressing(
&exact,
&HashMap::new(),
&mut Vec::new()
));
assert!(!is_non_progressing(&min, &HashMap::new(), &mut Vec::new()));
assert!(!is_non_progressing(
&minmax,
&HashMap::new(),
&mut Vec::new()
));
assert!(!is_non_progressing(
&reponce,
&HashMap::new(),
&mut Vec::new()
));
}
#[test]
fn non_progressing_push() {
let a = "";
let non_progressing_node = Box::new(ParserNode {
expr: ParserExpr::Str(a.into()),
span: Span::new(a, 0, 0).unwrap(),
});
let push = ParserExpr::Push(non_progressing_node.clone());
assert!(is_non_progressing(&push, &HashMap::new(), &mut Vec::new()));
}
#[test]
fn progressing_push() {
let a = "i'm make progress";
let progressing_node = Box::new(ParserNode {
expr: ParserExpr::Str(a.into()),
span: Span::new(a, 0, 1).unwrap(),
});
let push = ParserExpr::Push(progressing_node.clone());
assert!(!is_non_progressing(&push, &HashMap::new(), &mut Vec::new()));
}
#[test]
fn node_tag_forwards_is_non_progressing() {
let progressing_node = Box::new(ParserNode {
expr: ParserExpr::Str("i'm make progress".into()),
span: Span::new(" ", 0, 1).unwrap(),
});
assert!(!is_non_progressing(
&progressing_node.clone().expr,
&HashMap::new(),
&mut Vec::new()
));
let non_progressing_node = Box::new(ParserNode {
expr: ParserExpr::Str("".into()),
span: Span::new(" ", 0, 1).unwrap(),
});
assert!(is_non_progressing(
&non_progressing_node.clone().expr,
&HashMap::new(),
&mut Vec::new()
));
let progressing = ParserExpr::NodeTag(progressing_node.clone(), "TAG".into());
let non_progressing = ParserExpr::NodeTag(non_progressing_node.clone(), "TAG".into());
assert!(!is_non_progressing(
&progressing,
&HashMap::new(),
&mut Vec::new()
));
assert!(is_non_progressing(
&non_progressing,
&HashMap::new(),
&mut Vec::new()
));
}
#[test]
fn progressing_range() {
let progressing = ParserExpr::Range("A".into(), "Z".into());
let failing_is_progressing = ParserExpr::Range("Z".into(), "A".into());
assert!(!is_non_progressing(
&progressing,
&HashMap::new(),
&mut Vec::new()
));
assert!(!is_non_progressing(
&failing_is_progressing,
&HashMap::new(),
&mut Vec::new()
));
}
#[test]
fn progressing_choice() {
let left_progressing_node = Box::new(ParserNode {
expr: ParserExpr::Str("i'm make progress".into()),
span: Span::new(" ", 0, 1).unwrap(),
});
assert!(!is_non_progressing(
&left_progressing_node.clone().expr,
&HashMap::new(),
&mut Vec::new()
));
let right_progressing_node = Box::new(ParserNode {
expr: ParserExpr::Ident("DROP".into()),
span: Span::new("DROP", 0, 3).unwrap(),
});
assert!(!is_non_progressing(
&ParserExpr::Choice(left_progressing_node, right_progressing_node),
&HashMap::new(),
&mut Vec::new()
))
}
#[test]
fn non_progressing_choices() {
let left_progressing_node = Box::new(ParserNode {
expr: ParserExpr::Str("i'm make progress".into()),
span: Span::new(" ", 0, 1).unwrap(),
});
assert!(!is_non_progressing(
&left_progressing_node.clone().expr,