feat: добавлен парсинг правил грамматики
This commit is contained in:
9
src/rule.py
Normal file
9
src/rule.py
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
EMPTY_SYMBOL = '$'
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Rule:
|
||||||
|
operand: str
|
||||||
|
target: str
|
||||||
|
is_blocking: bool
|
||||||
@ -1,4 +1,4 @@
|
|||||||
from collections import OrderedDict
|
from rule import Rule, EMPTY_SYMBOL
|
||||||
import re
|
import re
|
||||||
|
|
||||||
class RulesParser:
|
class RulesParser:
|
||||||
@ -7,9 +7,9 @@ class RulesParser:
|
|||||||
NEWLINE = '\n'
|
NEWLINE = '\n'
|
||||||
IGNORE = r'\s+'
|
IGNORE = r'\s+'
|
||||||
COMMENTS = r'//.+$'
|
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
|
Parsing file according to syntax, specified
|
||||||
in class variables. Hardcoded for now (and forever)
|
in class variables. Hardcoded for now (and forever)
|
||||||
@ -17,13 +17,32 @@ class RulesParser:
|
|||||||
with open(file, 'r') as f:
|
with open(file, 'r') as f:
|
||||||
text = f.read()
|
text = f.read()
|
||||||
lines = self._get_lines(text)
|
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
|
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]:
|
def _get_lines(self, src: str) -> list[str]:
|
||||||
"""
|
"""
|
||||||
|
|||||||
Reference in New Issue
Block a user