| 1 |
# SPDX-FileCopyrightText: Peter Pentchev <[email protected]> |
| 2 |
# SPDX-License-Identifier: BSD-2-Clause |
| 3 |
|
| 4 |
"""Parse feature names, versions, and simple expressions.""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
from typing import Final |
| 9 |
|
| 10 |
import pyparsing as pyp |
| 11 |
|
| 12 |
from . import defs |
| 13 |
from . import expr as fexpr |
| 14 |
from . import version as fver |
| 15 |
|
| 16 |
|
| 17 |
_p_comp_num: Final = pyp.Word(pyp.srange("[0-9]")) |
| 18 |
|
| 19 |
_p_comp_rest: Final = pyp.Word(pyp.srange("[A-Za-z~-]"), pyp.srange("[0-9A-Za-z~-]")) |
| 20 |
|
| 21 |
_p_version_comp: Final = ( |
| 22 |
_p_comp_num.set_results_name("num") + pyp.Opt(_p_comp_rest.set_results_name("rest_first")) |
| 23 |
) | _p_comp_rest.set_results_name("rest_only") |
| 24 |
|
| 25 |
_p_version: Final = _p_version_comp + pyp.ZeroOrMore(pyp.Char(".").suppress() + _p_version_comp) |
| 26 |
|
| 27 |
_p_feature: Final = pyp.Word(pyp.srange("[A-Za-z0-9_-]")) |
| 28 |
|
| 29 |
_p_op_sign: Final = pyp.one_of(["<=", "<", "=", ">=", ">"]) |
| 30 |
|
| 31 |
_p_op_word: Final = pyp.one_of(["le", "lt", "eq", "ge", "gt"]) |
| 32 |
|
| 33 |
_p_op_sign_and_value: Final = ( |
| 34 |
pyp.Opt(pyp.White()).suppress() + _p_op_sign + pyp.Opt(pyp.White()).suppress() + _p_version |
| 35 |
) |
| 36 |
|
| 37 |
_p_op_word_and_value: Final = ( |
| 38 |
pyp.White().suppress() + _p_op_word + pyp.White().suppress() + _p_version |
| 39 |
) |
| 40 |
|
| 41 |
_p_expr: Final = _p_feature + pyp.Opt(_p_op_sign_and_value | _p_op_word_and_value) |
| 42 |
|
| 43 |
_p_feature_version: Final = _p_feature + pyp.Opt(pyp.Literal("=").suppress() + _p_version) |
| 44 |
|
| 45 |
_p_features_line: Final = _p_feature_version + pyp.ZeroOrMore( |
| 46 |
pyp.White().suppress() + _p_feature_version, |
| 47 |
) |
| 48 |
|
| 49 |
|
| 50 |
@_p_version_comp.set_parse_action |
| 51 |
def _process_version_comp(tokens: pyp.ParseResults) -> fver.VersionComponent: |
| 52 |
"""Build a `VersionComponent` object out of the numeric and string parts.""" |
| 53 |
tok_dict: Final[dict[str, str]] = tokens.as_dict() |
| 54 |
num_str: Final = tok_dict.get("num") |
| 55 |
rest: Final = tok_dict.get("rest_first", tok_dict.get("rest_only", "")) |
| 56 |
return fver.VersionComponent(num=int(num_str) if num_str is not None else None, rest=rest) |
| 57 |
|
| 58 |
|
| 59 |
@_p_version.set_parse_action |
| 60 |
def _process_version(tokens: pyp.ParseResults) -> fver.Version: |
| 61 |
"""Build a `Version` object out of the version components.""" |
| 62 |
res: Final = tokens.as_list() |
| 63 |
if not all(isinstance(comp, fver.VersionComponent) for comp in res): |
| 64 |
raise ParseError(2, f"Weird version parse result: {res!r}") |
| 65 |
|
| 66 |
return fver.Version(value=".".join(str(comp) for comp in res), components=res) |
| 67 |
|
| 68 |
|
| 69 |
@_p_op_sign.set_parse_action |
| 70 |
def _parse_op_sign(tokens: pyp.ParseResults) -> fexpr.BoolOp: |
| 71 |
"""Parse a boolean operation written as a sign ("<", ">=", etc).""" |
| 72 |
return fexpr.OPS[tokens[0]] |
| 73 |
|
| 74 |
|
| 75 |
@_p_op_word.set_parse_action |
| 76 |
def _parse_op_word(tokens: pyp.ParseResults) -> fexpr.BoolOp: |
| 77 |
"""Parse a boolean operation written as a sign ("lt", "ge", etc).""" |
| 78 |
return fexpr.OPS[tokens[0]] |
| 79 |
|
| 80 |
|
| 81 |
@_p_expr.set_parse_action |
| 82 |
def _parse_expr(tokens: pyp.ParseResults) -> defs.Mode: |
| 83 |
"""Build a `Mode` out of a single feature name or a simple expression.""" |
| 84 |
res: Final = tokens.as_list() |
| 85 |
match res: |
| 86 |
case [feature_name] if isinstance(feature_name, str): |
| 87 |
return defs.ModeSingle(feature=feature_name, ast=fexpr.ExprFeature(feature_name)) |
| 88 |
|
| 89 |
case [feature_name, cmp_op, ver] if ( |
| 90 |
isinstance(feature_name, str) |
| 91 |
and isinstance( |
| 92 |
cmp_op, |
| 93 |
fexpr.BoolOp, |
| 94 |
) |
| 95 |
and isinstance(ver, fver.Version) |
| 96 |
): |
| 97 |
return defs.ModeSimple( |
| 98 |
ast=fexpr.ExprOp( |
| 99 |
op=cmp_op, |
| 100 |
args=[fexpr.ExprFeature(feature_name), fexpr.ExprVersion(ver)], |
| 101 |
), |
| 102 |
) |
| 103 |
|
| 104 |
raise ParseError(2, f"Weird expr parse results: {res!r}") |
| 105 |
|
| 106 |
|
| 107 |
@_p_feature_version.set_parse_action |
| 108 |
def _parse_feature_version(tokens: pyp.ParseResults) -> tuple[str, fver.Version]: |
| 109 |
"""Parse a feature name and a version, defaulting to "1.0".""" |
| 110 |
res: Final = tokens.as_list() |
| 111 |
match res: |
| 112 |
case [feature] if isinstance(feature, str): |
| 113 |
return (feature, parse_version("1.0")) |
| 114 |
|
| 115 |
case [feature, ver] if isinstance(feature, str) and isinstance(ver, fver.Version): |
| 116 |
return (feature, ver) |
| 117 |
|
| 118 |
raise ParseError(2, f"Weird feature/version parse results: {res!r}") |
| 119 |
|
| 120 |
|
| 121 |
@_p_features_line.set_parse_action |
| 122 |
def _parse_features_line(tokens: pyp.ParseResults) -> dict[str, fver.Version]: |
| 123 |
"""Build a features dictionary out of the parsed name/version tuples.""" |
| 124 |
|
| 125 |
# We lie a little bit, or mypy won't be happy. |
| 126 |
def validate_pair(pair: tuple[str, fver.Version]) -> tuple[str, fver.Version]: |
| 127 |
"""Validate a single parsed result.""" |
| 128 |
match pair: |
| 129 |
case (name, value) if isinstance(name, str) and isinstance(value, fver.Version): |
| 130 |
return name, value |
| 131 |
|
| 132 |
raise ParseError(2, f"Weird features line parse result: {pair!r}") |
| 133 |
|
| 134 |
res: Final = tokens.as_list() |
| 135 |
return dict(validate_pair(pair) for pair in res) |
| 136 |
|
| 137 |
|
| 138 |
_p_version_complete: Final = _p_version.leave_whitespace() |
| 139 |
|
| 140 |
_p_expr_complete: Final = _p_expr.leave_whitespace() |
| 141 |
|
| 142 |
_p_features_line_complete: Final = _p_features_line.leave_whitespace() |
| 143 |
|
| 144 |
|
| 145 |
class ParseError(defs.FCError): |
| 146 |
"""An error that occurred while parsing the expression.""" |
| 147 |
|
| 148 |
|
| 149 |
def parse_version(value: str) -> fver.Version: |
| 150 |
"""Parse a version string into a `Version` object.""" |
| 151 |
res: Final = _p_version_complete.parse_string(value).as_list() |
| 152 |
match res: |
| 153 |
case [ver] if isinstance(ver, fver.Version) and ver.value == value: |
| 154 |
return ver |
| 155 |
|
| 156 |
case [ver]: |
| 157 |
raise ParseError( |
| 158 |
2, |
| 159 |
f"Could not parse the whole of {value!r} as a version string " |
| 160 |
f"(parsed {ver!r} from {res!r})", |
| 161 |
) |
| 162 |
|
| 163 |
raise ParseError(2, f"Could not parse {value!r} as a version string (result: {res!r})") |
| 164 |
|
| 165 |
|
| 166 |
def parse_expr(expr: str) -> defs.Mode: |
| 167 |
"""Parse a simple "feature-name op version" expression. |
| 168 |
|
| 169 |
If the expression is valid, return an `Expr` object corresponding |
| 170 |
to the specified check. Use this object's `evaluate()` method and |
| 171 |
pass a features dictionary as returned by the `obtain_features()` |
| 172 |
function to get a `Result` object; for simple expressions it will be |
| 173 |
a `ResultBool` object with a boolean `value` member. |
| 174 |
|
| 175 |
from feature_check import expr as fexpr |
| 176 |
from feature_check import obtain as fobtain |
| 177 |
|
| 178 |
data = fobtain.obtain_features("timelimit"); |
| 179 |
expr = fexpr.parse_simple("subsecond > 0") |
| 180 |
print(expr.evaluate(data).value) |
| 181 |
""" |
| 182 |
res: Final = _p_expr_complete.parse_string(expr).as_list() |
| 183 |
match res: |
| 184 |
case [mode] if isinstance(mode, defs.Mode): |
| 185 |
return mode |
| 186 |
|
| 187 |
raise ParseError(2, f"Could not parse {expr!r} as an expression (results: {res!r})") |
| 188 |
|
| 189 |
|
| 190 |
def parse_features_line(features_line: str) -> dict[str, fver.Version]: |
| 191 |
"""Parse the features list, default to version "1.0".""" |
| 192 |
try: |
| 193 |
res: Final = _p_features_line_complete.parse_string(features_line).as_list() |
| 194 |
except pyp.exceptions.ParseBaseException as err: |
| 195 |
raise ParseError(2, f"Could not parse {features_line!r} as a features line: {err}") from err |
| 196 |
match res: |
| 197 |
case [features] if isinstance(features, dict): |
| 198 |
return features |
| 199 |
|
| 200 |
raise ParseError( |
| 201 |
2, |
| 202 |
f"Could not parse {features_line!r} as a features line (results: {res!r})", |
| 203 |
) |