Debian Codegraph @

pint/delegates/txt_defparser/group.py

raw
1 """
2 pint.delegates.txt_defparser.group
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 Definitions for parsing Group and their related objects
6
7 Notices that some of the checks are done within the
8 format agnostic parent definition class.
9
10 See each one for a slighly longer description of the
11 syntax.
12
13 :copyright: 2022 by Pint Authors, see AUTHORS for more details.
14 :license: BSD, see LICENSE for more details.
15 """
16
17 from __future__ import annotations
18
19 import re
20 import typing as ty
21 from dataclasses import dataclass
22
23 import flexparser as fp
24
25 from ...facets.group import definitions
26 from ..base_defparser import PintParsedStatement
27 from . import block, common, plain
28
29
30 @dataclass(frozen=True)
31 class BeginGroup(PintParsedStatement):
32 """Being of a group directive.
33
34 @group <name> [using <group 1>, ..., <group N>]
35 """
36
37 #: Regex to match the header parts of a definition.
38 _header_re = re.compile(r"@group\s+(?P<name>\w+)\s*(using\s(?P<used_groups>.*))*")
39
40 name: str
41 using_group_names: ty.Tuple[str, ...]
42
43 @classmethod
44 def from_string(cls, s: str) -> fp.NullableParsedResult[BeginGroup]:
45 if not s.startswith("@group"):
46 return None
47
48 r = cls._header_re.search(s)
49
50 if r is None:
51 return common.DefinitionSyntaxError(f"Invalid Group header syntax: '{s}'")
52
53 name = r.groupdict()["name"].strip()
54 groups = r.groupdict()["used_groups"]
55 if groups:
56 parent_group_names = tuple(a.strip() for a in groups.split(","))
57 else:
58 parent_group_names = ()
59
60 return cls(name, parent_group_names)
61
62
63 @dataclass(frozen=True)
64 class GroupDefinition(
65 block.DirectiveBlock[
66 definitions.GroupDefinition,
67 BeginGroup,
68 ty.Union[
69 plain.CommentDefinition,
70 plain.UnitDefinition,
71 ],
72 ]
73 ):
74 """Definition of a group.
75
76 @group <name> [using <group 1>, ..., <group N>]
77 <definition 1>
78 ...
79 <definition N>
80 @end
81
82 See UnitDefinition and Comment for more parsing related information.
83
84 Example::
85
86 @group AvoirdupoisUS using Avoirdupois
87 US_hundredweight = hundredweight = US_cwt
88 US_ton = ton
89 US_force_ton = force_ton = _ = US_ton_force
90 @end
91
92 """
93
94 def derive_definition(self) -> definitions.GroupDefinition:
95 return definitions.GroupDefinition(
96 self.name, self.using_group_names, self.definitions
97 )
98
99 @property
100 def name(self) -> str:
101 assert isinstance(self.opening, BeginGroup)
102 return self.opening.name
103
104 @property
105 def using_group_names(self) -> tuple[str, ...]:
106 assert isinstance(self.opening, BeginGroup)
107 return self.opening.using_group_names
108
109 @property
110 def definitions(self) -> tuple[plain.UnitDefinition, ...]:
111 return tuple(el for el in self.body if isinstance(el, plain.UnitDefinition))