| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import re |
| 4 |
import typing as ty |
| 5 |
from dataclasses import dataclass |
| 6 |
|
| 7 |
import flexparser.flexparser as fp |
| 8 |
|
| 9 |
from . import common, errors |
| 10 |
|
| 11 |
|
| 12 |
@dataclass(frozen=True) |
| 13 |
class Rule(fp.ParsedStatement): |
| 14 |
new_unit_name: str |
| 15 |
old_unit_name: ty.Optional[str] = None |
| 16 |
|
| 17 |
@classmethod |
| 18 |
def from_string(cls, s: str) -> fp.NullableParsedResult[Rule]: |
| 19 |
if ":" not in s: |
| 20 |
return cls(s.strip()) |
| 21 |
parts = [p.strip() for p in s.split(":")] |
| 22 |
if len(parts) != 2: |
| 23 |
return errors.DefinitionSyntaxError( |
| 24 |
f"Exactly two terms expected for rule, not {len(parts)} (`{s}`)" |
| 25 |
) |
| 26 |
return cls(*parts) |
| 27 |
|
| 28 |
|
| 29 |
@dataclass(frozen=True) |
| 30 |
class BeginSystem(fp.ParsedStatement): |
| 31 |
"""Being of a system directive. |
| 32 |
|
| 33 |
@system <name> [using <group 1>, ..., <group N>] |
| 34 |
""" |
| 35 |
|
| 36 |
|
| 37 |
_header_re = re.compile(r"@system\s+(?P<name>\w+)\s*(using\s(?P<used_groups>.*))*") |
| 38 |
|
| 39 |
name: str |
| 40 |
using_group_names: ty.Tuple[str, ...] |
| 41 |
|
| 42 |
@classmethod |
| 43 |
def from_string(cls, s: str) -> fp.NullableParsedResult[BeginSystem]: |
| 44 |
if not s.startswith("@system"): |
| 45 |
return None |
| 46 |
|
| 47 |
r = cls._header_re.search(s) |
| 48 |
|
| 49 |
if r is None: |
| 50 |
raise ValueError("Invalid System header syntax '%s'" % s) |
| 51 |
|
| 52 |
name = r.groupdict()["name"].strip() |
| 53 |
groups = r.groupdict()["used_groups"] |
| 54 |
|
| 55 |
|
| 56 |
if groups: |
| 57 |
group_names = tuple(a.strip() for a in groups.split(",")) |
| 58 |
else: |
| 59 |
group_names = ("root",) |
| 60 |
|
| 61 |
return cls(name, group_names) |
| 62 |
|
| 63 |
|
| 64 |
@dataclass(frozen=True) |
| 65 |
class SystemDefinition(common.DirectiveBlock): |
| 66 |
"""Definition of a System: |
| 67 |
|
| 68 |
@system <name> [using <group 1>, ..., <group N>] |
| 69 |
<rule 1> |
| 70 |
... |
| 71 |
<rule N> |
| 72 |
@end |
| 73 |
|
| 74 |
See Rule and Comment for more parsing related information. |
| 75 |
|
| 76 |
The syntax for the rule is: |
| 77 |
|
| 78 |
new_unit_name : old_unit_name |
| 79 |
|
| 80 |
where: |
| 81 |
- old_unit_name: a root unit part which is going to be removed from the system. |
| 82 |
- new_unit_name: a non root unit which is going to replace the old_unit. |
| 83 |
|
| 84 |
If the new_unit_name and the old_unit_name, the later and the colon can be omitted. |
| 85 |
""" |
| 86 |
|
| 87 |
@property |
| 88 |
def unit_replacements(self) -> ty.Tuple[ty.Tuple[str, str], ...]: |
| 89 |
return tuple((el.new_unit_name, el.old_unit_name) for el in self.body) |