repeating.nim
1.94 KB
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
import petitparser
# An abstract parser that repeatedly parses between 'min' and 'max' instances of its delegate.
type
RepeatingParser = ref object of DelegateParser
min*: int
max*: int
const UNBOUNDED = 1
proc newRepeatingParser*(delegate: Parser, min, max: int): RepeatingParser =
if min < 0:
raise newException(Exception, "Invalid min repetitions")
if max != UNBOUNDED and min > max:
raise newException(Exception, "Invalid max repetitions")
RepeatingParser(delegate, min, max)
discard """
@Override
public boolean hasEqualProperties(Parser other) {
return super.hasEqualProperties(other) &&
Objects.equals(min, ((RepeatingParser) other).min) &&
Objects.equals(max, ((RepeatingParser) other).max);
}
@Override
public String toString() {
return super.toString() + "[" + min + ".." + (max == UNBOUNDED ? "*" : max) + "]";
}
"""
# A greedy parser that repeatedly parses between 'min' and 'max' instances of its delegate.
type
PossessiveRepeatingParser = ref object of RepeatingParser
proc newPossessiveRepeatingParser*(delegate: Parser, min, max: int): PossessiveRepeatingParser =
PossessiveRepeatingParser(newRepeatingParser(delegate, min, max))
discard """
@Override
public Result parseOn(Context context) {
Context current = context;
List<Object> elements = new ArrayList<>();
while (elements.size() < min) {
Result result = delegate.parseOn(current);
if (result.isFailure()) {
return result;
}
elements.add(result.get());
current = result;
}
while (max == UNBOUNDED || elements.size() < max) {
Result result = delegate.parseOn(current);
if (result.isFailure()) {
return current.success(elements);
}
elements.add(result.get());
current = result;
}
return current.success(elements);
}
@Override
public Parser copy() {
return new PossessiveRepeatingParser(delegate, min, max);
}
"""