Debian Codegraph @

mesonbuild/interpreterbase/baseobjects.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2013-2021 The Meson development team
3
4 from __future__ import annotations
5
6 from .. import mparser
7 from .exceptions import InvalidCode, InvalidArguments
8 from .helpers import flatten, resolve_second_level_holders
9 from .operator import MesonOperator
10 from ..mesonlib import HoldableObject, MesonBugException, SimpleABC, SubProject, ROOT_SUBPROJECT
11 import textwrap
12
13 import typing as T
14 from contextlib import AbstractContextManager
15
16 if T.TYPE_CHECKING:
17 from typing_extensions import TypeAlias
18
19 # Object holders need the actual interpreter
20 from ..interpreter import Interpreter
21
22
23 TV_func = T.TypeVar('TV_func', bound=T.Callable[..., T.Any])
24
25 TYPE_elementary: TypeAlias = T.Union[str, int, bool, T.Sequence['TYPE_elementary'], T.Dict[str, 'TYPE_elementary']]
26 TYPE_var: TypeAlias = T.Union[TYPE_elementary, HoldableObject, 'MesonInterpreterObject', T.Sequence['TYPE_var'], T.Dict[str, 'TYPE_var']]
27 TYPE_nvar = T.Union[TYPE_var, mparser.BaseNode]
28 TYPE_kwargs = T.Dict[str, TYPE_var]
29 TYPE_nkwargs = T.Dict[str, TYPE_nvar]
30 TYPE_key_resolver = T.Callable[[mparser.BaseNode], str]
31 TYPE_op_arg = T.TypeVar('TYPE_op_arg', bound='TYPE_var', contravariant=True)
32 TYPE_op_func = T.Callable[[TYPE_op_arg, TYPE_op_arg], TYPE_var]
33 TYPE_method_func = T.Callable[['InterpreterObject', T.List[TYPE_var], TYPE_kwargs], TYPE_var]
34
35 class InterpreterObject:
36 TRIVIAL_OPERATORS: T.Dict[
37 MesonOperator,
38 T.Tuple[
39 T.Union[T.Type, T.Tuple[T.Type, ...]],
40 TYPE_op_func
41 ]
42 ] = {}
43
44 OPERATORS: T.Dict[MesonOperator, TYPE_op_func] = {}
45
46 METHODS: T.Dict[
47 str,
48 TYPE_method_func,
49 ] = {}
50
51 def __init_subclass__(cls: T.Type[InterpreterObject], **kwargs: T.Any) -> None:
52 super().__init_subclass__(**kwargs)
53 saved_trivial_operators = cls.TRIVIAL_OPERATORS
54
55 cls.METHODS = {}
56 cls.OPERATORS = {}
57 cls.TRIVIAL_OPERATORS = {}
58
59 # Compute inherited operators and methods according to the Python resolution
60 # order. Reverse the result of mro() because update() will overwrite entries
61 # that are set by the superclass with those that are set by the subclass.
62 for superclass in reversed(cls.mro()[1:]):
63 if superclass is InterpreterObject:
64 # InterpreterObject cannot use @InterpreterObject.operator because
65 # __init_subclass__ does not operate on InterpreterObject itself
66 cls.OPERATORS.update({
67 MesonOperator.EQUALS: InterpreterObject.op_equals,
68 MesonOperator.NOT_EQUALS: InterpreterObject.op_not_equals
69 })
70
71 elif issubclass(superclass, InterpreterObject):
72 cls.METHODS.update(superclass.METHODS)
73 cls.OPERATORS.update(superclass.OPERATORS)
74 cls.TRIVIAL_OPERATORS.update(superclass.TRIVIAL_OPERATORS)
75
76 for name, method in cls.__dict__.items():
77 if hasattr(method, 'meson_method'):
78 cls.METHODS[method.meson_method] = method
79 if hasattr(method, 'meson_operator'):
80 cls.OPERATORS[method.meson_operator] = method
81 cls.TRIVIAL_OPERATORS.update(saved_trivial_operators)
82
83 @staticmethod
84 def method(name: str) -> T.Callable[[TV_func], TV_func]:
85 '''Decorator that tags a Python method as the implementation of a method
86 for the Meson interpreter'''
87 def decorator(f: TV_func) -> TV_func:
88 f.meson_method = name # type: ignore[attr-defined]
89 return f
90 return decorator
91
92 @staticmethod
93 def operator(op: MesonOperator) -> T.Callable[[TV_func], TV_func]:
94 '''Decorator that tags a method as the implementation of an operator
95 for the Meson interpreter'''
96 def decorator(f: TV_func) -> TV_func:
97 f.meson_operator = op # type: ignore[attr-defined]
98 return f
99 return decorator
100
101 def __init__(self, *, subproject: T.Optional['SubProject'] = None) -> None:
102 # Current node set during a method call. This can be used as location
103 # when printing a warning message during a method call.
104 self.current_node: mparser.BaseNode = None
105 self.subproject = subproject or ROOT_SUBPROJECT
106
107 # The type of the object that can be printed to the user
108 def display_name(self) -> str:
109 return type(self).__name__
110
111 def method_call(
112 self,
113 method_name: str,
114 args: T.List[TYPE_var],
115 kwargs: TYPE_kwargs
116 ) -> TYPE_var:
117 if method_name in self.METHODS:
118 method = self.METHODS[method_name]
119 if not getattr(method, 'no-args-flattening', False):
120 args = flatten(args)
121 if not getattr(method, 'no-second-level-holder-flattening', False):
122 args, kwargs = resolve_second_level_holders(args, kwargs)
123 return method(self, args, kwargs)
124
125 ustr = f'Unknown method "{method_name}" in object {self} of type {type(self).__name__}.'
126 from difflib import get_close_matches
127 close_matches = get_close_matches(method_name, self.METHODS)
128 if close_matches:
129 ustr += f' Did you mean "{close_matches[0]}"?'
130 raise InvalidCode(ustr)
131
132 def operator_call(self, operator: MesonOperator, other: TYPE_var) -> TYPE_var:
133 if operator in self.TRIVIAL_OPERATORS:
134 op = self.TRIVIAL_OPERATORS[operator]
135 if op[0] is None and other is not None:
136 raise MesonBugException(f'The unary operator `{operator.value}` of {self.display_name()} was passed the object {other} of type {type(other).__name__}')
137 if op[0] is not None and not isinstance(other, op[0]):
138 raise InvalidArguments(f'The `{operator.value}` operator of {self.display_name()} does not accept objects of type {type(other).__name__} ({other})')
139 return op[1](self, other)
140 if operator in self.OPERATORS:
141 return self.OPERATORS[operator](self, other)
142
143 raise InvalidCode(f'Object {self} of type {self.display_name()} does not support the `{operator.value}` operator.')
144
145 # Default comparison operator support
146 def _throw_comp_exception(self, other: TYPE_var, opt_type: str) -> T.NoReturn:
147 raise InvalidArguments(textwrap.dedent(
148 f'''
149 Trying to compare values of different types ({self.display_name()}, {type(other).__name__}) using {opt_type}.
150 This was deprecated and undefined behavior previously and is as of 0.60.0 a hard error.
151 '''
152 ))
153
154 def op_equals(self, other: TYPE_var) -> bool:
155 # We use `type(...) == type(...)` here to enforce an *exact* match for comparison. We
156 # don't want comparisons to be possible where `isinstance(derived_obj, type(base_obj))`
157 # would pass because this comparison must never be true: `derived_obj == base_obj`
158 if type(self) is not type(other):
159 self._throw_comp_exception(other, '==')
160 return self == other
161
162 def op_not_equals(self, other: TYPE_var) -> bool:
163 if type(self) is not type(other):
164 self._throw_comp_exception(other, '!=')
165 return self != other
166
167 class MesonInterpreterObject(InterpreterObject):
168 ''' All non-elementary objects and non-object-holders should be derived from this '''
169
170 class MutableInterpreterObject:
171 ''' Dummy class to mark the object type as mutable '''
172
173 class UnknownValue(MesonInterpreterObject):
174 '''This class is only used for the rewriter/static introspection tool and
175 indicates that a value cannot be determined statically, either because of
176 limitations in our code or because the value differs from machine to
177 machine.'''
178
179 class UndefinedVariable(MesonInterpreterObject):
180 '''This class is only used for the rewriter/static introspection tool and
181 represents the `value` a meson-variable has if it was never written to.'''
182
183 HoldableTypes = (HoldableObject, int, bool, str, list, dict)
184 TYPE_HoldableTypes = T.Union[TYPE_var, HoldableObject]
185 InterpreterObjectTypeVar = T.TypeVar('InterpreterObjectTypeVar', bound=TYPE_HoldableTypes)
186
187 class ObjectHolder(InterpreterObject, T.Generic[InterpreterObjectTypeVar]):
188 def __init__(self, obj: InterpreterObjectTypeVar, interpreter: 'Interpreter') -> None:
189 super().__init__(subproject=interpreter.subproject)
190 # This causes some type checkers to assume that obj is a base
191 # HoldableObject, not the specialized type, so only do this assert in
192 # non-type checking situations
193 if not T.TYPE_CHECKING:
194 assert isinstance(obj, HoldableTypes), f'This is a bug: Trying to hold object of type `{type(obj).__name__}` that is not in `{HoldableTypes}`'
195 self.held_object = obj
196 self.interpreter = interpreter
197 self.env = self.interpreter.environment
198
199 # Hide the object holder abstraction from the user
200 def display_name(self) -> str:
201 return type(self.held_object).__name__
202
203 # Override default comparison operators for the held object
204 @InterpreterObject.operator(MesonOperator.EQUALS)
205 def op_equals(self, other: TYPE_var) -> bool:
206 # See the comment from InterpreterObject why we are using `type()` here.
207 if type(self.held_object) is not type(other):
208 self._throw_comp_exception(other, '==')
209 return self.held_object == other
210
211 @InterpreterObject.operator(MesonOperator.NOT_EQUALS)
212 def op_not_equals(self, other: TYPE_var) -> bool:
213 if type(self.held_object) is not type(other):
214 self._throw_comp_exception(other, '!=')
215 return self.held_object != other
216
217 def __repr__(self) -> str:
218 return f'<[{type(self).__name__}] holds [{type(self.held_object).__name__}]: {self.held_object!r}>'
219
220 class IterableObject(metaclass=SimpleABC):
221 '''Base class for all objects that can be iterated over in a foreach loop'''
222
223 def iter_tuple_size(self) -> T.Optional[int]:
224 '''Return the size of the tuple for each iteration. Returns None if only a single value is returned.'''
225 raise MesonBugException(f'iter_tuple_size not implemented for {self.__class__.__name__}')
226
227 def iter_self(self) -> T.Iterator[T.Union[TYPE_var, T.Tuple[TYPE_var, ...]]]:
228 raise MesonBugException(f'iter not implemented for {self.__class__.__name__}')
229
230 def size(self) -> int:
231 raise MesonBugException(f'size not implemented for {self.__class__.__name__}')
232
233 class ContextManagerObject(MesonInterpreterObject, AbstractContextManager):
234 def __init__(self, subproject: 'SubProject') -> None:
235 super().__init__(subproject=subproject)
236
237
238 class DefaultObject(MesonInterpreterObject):
239 """A default value to a keyword argument."""