| 
 | 1 | +# SPDX-FileCopyrightText: 2023 The meson-python developers  | 
 | 2 | +#  | 
 | 3 | +# SPDX-License-Identifier: MIT  | 
 | 4 | + | 
 | 5 | +from __future__ import annotations  | 
 | 6 | + | 
 | 7 | +import ast  | 
 | 8 | +import operator  | 
 | 9 | +import string  | 
 | 10 | +import sys  | 
 | 11 | +import typing  | 
 | 12 | + | 
 | 13 | + | 
 | 14 | +if typing.TYPE_CHECKING:  # pragma: no cover  | 
 | 15 | +    from typing import Any, Callable, Iterator, Mapping, Optional, Type  | 
 | 16 | + | 
 | 17 | + | 
 | 18 | +_methods = {}  | 
 | 19 | + | 
 | 20 | + | 
 | 21 | +def _register(nodetype: Type[ast.AST]) -> Callable[..., Callable[..., Any]]:  | 
 | 22 | +    def closure(method: Callable[[Interpreter, ast.AST], Any]) -> Callable[[Interpreter, ast.AST], Any]:  | 
 | 23 | +        _methods[nodetype] = method  | 
 | 24 | +        return method  | 
 | 25 | +    return closure  | 
 | 26 | + | 
 | 27 | + | 
 | 28 | +class Interpreter(typing.Mapping[str, object]):  | 
 | 29 | + | 
 | 30 | +    _operators = {  | 
 | 31 | +        ast.Add: operator.add,  | 
 | 32 | +        ast.Sub: operator.sub,  | 
 | 33 | +        ast.Mult: operator.mul,  | 
 | 34 | +        ast.Div: operator.truediv,  | 
 | 35 | +        ast.FloorDiv: operator.floordiv,  | 
 | 36 | +    }  | 
 | 37 | + | 
 | 38 | +    def __init__(self, variables: Mapping[str, Any]):  | 
 | 39 | +        self._variables = variables  | 
 | 40 | + | 
 | 41 | +    def eval(self, string: str) -> Any:  | 
 | 42 | +        try:  | 
 | 43 | +            expr = ast.parse(string, mode='eval')  | 
 | 44 | +            return self._eval(expr)  | 
 | 45 | +        except KeyError as exc:  | 
 | 46 | +            raise ValueError(f'unknown variable "{exc.args[0]}"') from exc  | 
 | 47 | +        except NotImplementedError as exc:  | 
 | 48 | +            raise ValueError(f'invalid expression {string!r}') from exc  | 
 | 49 | + | 
 | 50 | +    __getitem__ = eval  | 
 | 51 | + | 
 | 52 | +    def __len__(self) -> int:  | 
 | 53 | +        return len(self._variables)  | 
 | 54 | + | 
 | 55 | +    def __iter__(self) -> Iterator[str]:  | 
 | 56 | +        return iter(self._variables)  | 
 | 57 | + | 
 | 58 | +    def _eval(self, node: ast.AST) -> Any:  | 
 | 59 | +        # Cannot use functools.singlemethoddispatch as long as Python 3.7 is supported.  | 
 | 60 | +        method = _methods.get(type(node), None)  | 
 | 61 | +        if method is None:  | 
 | 62 | +            raise NotImplementedError  | 
 | 63 | +        return method(self, node)  | 
 | 64 | + | 
 | 65 | +    @_register(ast.Expression)  | 
 | 66 | +    def _expression(self, node: ast.Expression) -> Any:  | 
 | 67 | +        return self._eval(node.body)  | 
 | 68 | + | 
 | 69 | +    @_register(ast.BinOp)  | 
 | 70 | +    def _binop(self, node: ast.BinOp) -> Any:  | 
 | 71 | +        func = self._operators.get(type(node.op))  | 
 | 72 | +        if func is None:  | 
 | 73 | +            raise NotImplementedError  | 
 | 74 | +        return func(self._eval(node.left), self._eval(node.right))  | 
 | 75 | + | 
 | 76 | +    @_register(ast.Constant)  | 
 | 77 | +    def _constant(self, node: ast.Constant) -> Any:  | 
 | 78 | +        return node.value  | 
 | 79 | + | 
 | 80 | +    if sys.version_info < (3, 8):  | 
 | 81 | + | 
 | 82 | +        # Python 3.7, replaced by ast.Constant is later versions.  | 
 | 83 | +        @_register(ast.Num)  | 
 | 84 | +        def _num(self, node: ast.Num) -> Any:  | 
 | 85 | +            return node.n  | 
 | 86 | + | 
 | 87 | +        # Python 3.7, replaced by ast.Constant is later versions.  | 
 | 88 | +        @_register(ast.Str)  | 
 | 89 | +        def _str(self, node: ast.Str) -> Any:  | 
 | 90 | +            return node.s  | 
 | 91 | + | 
 | 92 | +    @_register(ast.Name)  | 
 | 93 | +    def _variable(self, node: ast.Name) -> Any:  | 
 | 94 | +        value = self._variables[node.id]  | 
 | 95 | +        if callable(value):  | 
 | 96 | +            value = value()  | 
 | 97 | +        return value  | 
 | 98 | + | 
 | 99 | + | 
 | 100 | +def _ncores() -> int:  | 
 | 101 | +    return 42  | 
 | 102 | + | 
 | 103 | + | 
 | 104 | +class Template(string.Template):  | 
 | 105 | +    braceidpattern = r'[^}]+'  | 
 | 106 | + | 
 | 107 | + | 
 | 108 | +def eval(template: str, variables: Optional[Mapping[str, Any]] = None) -> str:  | 
 | 109 | +    if variables is None:  | 
 | 110 | +        variables = {'ncores': _ncores}  | 
 | 111 | +    return Template(template).substitute(Interpreter(variables))  | 
0 commit comments