-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.py
53 lines (39 loc) · 1.69 KB
/
parser.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
import os
from parglare import Grammar, Parser
from .json_actions import action
class JSONParser:
grammar = os.path.join(os.path.dirname(__file__), "jsongrammar.pg")
def __init__(self, actions=action.all, build_tree=False):
self.actions = actions
self.build_tree = build_tree
def fetch_tree(self, result):
if self.build_tree:
print(result.tree_str())
else:
info_message = """
JSONParser initialized with `build_tree=False`.
To view the parse tree, initialize with `build_tree=True`.
"""
print(info_message)
def from_file(self, filename, cleaned=True, **kwargs):
actions = self.actions if cleaned else None
g = Grammar.from_file(self.grammar, **kwargs)
parser = Parser(g, actions=actions, build_tree=self.build_tree, **kwargs)
result = parser.parse_file(file_name=filename)
self.fetch_tree(result)
return result
def from_string(self, input_str, cleaned=True, **kwargs):
actions = self.actions if cleaned else None
g = Grammar.from_file(self.grammar, **kwargs)
parser = Parser(g, actions=actions, build_tree=self.build_tree, **kwargs)
result = parser.parse(input_str)
self.fetch_tree(result)
return result
def from_stream(self, source, cleaned=True, **kwargs):
actions = self.actions if cleaned else None
g = Grammar.from_file(self.grammar, **kwargs)
parser = Parser(g, actions=actions, build_tree=self.build_tree, **kwargs)
with open(source, "r") as f:
result = parser.parse(f.read())
self.fetch_tree(result)
return result