Debian Codegraph @

python/src/feature_check/expr.py

raw
1 # SPDX-FileCopyrightText: Peter Pentchev <[email protected]>
2 # SPDX-License-Identifier: BSD-2-Clause
3
4 """Expression evaluation for the feature-check Python library."""
5
6 from __future__ import annotations
7
8 import dataclasses
9 from collections.abc import Callable
10 from typing import Final
11
12 from . import defs
13 from . import version as fver
14
15
16 BoolOpFunction = Callable[[list[defs.Result]], bool]
17
18
19 @dataclasses.dataclass(frozen=True)
20 class ResultBool(defs.Result):
21 """A boolean result of an expression; the "value" member is boolean."""
22
23 value: bool
24
25 def __str__(self) -> str:
26 """Provide a human-readable representation of the calculation result."""
27 return f"ResultBool: {self.value}"
28
29
30 @dataclasses.dataclass(frozen=True)
31 class ResultVersion(defs.Result):
32 """A version number as a result of an expression.
33
34 The "value" member is the version number string.
35 """
36
37 value: fver.Version
38
39 def __str__(self) -> str:
40 """Provide a human-readable representation of the calculation result."""
41 return f"ResultVersion: {self.value.value}"
42
43
44 @dataclasses.dataclass(frozen=True)
45 class ExprFeature(defs.Expr):
46 """An expression that returns a program feature name as a string."""
47
48 name: str
49
50 def evaluate(self, data: dict[str, fver.Version]) -> ResultVersion:
51 """Look up the feature, return the result in a ResultVersion object."""
52 return ResultVersion(value=data[self.name])
53
54
55 @dataclasses.dataclass(frozen=True)
56 class ExprVersion(defs.Expr):
57 """An expression that returns a version number for a feature."""
58
59 value: fver.Version
60
61 def evaluate(self, _data: dict[str, fver.Version]) -> ResultVersion:
62 """Return the version number as a ResultVersion object."""
63 return ResultVersion(value=self.value)
64
65
66 @dataclasses.dataclass(frozen=True)
67 class BoolOp:
68 """A two-argument boolean operation."""
69
70 args: list[type[defs.Result]]
71 action: BoolOpFunction
72
73
74 def _def_op_bool_ver(check: Callable[[int], bool]) -> BoolOpFunction:
75 def _op_bool_ver(args: list[defs.Result]) -> bool:
76 """Check whether the arguments are in the expected relation."""
77 match args:
78 case [left, right] if isinstance(left, ResultVersion) and isinstance(
79 right,
80 ResultVersion,
81 ):
82 return check(fver.version_compare(left.value, right.value))
83
84 raise TypeError(args)
85
86 return _op_bool_ver
87
88
89 NAMED_OPS = {
90 "lt": BoolOp(
91 args=[ResultVersion, ResultVersion],
92 action=_def_op_bool_ver(lambda res: res < 0),
93 ),
94 "le": BoolOp(
95 args=[ResultVersion, ResultVersion],
96 action=_def_op_bool_ver(lambda res: res <= 0),
97 ),
98 "eq": BoolOp(
99 args=[ResultVersion, ResultVersion],
100 action=_def_op_bool_ver(lambda res: res == 0),
101 ),
102 "ge": BoolOp(
103 args=[ResultVersion, ResultVersion],
104 action=_def_op_bool_ver(lambda res: res >= 0),
105 ),
106 "gt": BoolOp(
107 args=[ResultVersion, ResultVersion],
108 action=_def_op_bool_ver(lambda res: res > 0),
109 ),
110 }
111
112 SYNONYMS = {"<": "lt", "<=": "le", "=": "eq", ">=": "ge", ">": "gt"}
113
114 OPS = dict(
115 list(NAMED_OPS.items()) + [(name, NAMED_OPS[value]) for name, value in SYNONYMS.items()],
116 )
117
118
119 @dataclasses.dataclass(frozen=True)
120 class ExprOp(defs.Expr):
121 """A two-argument operation expression."""
122
123 op: BoolOp
124 args: list[defs.Expr]
125
126 def __post_init__(self) -> None:
127 """Validate the passed arguments."""
128 if len(self.args) != len(self.op.args):
129 raise ValueError((self.args, self.op.args))
130
131 def evaluate(self, data: dict[str, fver.Version]) -> ResultBool:
132 """Evaluate the expression over the specified data."""
133 args: Final = [expr.evaluate(data) for expr in self.args]
134
135 for idx, value in enumerate(args):
136 if not isinstance(value, self.op.args[idx]):
137 raise TypeError((idx, self.op.args[idx], value))
138
139 return ResultBool(value=self.op.action(args))