-
Notifications
You must be signed in to change notification settings - Fork 2
/
peglet_to_parson.py
37 lines (32 loc) · 1.01 KB
/
peglet_to_parson.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
"""
Convert a Peglet grammar to a Parson one.
"""
import re
from parson import Grammar, alter
name = r'[A-Za-z_]\w*'
grammar = Grammar(r"""
grammar : _? rule* :end.
rule : name _ '= ' :equ token* :'.' _?.
token : '|' :'|'
| /(\/\w*\/\s)/
| name !(_ '= ')
| '!' :'!'
| _ !(name _ '= ' | :end)
| !('= '|name) /(\S+)/ :mk_regex.
name : /("""+name+""")/ !!(/\s/ | :end).
_ : /(\s+)/.
""")
def mk_regex(s): return '/' + s.replace('/', '\\/') + '/'
def peglet_to_parson(text):
nonterminals = set()
def equ(name, space):
nonterminals.add(name)
return name, space, ': '
g = grammar(equ=alter(equ), mk_regex=mk_regex)
tokens = g.grammar(text)
return ''.join(':'+token if re.match(name+'$', token) and token not in nonterminals
else token
for token in tokens)
if __name__ == '__main__':
import sys
print peglet_to_parson(sys.stdin.read())