-
Notifications
You must be signed in to change notification settings - Fork 0
/
grammar.py
61 lines (48 loc) · 1.36 KB
/
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
"""
A class used as a data structure to represent a grammar.
An instance of the Grammar class is initialized with the source path to
a grammar JSON file. The JSON file is parsed into the grammar object's
members.
"""
import json
class Grammar:
def __init__(self, source):
try:
self.desc = ""
self.rules = dict()
with open(source) as json_file:
grammar = json.load(json_file)
self.desc = grammar["desc"]
self.rules = grammar["rules"]
except (OSError, IOError):
pass
def get_desc(self):
return self.desc
def produces(self, variable):
"""
Retrieve all the productions that the passed variable is
capable of producing.
:param variable: The variable in question.
:return: A list of productions.
"""
if variable not in self.rules:
return False
return self.rules[variable]
def get_rule(self, variable, input_symbol):
"""
Retrieve the single production (rule) that the passed variable
can produce whose leftmost symbol is the passed input (terminal)
symbol.
:param variable: The variable in question.
:param input_symbol: The input symbol in question.
:return: A single production.
"""
if len(input_symbol) != 1:
return False
productions = self.produces(variable)
if not productions:
return False
for production in productions:
if production[0] == input_symbol:
return production
return False