Debian Codegraph @

examples/pint/pint_parser/group.py

raw symbols SCIP
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, plain
10
11
12 @dataclass(frozen=True)
13 class BeginGroup(fp.ParsedStatement):
14 """Being of a group directive.
15
16 @group <name> [using <group 1>, ..., <group N>]
17 """
18
19 #: Regex to match the header parts of a definition.
20 _header_re = re.compile(r"@group\s+(?P<name>\w+)\s*(using\s(?P<used_groups>.*))*")
21
22 name: str
23 using_group_names: ty.Tuple[str, ...]
24
25 @classmethod
26 def from_string(cls, s: str) -> fp.NullableParsedResult[BeginGroup]:
27 if not s.startswith("@group"):
28 return None
29
30 r = cls._header_re.search(s)
31
32 if r is None:
33 raise ValueError("Invalid Group header syntax: '%s'" % s)
34
35 name = r.groupdict()["name"].strip()
36 groups = r.groupdict()["used_groups"]
37 if groups:
38 parent_group_names = tuple(a.strip() for a in groups.split(","))
39 else:
40 parent_group_names = ()
41
42 return cls(name, parent_group_names)
43
44
45 @dataclass(frozen=True)
46 class GroupDefinition(common.DirectiveBlock):
47 """Definition of a group.
48
49 @group <name> [using <group 1>, ..., <group N>]
50 <definition 1>
51 ...
52 <definition N>
53 @end
54
55 See UnitDefinition and Comment for more parsing related information.
56
57 Example::
58
59 @group AvoirdupoisUS using Avoirdupois
60 US_hundredweight = hundredweight = US_cwt
61 US_ton = ton
62 US_force_ton = force_ton = _ = US_ton_force
63 @end
64
65 """
66
67 @property
68 def unit_names(self) -> ty.Tuple[str, ...]:
69 return tuple(
70 el.name for el in self.body if isinstance(el, plain.UnitDefinition)
71 )