-
Notifications
You must be signed in to change notification settings - Fork 0
/
grammar.py
67 lines (52 loc) · 2.12 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
62
63
64
65
66
67
from constants import LAMBDA_SYMBOL
from typing import List, Dict
from production import Production
import json
ErrNoProductions = Exception("file does not have productions")
ErrNoTerminals = Exception("file does not have terminals")
ErrNoNoTerminals = Exception("file does not have no terminals")
ErrNoNoTerminalProductionLeft = Exception(
"production left is not in no_terminals"
)
ErrSymbolNotDefined = Exception(
"symbol is not defined as terminal or no_terminal"
)
class Grammar:
def __init__(self):
self.terminals: List[str] = []
self.no_terminals: List[str] = []
self.productions: List[Production] = []
def validate_loaded_file(self, loaded_json: Dict):
if loaded_json.get("terminals") is None:
raise ErrNoTerminals
self.terminals = loaded_json["terminals"]
self.terminals.append(LAMBDA_SYMBOL)
if loaded_json.get("no_terminals") is None:
raise ErrNoNoTerminals
self.no_terminals = loaded_json["no_terminals"]
if loaded_json.get("productions") is None:
raise ErrNoProductions
productions: Dict[str, List[List[str]]] = loaded_json["productions"]
productions_count = 0
for production_left in productions:
if production_left not in self.no_terminals:
raise ErrNoNoTerminalProductionLeft
for symbols in productions[production_left]:
for symbol in symbols:
if (
symbol not in self.no_terminals
and symbol not in self.terminals
):
print("Symbol:" + symbol)
raise ErrSymbolNotDefined
self.productions.append(
Production(production_left, symbols, productions_count)
)
productions_count = productions_count + 1
def load_from_file(self, file_path: str):
file = open(file_path)
loaded_json: Dict = json.load(file)
try:
self.validate_loaded_file(loaded_json)
except Exception as err:
print(err)