Debian Codegraph @

pint/delegates/txt_defparser/plain.py

raw
1 """
2 pint.delegates.txt_defparser.plain
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 Definitions for parsing:
6 - Equality
7 - CommentDefinition
8 - PrefixDefinition
9 - UnitDefinition
10 - DimensionDefinition
11 - DerivedDimensionDefinition
12 - AliasDefinition
13
14 Notices that some of the checks are done within the
15 format agnostic parent definition class.
16
17 See each one for a slighly longer description of the
18 syntax.
19
20 :copyright: 2022 by Pint Authors, see AUTHORS for more details.
21 :license: BSD, see LICENSE for more details.
22 """
23
24 from __future__ import annotations
25
26 from dataclasses import dataclass
27
28 import flexparser as fp
29
30 from ...converters import Converter
31 from ...facets.plain import definitions
32 from ...util import UnitsContainer
33 from ..base_defparser import ParserConfig, PintParsedStatement
34 from . import common
35
36
37 @dataclass(frozen=True)
38 class Equality(PintParsedStatement, definitions.Equality):
39 """An equality statement contains a left and right hand separated
40
41 lhs and rhs should be space stripped.
42 """
43
44 @classmethod
45 def from_string(cls, s: str) -> fp.NullableParsedResult[Equality]:
46 if "=" not in s:
47 return None
48 parts = [p.strip() for p in s.split("=")]
49 if len(parts) != 2:
50 return common.DefinitionSyntaxError(
51 f"Exactly two terms expected, not {len(parts)} (`{s}`)"
52 )
53 return cls(*parts)
54
55
56 @dataclass(frozen=True)
57 class CommentDefinition(PintParsedStatement, definitions.CommentDefinition):
58 """Comments start with a # character.
59
60 # This is a comment.
61 ## This is also a comment.
62
63 Captured value does not include the leading # character and space stripped.
64 """
65
66 @classmethod
67 def from_string(cls, s: str) -> fp.NullableParsedResult[CommentDefinition]:
68 if not s.startswith("#"):
69 return None
70 return cls(s[1:].strip())
71
72
73 @dataclass(frozen=True)
74 class PrefixDefinition(PintParsedStatement, definitions.PrefixDefinition):
75 """Definition of a prefix::
76
77 <prefix>- = <value> [= <symbol>] [= <alias>] [ = <alias> ] [...]
78
79 Example::
80
81 deca- = 1e+1 = da- = deka-
82 """
83
84 @classmethod
85 def from_string_and_config(
86 cls, s: str, config: ParserConfig
87 ) -> fp.NullableParsedResult[PrefixDefinition]:
88 if "=" not in s:
89 return None
90
91 name, value, *aliases = s.split("=")
92
93 name = name.strip()
94 if not name.endswith("-"):
95 return None
96
97 name = name.rstrip("-")
98 aliases = tuple(alias.strip().rstrip("-") for alias in aliases)
99
100 defined_symbol = None
101 if aliases:
102 if aliases[0] == "_":
103 aliases = aliases[1:]
104 else:
105 defined_symbol, *aliases = aliases
106
107 aliases = tuple(alias for alias in aliases if alias not in ("", "_"))
108
109 try:
110 value = config.to_number(value)
111 except definitions.NotNumeric as ex:
112 return common.DefinitionSyntaxError(
113 f"Prefix definition ('{name}') must contain only numbers, not {ex.value}"
114 )
115
116 try:
117 return cls(name, value, defined_symbol, aliases)
118 except Exception as exc:
119 return common.DefinitionSyntaxError(str(exc))
120
121
122 @dataclass(frozen=True)
123 class UnitDefinition(PintParsedStatement, definitions.UnitDefinition):
124 """Definition of a unit::
125
126 <canonical name> = <relation to another unit or dimension> [= <symbol>] [= <alias>] [ = <alias> ] [...]
127
128 Example::
129
130 millennium = 1e3 * year = _ = millennia
131
132 Parameters
133 ----------
134 reference : UnitsContainer
135 Reference units.
136 is_base : bool
137 Indicates if it is a base unit.
138
139 """
140
141 @classmethod
142 def from_string_and_config(
143 cls, s: str, config: ParserConfig
144 ) -> fp.NullableParsedResult[UnitDefinition]:
145 if "=" not in s:
146 return None
147
148 name, value, *aliases = (p.strip() for p in s.split("="))
149
150 defined_symbol = None
151 if aliases:
152 if aliases[0] == "_":
153 aliases = aliases[1:]
154 else:
155 defined_symbol, *aliases = aliases
156
157 aliases = tuple(alias for alias in aliases if alias not in ("", "_"))
158
159 if ";" in value:
160 [converter, modifiers] = value.split(";", 1)
161
162 try:
163 modifiers = {
164 key.strip(): config.to_number(value)
165 for key, value in (part.split(":") for part in modifiers.split(";"))
166 }
167 except definitions.NotNumeric as ex:
168 return common.DefinitionSyntaxError(
169 f"Unit definition ('{name}') must contain only numbers in modifier, not {ex.value}"
170 )
171
172 else:
173 converter = value
174 modifiers = {}
175
176 converter = config.to_scaled_units_container(converter)
177
178 try:
179 reference = UnitsContainer(converter)
180 # reference = converter.to_units_container()
181 except common.DefinitionSyntaxError as ex:
182 return common.DefinitionSyntaxError(f"While defining {name}: {ex}")
183
184 try:
185 converter = Converter.from_arguments(scale=converter.scale, **modifiers)
186 except Exception as ex:
187 return common.DefinitionSyntaxError(
188 f"Unable to assign a converter to the unit {ex}"
189 )
190
191 try:
192 return cls(name, defined_symbol, tuple(aliases), converter, reference)
193 except Exception as ex:
194 return common.DefinitionSyntaxError(str(ex))
195
196
197 @dataclass(frozen=True)
198 class DimensionDefinition(PintParsedStatement, definitions.DimensionDefinition):
199 """Definition of a root dimension::
200
201 [dimension name]
202
203 Example::
204
205 [volume]
206 """
207
208 @classmethod
209 def from_string(cls, s: str) -> fp.NullableParsedResult[DimensionDefinition]:
210 s = s.strip()
211
212 if not (s.startswith("[") and "=" not in s):
213 return None
214
215 return cls(s)
216
217
218 @dataclass(frozen=True)
219 class DerivedDimensionDefinition(
220 PintParsedStatement, definitions.DerivedDimensionDefinition
221 ):
222 """Definition of a derived dimension::
223
224 [dimension name] = <relation to other dimensions>
225
226 Example::
227
228 [density] = [mass] / [volume]
229 """
230
231 @classmethod
232 def from_string_and_config(
233 cls, s: str, config: ParserConfig
234 ) -> fp.NullableParsedResult[DerivedDimensionDefinition]:
235 if not (s.startswith("[") and "=" in s):
236 return None
237
238 name, value, *aliases = s.split("=")
239
240 if aliases:
241 return common.DefinitionSyntaxError(
242 "Derived dimensions cannot have aliases."
243 )
244
245 try:
246 reference = config.to_dimension_container(value)
247 except common.DefinitionSyntaxError as exc:
248 return common.DefinitionSyntaxError(
249 f"In {name} derived dimensions must only be referenced "
250 f"to dimensions. {exc}"
251 )
252
253 try:
254 return cls(name.strip(), reference)
255 except Exception as exc:
256 return common.DefinitionSyntaxError(str(exc))
257
258
259 @dataclass(frozen=True)
260 class AliasDefinition(PintParsedStatement, definitions.AliasDefinition):
261 """Additional alias(es) for an already existing unit::
262
263 @alias <canonical name or previous alias> = <alias> [ = <alias> ] [...]
264
265 Example::
266
267 @alias meter = my_meter
268 """
269
270 @classmethod
271 def from_string(cls, s: str) -> fp.NullableParsedResult[AliasDefinition]:
272 if not s.startswith("@alias "):
273 return None
274 name, *aliases = s[len("@alias ") :].split("=")
275
276 try:
277 return cls(name.strip(), tuple(alias.strip() for alias in aliases))
278 except Exception as exc:
279 return common.DefinitionSyntaxError(str(exc))