Debian Codegraph @

pint/delegates/txt_defparser/system.py

raw
1 """
2 pint.delegates.txt_defparser.system
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 :copyright: 2022 by Pint Authors, see AUTHORS for more details.
6 :license: BSD, see LICENSE for more details.
7 """
8
9 from __future__ import annotations
10
11 import re
12 import typing as ty
13 from dataclasses import dataclass
14
15 import flexparser as fp
16
17 from ...facets.system import definitions
18 from ..base_defparser import PintParsedStatement
19 from . import block, common, plain
20
21
22 @dataclass(frozen=True)
23 class BaseUnitRule(PintParsedStatement, definitions.BaseUnitRule):
24 @classmethod
25 def from_string(cls, s: str) -> fp.NullableParsedResult[BaseUnitRule]:
26 if ":" not in s:
27 return cls(s.strip())
28 parts = [p.strip() for p in s.split(":")]
29 if len(parts) != 2:
30 return common.DefinitionSyntaxError(
31 f"Exactly two terms expected for rule, not {len(parts)} (`{s}`)"
32 )
33 return cls(*parts)
34
35
36 @dataclass(frozen=True)
37 class BeginSystem(PintParsedStatement):
38 """Being of a system directive.
39
40 @system <name> [using <group 1>, ..., <group N>]
41 """
42
43 #: Regex to match the header parts of a context.
44 _header_re = re.compile(r"@system\s+(?P<name>\w+)\s*(using\s(?P<used_groups>.*))*")
45
46 name: str
47 using_group_names: ty.Tuple[str, ...]
48
49 @classmethod
50 def from_string(cls, s: str) -> fp.NullableParsedResult[BeginSystem]:
51 if not s.startswith("@system"):
52 return None
53
54 r = cls._header_re.search(s)
55
56 if r is None:
57 raise ValueError("Invalid System header syntax '%s'" % s)
58
59 name = r.groupdict()["name"].strip()
60 groups = r.groupdict()["used_groups"]
61
62 # If the systems has no group, it automatically uses the root group.
63 if groups:
64 group_names = tuple(a.strip() for a in groups.split(","))
65 else:
66 group_names = ("root",)
67
68 return cls(name, group_names)
69
70
71 @dataclass(frozen=True)
72 class SystemDefinition(
73 block.DirectiveBlock[
74 definitions.SystemDefinition,
75 BeginSystem,
76 ty.Union[plain.CommentDefinition, BaseUnitRule],
77 ]
78 ):
79 """Definition of a System:
80
81 @system <name> [using <group 1>, ..., <group N>]
82 <rule 1>
83 ...
84 <rule N>
85 @end
86
87 See Rule and Comment for more parsing related information.
88
89 The syntax for the rule is:
90
91 new_unit_name : old_unit_name
92
93 where:
94 - old_unit_name: a root unit part which is going to be removed from the system.
95 - new_unit_name: a non root unit which is going to replace the old_unit.
96
97 If the new_unit_name and the old_unit_name, the later and the colon can be omitted.
98 """
99
100 def derive_definition(self) -> definitions.SystemDefinition:
101 return definitions.SystemDefinition(
102 self.name, self.using_group_names, self.rules
103 )
104
105 @property
106 def name(self) -> str:
107 assert isinstance(self.opening, BeginSystem)
108 return self.opening.name
109
110 @property
111 def using_group_names(self) -> tuple[str, ...]:
112 assert isinstance(self.opening, BeginSystem)
113 return self.opening.using_group_names
114
115 @property
116 def rules(self) -> tuple[BaseUnitRule, ...]:
117 return tuple(el for el in self.body if isinstance(el, BaseUnitRule))