summaryrefslogtreecommitdiff
path: root/pint/delegates/txt_defparser/defaults.py
blob: af6e31f293f350e9df4ace2dbce8238d14796739 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
    pint.delegates.txt_defparser.defaults
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Definitions for parsing Default sections.

    See each one for a slighly longer description of the
    syntax.

    :copyright: 2022 by Pint Authors, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""

from __future__ import annotations

import typing as ty
from dataclasses import dataclass, fields

from ..._vendor import flexparser as fp
from ...facets.plain import definitions
from . import block, plain


@dataclass(frozen=True)
class BeginDefaults(fp.ParsedStatement):
    """Being of a defaults directive.

    @defaults
    """

    @classmethod
    def from_string(cls, s: str) -> fp.FromString[BeginDefaults]:
        if s.strip() == "@defaults":
            return cls()
        return None


@dataclass(frozen=True)
class DefaultsDefinition(block.DirectiveBlock):
    """Directive to store values.

        @defaults
            system = mks
        @end

    See Equality and Comment for more parsing related information.
    """

    opening: fp.Single[BeginDefaults]
    body: fp.Multi[
        ty.Union[
            plain.CommentDefinition,
            plain.Equality,
        ]
    ]

    @property
    def _valid_fields(self):
        return tuple(f.name for f in fields(definitions.DefaultsDefinition))

    def derive_definition(self):
        for definition in self.filter_by(plain.Equality):
            if definition.lhs not in self._valid_fields:
                raise ValueError(
                    f"`{definition.lhs}` is not a valid key "
                    f"for the default section. {self._valid_fields}"
                )

        return definitions.DefaultsDefinition(
            *tuple(self.get_key(key) for key in self._valid_fields)
        )

    def get_key(self, key):
        for stmt in self.body:
            if isinstance(stmt, plain.Equality) and stmt.lhs == key:
                return stmt.rhs
        raise KeyError(key)