feat: добавлен парсинг правил грамматики

This commit is contained in:
ElectronixTM
2025-03-16 00:23:30 +03:00
parent 927cd2a133
commit b044e908bb
2 changed files with 34 additions and 6 deletions

9
src/rule.py Normal file
View File

@ -0,0 +1,9 @@
from dataclasses import dataclass
EMPTY_SYMBOL = '$'
@dataclass(frozen=True)
class Rule:
operand: str
target: str
is_blocking: bool

View File

@ -1,4 +1,4 @@
from collections import OrderedDict
from rule import Rule, EMPTY_SYMBOL
import re
class RulesParser:
@ -7,9 +7,9 @@ class RulesParser:
NEWLINE = '\n'
IGNORE = r'\s+'
COMMENTS = r'//.+$'
EMPTY = r'\$'
EMPTY = re.escape(EMPTY_SYMBOL)
def parse(self, file: str):
def parse(self, file: str) -> list[Rule]:
"""
Parsing file according to syntax, specified
in class variables. Hardcoded for now (and forever)
@ -17,13 +17,32 @@ class RulesParser:
with open(file, 'r') as f:
text = f.read()
lines = self._get_lines(text)
self._parse_rule(lines[0])
rules = list()
for line in lines:
rules.append(self._parse_rule(line))
return rules
def _parse_rule(self, line: str) -> tuple[str, str]:
def _parse_rule(self, line: str) -> Rule:
"""
tries to parse rule according to set grammar
"""
print(re.split(self.IGNORE, line))
tokens = re.split(self.IGNORE, line)
# we always expect 3 parts: operand, arrow, target
arrow = tokens[1]
is_blocking = None
if re.fullmatch(self.TRANSFORM, arrow):
is_blocking = False
elif re.fullmatch(self.B_TRANSFORM, arrow):
is_blocking = True
else:
raise ValueError(f"Can't recognize transform symbol. "
f"\"{self.TRANSFORM}\" or \"{self.B_TRANSFORM}\""
f" expected, but \"{arrow}\" encountered")
return Rule(
operand=tokens[0],
target=tokens[2],
is_blocking=is_blocking
)
def _get_lines(self, src: str) -> list[str]:
"""