-
Notifications
You must be signed in to change notification settings - Fork 32
/
test_grammar.py
126 lines (110 loc) · 3.26 KB
/
test_grammar.py
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
"""
Testing grammar construction
"""
import pytest
from parglare import Parser
from parglare.grammar import (Grammar, MULT_ONE_OR_MORE, MULT_ZERO_OR_MORE,
MULT_OPTIONAL)
test_grammar = r'''
A: B C+[COMMA, nogreedy];
B: C* D? | D;
terminals
C: 'c';
D: /\d+\/\d+/;
COMMA: ',';
'''
@pytest.fixture
def test_grammar_struct():
return {
'start': 'A',
'rules': {
'A': {
'productions': [
{'production': ['B', {'symbol': 'C',
'mult': MULT_ONE_OR_MORE,
'modifiers': ['COMMA', 'nogreedy']}]}
]
},
'B': {
'productions': [
{'production': [{'symbol': 'C',
'mult': MULT_ZERO_OR_MORE},
{'symbol': 'D',
'mult': MULT_OPTIONAL}]},
{'production': ['D']}
]
}
},
'terminals': {
'C': {'recognizer': 'c'},
'D': {'recognizer': r'/\d+\/\d+/'},
'COMMA': {'recognizer': ','},
}
}
test_grammar_struct_desugared = {
'start': "A",
'rules': {
"S'": {
'productions': [
{'production': ['A', 'STOP']}
]
},
'A': {
'productions': [
{'production': ['B', 'C_1_COMMA_nogreedy']}
]
},
'B': {
'productions': [
{'production': ['C_0', 'D_opt']},
{'production': ['D']}
]
},
'C_1_COMMA_nogreedy': {
'action': 'collect_sep',
'productions': [
{'production': ['C_1_COMMA_nogreedy', 'COMMA', 'C'],
'modifiers': ['nogreedy']},
{'production': ['C']},
]
},
'C_1': {
'action': 'collect',
'productions': [
{'production': ['C_1', 'C']},
{'production': ['C']},
]
},
'C_0': {
'productions': [
{'production': ['C_1']},
{'production': ['EMPTY']}
]
},
'D_opt': {
'action': 'optional',
'productions': [
{'production': ['D']},
{'production': ['EMPTY']}
]
}
},
'terminals': {
'C': {'recognizer': 'c'},
'D': {'recognizer': r'/\d+\/\d+/'},
'COMMA': {'recognizer': ','},
}
}
def test_grammar_construction_from_struct(test_grammar_struct):
grammar = Grammar.from_struct(test_grammar_struct)
assert grammar.grammar_struct == test_grammar_struct_desugared
def test_grammar_struct_construction_from_string(test_grammar_struct):
grammar_struct = Grammar.struct_from_string(test_grammar)
Grammar.remove_locations(grammar_struct)
assert grammar_struct == test_grammar_struct
def test_grammar_from_string():
grammar = Grammar.from_string(test_grammar)
assert grammar
parser = Parser(grammar)
result = parser.parse('c c c c 34/44 c,c,c ')
assert result == [[['c', 'c', 'c', 'c'], '34/44'], ['c', 'c', 'c']]