Debian Codegraph @

mesonbuild/interpreterbase/decorators.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 coredata, mesonlib, mlog
7 from .disabler import Disabler
8 from .baseobjects import DefaultObject
9 from .exceptions import InterpreterException, InvalidArguments
10 from ._unholder import _unholder
11
12 from functools import wraps
13 import abc
14 import itertools
15 import copy
16 import typing as T
17
18 if T.TYPE_CHECKING:
19 from typing_extensions import Protocol, TypeAlias, TypeIs
20
21 from .. import mparser
22 from ..mesonlib import SubProject
23 from ..modules import ModuleObject, ModuleState
24 from ..mparser import FunctionNode
25 from ..optinterpreter import OptionInterpreter
26 from .baseobjects import InterpreterObject, ObjectHolder, TV_func, TYPE_var, TYPE_kwargs
27 from .interpreterbase import InterpreterBase
28 from .operator import MesonOperator
29
30 _TV_IntegerObject = T.TypeVar('_TV_IntegerObject', bound=InterpreterObject, contravariant=True)
31 _TV_ARG1 = T.TypeVar('_TV_ARG1', bound=TYPE_var, contravariant=True)
32
33 class FN_Operator(Protocol[_TV_IntegerObject, _TV_ARG1]):
34 def __call__(s, self: _TV_IntegerObject, other: _TV_ARG1) -> TYPE_var: ...
35 _TV_FN_Operator = T.TypeVar('_TV_FN_Operator', bound=FN_Operator)
36
37 CalleeArgs: TypeAlias = T.Tuple[mparser.BaseNode, T.Optional[T.List[TYPE_var]], T.Optional[TYPE_kwargs], SubProject]
38
39 MesonVersionTarget = mesonlib.Range[mesonlib.Version] | mesonlib.NoProjectVersion | None
40
41
42 def is_module(obj: object) -> TypeIs[ModuleObject]:
43 return not hasattr(obj, 'current_node')
44
45
46 @T.overload
47 def get_callee_args(wrapped_args: T.Tuple[InterpreterObject, T.List[TYPE_var], TYPE_kwargs]) -> CalleeArgs: ...
48
49
50 @T.overload
51 def get_callee_args(wrapped_args: T.Tuple[ObjectHolder, object]) -> CalleeArgs: ...
52
53
54 @T.overload
55 def get_callee_args(wrapped_args: T.Tuple[InterpreterBase, FunctionNode, T.List[TYPE_var], TYPE_kwargs]) -> CalleeArgs: ...
56
57
58 @T.overload
59 def get_callee_args(wrapped_args: T.Tuple[ModuleObject, ModuleState, T.List[TYPE_var], TYPE_kwargs]) -> CalleeArgs: ...
60
61
62 @T.overload
63 def get_callee_args(wrapped_args: T.Tuple[OptionInterpreter, str, str, T.List[TYPE_var], TYPE_kwargs]) -> CalleeArgs: ...
64
65
66 def get_callee_args(wrapped_args: T.Union[
67 T.Tuple[InterpreterObject, T.List[TYPE_var], TYPE_kwargs],
68 T.Tuple[ObjectHolder, object],
69 T.Tuple[InterpreterBase, FunctionNode, T.List[TYPE_var], TYPE_kwargs],
70 T.Tuple[ModuleObject, ModuleState, T.List[TYPE_var], TYPE_kwargs],
71 T.Tuple[OptionInterpreter, str, str, T.List[TYPE_var], TYPE_kwargs],
72 ]) -> CalleeArgs:
73 if is_module(wrapped_args[0]):
74 s = wrapped_args[1]
75 else:
76 s = wrapped_args[0]
77 node = s.current_node
78 subproject = s.subproject
79 args: T.Optional[T.List[TYPE_var]] = None
80 kwargs: T.Optional[TYPE_kwargs] = None
81 if len(wrapped_args) >= 3:
82 args = wrapped_args[-2]
83 kwargs = wrapped_args[-1]
84 return node, args, kwargs, subproject
85
86
87 def noPosargs(f: TV_func) -> TV_func:
88 @wraps(f)
89 def wrapped(*wrapped_args: T.Any, **wrapped_kwargs: T.Any) -> T.Any:
90 args = get_callee_args(wrapped_args)[1]
91 if args:
92 raise InvalidArguments('Function does not take positional arguments.')
93 return f(*wrapped_args, **wrapped_kwargs)
94 return T.cast('TV_func', wrapped)
95
96 def noKwargs(f: TV_func) -> TV_func:
97 @wraps(f)
98 def wrapped(*wrapped_args: T.Any, **wrapped_kwargs: T.Any) -> T.Any:
99 kwargs = get_callee_args(wrapped_args)[2]
100 if kwargs:
101 raise InvalidArguments('Function does not take keyword arguments.')
102 return f(*wrapped_args, **wrapped_kwargs)
103 return T.cast('TV_func', wrapped)
104
105 def noArgsFlattening(f: TV_func) -> TV_func:
106 setattr(f, 'no-args-flattening', True) # noqa: B010
107 return f
108
109 def noSecondLevelHolderResolving(f: TV_func) -> TV_func:
110 setattr(f, 'no-second-level-holder-flattening', True) # noqa: B010
111 return f
112
113 def unholder_return(f: TV_func) -> T.Callable[..., TYPE_var]:
114 @wraps(f)
115 def wrapped(*wrapped_args: T.Any, **wrapped_kwargs: T.Any) -> T.Any:
116 res = f(*wrapped_args, **wrapped_kwargs)
117 return _unholder(res)
118 return T.cast('T.Callable[..., TYPE_var]', wrapped)
119
120 def disablerIfNotFound(f: TV_func) -> TV_func:
121 @wraps(f)
122 def wrapped(*wrapped_args: T.Any, **wrapped_kwargs: T.Any) -> T.Any:
123 kwargs = get_callee_args(wrapped_args)[2]
124 disabler = kwargs.pop('disabler', False)
125 ret = f(*wrapped_args, **wrapped_kwargs)
126 if disabler and not ret.found():
127 return Disabler()
128 return ret
129 return T.cast('TV_func', wrapped)
130
131 def kwargs_get_close_matches(invalid_kwargs: T.Set[str], valid_kwargs: T.Set[str]) -> T.List[str]:
132 with_close_matches = []
133 from difflib import get_close_matches
134 for invalid in sorted(invalid_kwargs):
135 close_matches = get_close_matches(invalid, valid_kwargs)
136 with_close_matches.append(f'"{invalid}" (did you mean "{close_matches[0]}"?)' if close_matches else f'"{invalid}"')
137 return with_close_matches
138
139 def typed_operator(operator: MesonOperator,
140 types: T.Union[T.Type, T.Tuple[T.Type, ...]]) -> T.Callable[['_TV_FN_Operator'], '_TV_FN_Operator']:
141 """Decorator that does type checking for operator calls.
142
143 The principle here is similar to typed_pos_args, however much simpler
144 since only one other object ever is passed
145 """
146 def inner(f: '_TV_FN_Operator') -> '_TV_FN_Operator':
147 @wraps(f)
148 def wrapper(self: 'InterpreterObject', other: TYPE_var) -> TYPE_var:
149 if not isinstance(other, types):
150 raise InvalidArguments(f'The `{operator.value}` of {self.display_name()} does not accept objects of type {type(other).__name__} ({other})')
151 return f(self, other)
152 return T.cast('_TV_FN_Operator', wrapper)
153 return inner
154
155
156 def typed_pos_args(name: str, *types: T.Union[T.Type, T.Tuple[T.Type, ...]],
157 varargs: T.Optional[T.Union[T.Type, T.Tuple[T.Type, ...]]] = None,
158 optargs: T.Optional[T.List[T.Union[T.Type, T.Tuple[T.Type, ...]]]] = None,
159 min_varargs: int = 0, max_varargs: int = 0) -> T.Callable[..., T.Any]:
160 """Decorator that types type checking of positional arguments.
161
162 This supports two different models of optional arguments, the first is the
163 variadic argument model. Variadic arguments are a possibly bounded,
164 possibly unbounded number of arguments of the same type (unions are
165 supported). The second is the standard default value model, in this case
166 a number of optional arguments may be provided, but they are still
167 ordered, and they may have different types.
168
169 This function does not support mixing variadic and default arguments.
170
171 :name: The name of the decorated function (as displayed in error messages)
172 :varargs: They type(s) of any variadic arguments the function takes. If
173 None the function takes no variadic args
174 :min_varargs: the minimum number of variadic arguments taken
175 :max_varargs: the maximum number of variadic arguments taken. 0 means unlimited
176 :optargs: The types of any optional arguments parameters taken. If None
177 then no optional parameters are taken.
178
179 Some examples of usage blow:
180 >>> @typed_pos_args('mod.func', str, (str, int))
181 ... def func(self, state: ModuleState, args: T.Tuple[str, T.Union[str, int]], kwargs: T.Dict[str, T.Any]) -> T.Any:
182 ... pass
183
184 >>> @typed_pos_args('method', str, varargs=str)
185 ... def method(self, node: BaseNode, args: T.Tuple[str, T.List[str]], kwargs: T.Dict[str, T.Any]) -> T.Any:
186 ... pass
187
188 >>> @typed_pos_args('method', varargs=str, min_varargs=1)
189 ... def method(self, node: BaseNode, args: T.Tuple[T.List[str]], kwargs: T.Dict[str, T.Any]) -> T.Any:
190 ... pass
191
192 >>> @typed_pos_args('method', str, optargs=[(str, int), str])
193 ... def method(self, node: BaseNode, args: T.Tuple[str, T.Optional[T.Union[str, int]], T.Optional[str]], kwargs: T.Dict[str, T.Any]) -> T.Any:
194 ... pass
195
196 When should you chose `typed_pos_args('name', varargs=str,
197 min_varargs=1)` vs `typed_pos_args('name', str, varargs=str)`?
198
199 The answer has to do with the semantics of the function, if all of the
200 inputs are the same type (such as with `files()`) then the former is
201 correct, all of the arguments are string names of files. If the first
202 argument is something else the it should be separated.
203 """
204 def inner(f: TV_func) -> TV_func:
205
206 @wraps(f)
207 def wrapper(*wrapped_args: T.Any, **wrapped_kwargs: T.Any) -> T.Any:
208 args = get_callee_args(wrapped_args)[1]
209
210 # These are implementation programming errors, end users should never see them.
211 assert isinstance(args, list), args
212 assert max_varargs >= 0, 'max_varags cannot be negative'
213 assert min_varargs >= 0, 'min_varags cannot be negative'
214 assert optargs is None or varargs is None, \
215 'varargs and optargs not supported together as this would be ambiguous'
216
217 num_args = len(args)
218 num_types = len(types)
219 a_types = types
220 last_pos = num_args
221
222 if varargs:
223 min_args = num_types + min_varargs
224 max_args = num_types + max_varargs
225 if max_varargs == 0 and num_args < min_args:
226 raise InvalidArguments(f'{name} takes at least {min_args} arguments, but got {num_args}.')
227 elif max_varargs != 0 and (num_args < min_args or num_args > max_args):
228 raise InvalidArguments(f'{name} takes between {min_args} and {max_args} arguments, but got {num_args}.')
229 elif optargs:
230 if num_args < num_types:
231 raise InvalidArguments(f'{name} takes at least {num_types} arguments, but got {num_args}.')
232 elif num_args > num_types + len(optargs):
233 raise InvalidArguments(f'{name} takes at most {num_types + len(optargs)} arguments, but got {num_args}.')
234 # Add the number of positional arguments required
235 if num_args > num_types:
236 diff = num_args - num_types
237 a_types = tuple(list(types) + list(optargs[:diff]))
238 elif num_args != num_types:
239 raise InvalidArguments(f'{name} takes exactly {num_types} arguments, but got {num_args}.')
240
241 for i, (arg, type_) in enumerate(itertools.zip_longest(args, a_types, fillvalue=varargs), start=1):
242 if not isinstance(arg, type_):
243 # if DefaultObject is an explicit allowed allowed type allow
244 # it through.
245 if isinstance(arg, DefaultObject):
246 if i >= last_pos:
247 if varargs:
248 msg = 'not allowed for variadic arguments'
249 else:
250 msg = 'not allowed for optional positional arguments'
251 else:
252 msg = 'not allowed for required positional arguments'
253 raise InvalidArguments(f'default() objects are {msg}')
254
255 if isinstance(type_, tuple):
256 shouldbe = 'one of: {}'.format(", ".join(f'"{t.__name__}"' for t in type_))
257 else:
258 shouldbe = f'"{type_.__name__}"'
259 raise InvalidArguments(f'{name} argument {i} was of type "{type(arg).__name__}" but should have been {shouldbe}')
260
261 # Ensure that we're actually passing a tuple.
262 # Depending on what kind of function we're calling the length of
263 # wrapped_args can vary.
264 nargs = list(wrapped_args)
265 i = nargs.index(args)
266 if varargs:
267 # if we have varargs we need to split them into a separate
268 # tuple, as python's typing doesn't understand tuples with
269 # fixed elements and variadic elements, only one or the other.
270 # so in that case we need T.Tuple[int, str, float, T.Tuple[str, ...]]
271 pos = args[:len(types)]
272 var = list(args[len(types):])
273 pos.append(var)
274 nargs[i] = tuple(pos)
275 elif optargs:
276 if num_args < num_types + len(optargs):
277 diff = num_types + len(optargs) - num_args
278 nargs[i] = tuple(list(args) + [None] * diff)
279 else:
280 nargs[i] = tuple(args)
281 else:
282 nargs[i] = tuple(args)
283 return f(*nargs, **wrapped_kwargs)
284
285 return T.cast('TV_func', wrapper)
286 return inner
287
288
289 class ContainerTypeInfo:
290
291 """Container information for keyword arguments.
292
293 For keyword arguments that are containers (list or dict), this class encodes
294 that information.
295
296 :param container: the type of container
297 :param contains: the types the container holds
298 :param pairs: if the container is supposed to be of even length.
299 This is mainly used for interfaces that predate the addition of dictionaries, and use
300 `[key, value, key2, value2]` format.
301 :param allow_empty: Whether this container is allowed to be empty
302 There are some cases where containers not only must be passed, but must
303 not be empty, and other cases where an empty container is allowed.
304 """
305
306 def __init__(self, container: T.Type, contains: T.Union[T.Type, T.Tuple[T.Type, ...]], *,
307 pairs: bool = False, allow_empty: bool = True):
308 self.container = container
309 self.contains = contains
310 self.pairs = pairs
311 self.allow_empty = allow_empty
312
313 def check(self, value: T.Any) -> bool:
314 """Check that a value is valid.
315
316 :param value: A value to check
317 :return: True if it is valid, False otherwise
318 """
319 if not isinstance(value, self.container):
320 return False
321 iter_ = iter(value.values()) if isinstance(value, dict) else iter(value)
322 if any(not isinstance(i, self.contains) for i in iter_):
323 return False
324 if self.pairs and len(value) % 2 != 0:
325 return False
326 if not value and not self.allow_empty:
327 return False
328 return True
329
330 def check_any(self, value: T.Any) -> bool:
331 """Check a value should emit new/deprecated feature.
332
333 :param value: A value to check
334 :return: True if any of the items in value matches, False otherwise
335 """
336 if not isinstance(value, self.container):
337 return False
338 iter_ = iter(value.values()) if isinstance(value, dict) else iter(value)
339 return any(isinstance(i, self.contains) for i in iter_)
340
341 def description(self) -> str:
342 """Human readable description of this container type.
343
344 :return: string to be printed
345 """
346 container = 'dict' if self.container is dict else 'array'
347 if isinstance(self.contains, tuple):
348 contains = ' | '.join([t.__name__ for t in self.contains])
349 else:
350 contains = self.contains.__name__
351 s = f'{container}[{contains}]'
352 if self.pairs:
353 s += ' that has even size'
354 if not self.allow_empty:
355 s += ' that cannot be empty'
356 return s
357
358 _T = T.TypeVar('_T')
359
360 class _NULL_T:
361 """Special null type for evolution, this is an implementation detail."""
362
363
364 _NULL = _NULL_T()
365
366 class KwargInfo(T.Generic[_T]):
367
368 """A description of a keyword argument to a meson function
369
370 This is used to describe a value to the :func:typed_kwargs function.
371
372 :param name: the name of the parameter
373 :param types: A type or tuple of types that are allowed, or a :class:ContainerType
374 :param required: Whether this is a required keyword argument. defaults to False
375 :param listify: If true, then the argument will be listified before being
376 checked. This is useful for cases where the Meson DSL allows a scalar or
377 a container, but internally we only want to work with containers
378 :param default: A default value to use if this isn't set. defaults to None,
379 this may be safely set to a mutable type, as long as that type does not
380 itself contain mutable types, typed_kwargs will copy the default
381 :param since: Meson version in which this argument has been added. defaults to None
382 :param since_message: An extra message to pass to FeatureNew when since is triggered
383 :param deprecated: Meson version in which this argument has been deprecated. defaults to None
384 :param deprecated_message: An extra message to pass to FeatureDeprecated
385 when since is triggered
386 :param validator: A callable that does additional validation. This is mainly
387 intended for cases where a string is expected, but only a few specific
388 values are accepted. Must return None if the input is valid, or a
389 message if the input is invalid
390 :param convertor: A callable that converts the raw input value into a
391 different type. This is intended for cases such as the meson DSL using a
392 string, but the implementation using an Enum. This should not do
393 validation, just conversion.
394 :param deprecated_values: a dictionary mapping a value to the version of
395 meson it was deprecated in. The Value may be any valid value for this
396 argument.
397 :param since_values: a dictionary mapping a value to the version of meson it was
398 added in.
399 :param not_set_warning: A warning message that is logged if the kwarg is not
400 set by the user.
401 :param feature_validator: A callable returning an iterable of FeatureNew | FeatureDeprecated objects.
402 :param extra_types:
403 A mapping of types to a callable that is passed that type and returns an
404 error message. These types are specifically *not* added to the general
405 error message
406 :param as_default: Extra values to treat as empty values. These are always considered to be broken.
407 """
408 def __init__(self, name: str,
409 types: T.Union[T.Type[_T], T.Tuple[T.Union[T.Type[_T], ContainerTypeInfo], ...], ContainerTypeInfo],
410 *, required: bool = False, listify: bool = False,
411 default: T.Optional[_T] = None,
412 since: T.Optional[str] = None,
413 since_message: T.Optional[str] = None,
414 since_values: T.Optional[T.Dict[T.Union[_T, ContainerTypeInfo, type], T.Union[str, T.Tuple[str, str]]]] = None,
415 deprecated: T.Optional[str] = None,
416 deprecated_message: T.Optional[str] = None,
417 deprecated_values: T.Optional[T.Dict[T.Union[_T, ContainerTypeInfo, type], T.Union[str, T.Tuple[str, str]]]] = None,
418 feature_validator: T.Optional[T.Callable[[_T], T.Iterable[FeatureCheckBase]]] = None,
419 validator: T.Optional[T.Callable[[T.Any], T.Optional[str]]] = None,
420 convertor: T.Optional[T.Callable[[_T], object]] = None,
421 not_set_warning: T.Optional[str] = None,
422 extra_types: T.Optional[T.Mapping[T.Type, T.Callable[[object], str]]] = None,
423 as_default: T.Optional[T.List[T.Tuple[object, T.Union[str, T.Tuple[str, str]]]]] = None):
424 self.name = name
425 self.types = types
426 self.required = required
427 self.listify = listify
428 self.default = default
429 self.since = since
430 self.since_message = since_message
431 self.since_values = since_values
432 self.feature_validator = feature_validator
433 self.deprecated = deprecated
434 self.deprecated_message = deprecated_message
435 self.deprecated_values = deprecated_values
436 self.validator = validator
437 self.convertor = convertor
438 self.not_set_warning = not_set_warning
439 self.extra_types = extra_types if extra_types is not None else {}
440 self.as_default = as_default
441
442 def evolve(self, *,
443 name: T.Union[str, _NULL_T] = _NULL,
444 required: T.Union[bool, _NULL_T] = _NULL,
445 listify: T.Union[bool, _NULL_T] = _NULL,
446 default: T.Union[_T, None, _NULL_T] = _NULL,
447 since: T.Union[str, None, _NULL_T] = _NULL,
448 since_message: T.Union[str, None, _NULL_T] = _NULL,
449 since_values: T.Union[T.Dict[T.Union[_T, ContainerTypeInfo, type], T.Union[str, T.Tuple[str, str]]], None, _NULL_T] = _NULL,
450 deprecated: T.Union[str, None, _NULL_T] = _NULL,
451 deprecated_message: T.Union[str, None, _NULL_T] = _NULL,
452 deprecated_values: T.Union[T.Dict[T.Union[_T, ContainerTypeInfo, type], T.Union[str, T.Tuple[str, str]]], None, _NULL_T] = _NULL,
453 feature_validator: T.Union[T.Callable[[_T], T.Iterable[FeatureCheckBase]], None, _NULL_T] = _NULL,
454 validator: T.Union[T.Callable[[_T], T.Optional[str]], None, _NULL_T] = _NULL,
455 convertor: T.Union[T.Callable[[_T], object], None, _NULL_T] = _NULL,
456 extra_types: T.Union[T.Mapping[T.Type, T.Callable[[object], str]], None, _NULL_T] = _NULL,
457 as_default: T.Union[T.List[T.Tuple[object, T.Union[str, T.Tuple[str, str]]]], None, _NULL_T] = _NULL
458 ) -> 'KwargInfo[_T]':
459 """Create a shallow copy of this KwargInfo, with modifications.
460
461 This allows us to create a new copy of a KwargInfo with modifications.
462 This allows us to use a shared kwarg that implements complex logic, but
463 has slight differences in usage, such as being added to different
464 functions in different versions of Meson.
465
466 The use the _NULL special value here allows us to pass None, which has
467 meaning in many of these cases. _NULL itself is never stored, always
468 being replaced by either the copy in self, or the provided new version.
469 """
470 return type(self)(
471 name if not isinstance(name, _NULL_T) else self.name,
472 self.types,
473 listify=listify if not isinstance(listify, _NULL_T) else self.listify,
474 required=required if not isinstance(required, _NULL_T) else self.required,
475 default=default if not isinstance(default, _NULL_T) else self.default,
476 since=since if not isinstance(since, _NULL_T) else self.since,
477 since_message=since_message if not isinstance(since_message, _NULL_T) else self.since_message,
478 since_values=since_values if not isinstance(since_values, _NULL_T) else self.since_values,
479 deprecated=deprecated if not isinstance(deprecated, _NULL_T) else self.deprecated,
480 deprecated_message=deprecated_message if not isinstance(deprecated_message, _NULL_T) else self.deprecated_message,
481 deprecated_values=deprecated_values if not isinstance(deprecated_values, _NULL_T) else self.deprecated_values,
482 feature_validator=feature_validator if not isinstance(feature_validator, _NULL_T) else self.feature_validator,
483 validator=validator if not isinstance(validator, _NULL_T) else self.validator,
484 convertor=convertor if not isinstance(convertor, _NULL_T) else self.convertor,
485 extra_types=extra_types if not isinstance(extra_types, _NULL_T) else self.extra_types,
486 as_default=as_default if not isinstance(as_default, _NULL_T) else self.as_default,
487 )
488
489
490 def typed_kwargs(name: str, *types: KwargInfo, allow_unknown: bool = False) -> T.Callable[..., T.Any]:
491 """Decorator for type checking keyword arguments.
492
493 Used to wrap a meson DSL implementation function, where it checks various
494 things about keyword arguments, including the type, and various other
495 information. For non-required values it sets the value to a default, which
496 means the value will always be provided.
497
498 If type is a :class:ContainerTypeInfo, then the default value will be
499 passed as an argument to the container initializer, making a shallow copy
500
501 :param name: the name of the function, including the object it's attached to
502 (if applicable)
503 :param *types: KwargInfo entries for each keyword argument.
504 """
505 def inner(f: TV_func) -> TV_func:
506
507 def types_description(types_tuple: T.Tuple[T.Union[T.Type, ContainerTypeInfo], ...]) -> str:
508 candidates = []
509 for t in types_tuple:
510 if isinstance(t, ContainerTypeInfo):
511 candidates.append(t.description())
512 else:
513 candidates.append(t.__name__)
514 shouldbe = 'one of: ' if len(candidates) > 1 else ''
515 shouldbe += ', '.join(candidates)
516 return shouldbe
517
518 def raw_description(t: object) -> str:
519 """describe a raw type (ie, one that is not a ContainerTypeInfo)."""
520 if isinstance(t, list):
521 if t:
522 return f"array[{' | '.join(sorted(mesonlib.OrderedSet(type(v).__name__ for v in t)))}]"
523 return 'array[]'
524 elif isinstance(t, dict):
525 if t:
526 return f"dict[{' | '.join(sorted(mesonlib.OrderedSet(type(v).__name__ for v in t.values())))}]"
527 return 'dict[]'
528 return type(t).__name__
529
530 def check_value_type(types_tuple: T.Tuple[T.Union[T.Type, ContainerTypeInfo], ...],
531 value: T.Any) -> bool:
532 for t in types_tuple:
533 if isinstance(t, ContainerTypeInfo):
534 if t.check(value):
535 return True
536 elif isinstance(value, t):
537 return True
538 return False
539
540 @wraps(f)
541 def wrapper(*wrapped_args: T.Any, **wrapped_kwargs: T.Any) -> T.Any:
542
543 def emit_feature_change(values: T.Dict[_T, T.Union[str, T.Tuple[str, str]]], feature: T.Union[T.Type['FeatureDeprecated'], T.Type['FeatureNew']]) -> None:
544 for n, version in values.items():
545 if isinstance(version, tuple):
546 version, msg = version
547 else:
548 msg = None
549
550 warning: T.Optional[str] = None
551 if isinstance(n, ContainerTypeInfo):
552 if n.check_any(value):
553 warning = f'of type {n.description()}'
554 elif isinstance(n, type):
555 if isinstance(value, n):
556 warning = f'of type {n.__name__}'
557 elif isinstance(value, list):
558 if n in value:
559 warning = f'value "{n}" in list'
560 elif isinstance(value, dict):
561 if n in value:
562 warning = f'value "{n}" in dict keys'
563 elif n == value:
564 warning = f'value "{n}"'
565 if warning:
566 feature.single_use(f'"{name}" keyword argument "{info.name}" {warning}', version, subproject, msg, location=node)
567
568 node, _, _kwargs, subproject = get_callee_args(wrapped_args)
569 # Cast here, as the convertor function may place something other than a TYPE_var in the kwargs
570 kwargs = T.cast('T.Dict[str, object]', _kwargs)
571
572 if not allow_unknown:
573 all_names = {t.name for t in types}
574 unknowns = set(kwargs).difference(all_names)
575 if unknowns:
576 ustr = ', '.join(kwargs_get_close_matches(unknowns, all_names))
577 raise InvalidArguments(f'{name} got unknown keyword arguments {ustr}')
578
579 for info in types:
580 types_tuple = info.types if isinstance(info.types, tuple) else (info.types,)
581 value = kwargs.get(info.name)
582 if isinstance(value, DefaultObject):
583 # Ensure that default() is not used for required options
584 # Otherwise, set the value to None, which will send us down
585 # the "unset" path
586 if info.required:
587 raise InvalidArguments(f'"{name}" got a default() value for the required keyword argument "{info.name}". '
588 'default() may not be used for required keyword arguments.')
589 value = None
590
591 if value is not None:
592 if info.since:
593 feature_name = info.name + ' arg in ' + name
594 FeatureNew.single_use(feature_name, info.since, subproject, info.since_message, location=node)
595 if info.deprecated:
596 feature_name = info.name + ' arg in ' + name
597 FeatureDeprecated.single_use(feature_name, info.deprecated, subproject, info.deprecated_message, location=node)
598 if info.as_default:
599 found = mesonlib.first(info.as_default, lambda x: value == x[0])
600 if found is not None:
601 msg = found[1]
602 extra = ''
603 if isinstance(msg, tuple):
604 msg, extra = msg
605 FeatureBroken.single_use(f"Using '{value}' as an empty value in {info.name}", msg, subproject, extra, node)
606 value = copy.copy(info.default)
607 if info.listify:
608 kwargs[info.name] = value = mesonlib.listify(value)
609 if not check_value_type(types_tuple, value):
610 extra_desc: T.List[str] = []
611 if info.extra_types:
612 if isinstance(value, list):
613 for (t, cb), v in itertools.product(info.extra_types.items(), value):
614 if isinstance(v, t):
615 extra_desc.append(cb(v))
616 else:
617 for t, cb in info.extra_types.items():
618 if isinstance(value, t):
619 extra_desc.append(cb(value))
620
621 shouldbe = types_description(types_tuple)
622 if extra_desc:
623 shouldbe = '{}. {}'.format(shouldbe, '. '.join(extra_desc))
624 raise InvalidArguments(f'{name} keyword argument {info.name!r} was of type {raw_description(value)} but should have been {shouldbe}')
625
626 if info.validator is not None:
627 msg = info.validator(value)
628 if msg is not None:
629 raise InvalidArguments(f'{name} keyword argument "{info.name}" {msg}')
630
631 if info.feature_validator is not None:
632 for each in info.feature_validator(value):
633 each.use(subproject, node)
634
635 if info.deprecated_values is not None:
636 emit_feature_change(info.deprecated_values, FeatureDeprecated)
637
638 if info.since_values is not None:
639 emit_feature_change(info.since_values, FeatureNew)
640
641 elif info.required:
642 raise InvalidArguments(f'{name} is missing required keyword argument "{info.name}"')
643 else:
644 # set the value to the default, this ensuring all kwargs are present
645 # This both simplifies the typing checking and the usage
646 assert check_value_type(types_tuple, info.default), f'In function {name} default value of {info.name} is not a valid type, got {type(info.default)} expected {types_description(types_tuple)}'
647 # Create a shallow copy of the container. This allows mutable
648 # types to be used safely as default values
649 kwargs[info.name] = copy.copy(info.default)
650 if info.not_set_warning:
651 mlog.warning(info.not_set_warning)
652
653 if info.convertor:
654 kwargs[info.name] = info.convertor(kwargs[info.name])
655
656 return f(*wrapped_args, **wrapped_kwargs)
657 return T.cast('TV_func', wrapper)
658 return inner
659
660
661 # This cannot be a dataclass due to https://github.com/python/mypy/issues/5374
662 class FeatureCheckBase(metaclass=mesonlib.SimpleABC):
663 "Base class for feature version checks"
664
665 feature_registry: T.ClassVar[T.Dict[str, T.Dict[str, T.Set[T.Tuple[str, T.Optional['mparser.BaseNode']]]]]]
666 emit_notice = False
667 unconditional = False
668
669 def __init__(self, feature_name: str, feature_version: str, extra_message: str = ''):
670 self.feature_name = feature_name
671 self.feature_version_for_msg = feature_version
672 self.extra_message = extra_message
673 self.feature_version = feature_version
674 # Map versions in the constraint of the form '0.46.0' to '0.46', to
675 # ensure that '0.46' in project(meson_version: '>=0.46') allows
676 # using features in '0.46.0'. Meson versioning is basically
677 # semver, i.e. '0.46.0' is the lowest version which satisfies the
678 # constraint '>=0.46', but meson.version_compare() is more like
679 # rpm versions for historical reasons.
680 while self.feature_version.endswith('.0'):
681 self.feature_version = self.feature_version[:-2]
682
683 @staticmethod
684 def get_target_version(subproject: str) -> MesonVersionTarget:
685 # Don't do any checks if project() has not been parsed yet
686 if subproject not in mesonlib.project_meson_versions:
687 return None
688 return mesonlib.project_meson_versions[subproject]
689
690 @staticmethod
691 @abc.abstractmethod
692 def check_version(target_version: MesonVersionTarget, feature_version: str) -> bool:
693 pass
694
695 def use(self, subproject: 'SubProject', location: T.Optional['mparser.BaseNode'] = None) -> None:
696 tv = self.get_target_version(subproject)
697 # No target version
698 if tv is None and not self.unconditional:
699 return
700 # Target version is new enough, don't warn
701 if self.check_version(tv, self.feature_version) and not self.emit_notice:
702 return
703 # Feature is too new for target version or we want to emit notices, register it
704 if subproject not in self.feature_registry:
705 self.feature_registry[subproject] = {self.feature_version_for_msg: set()}
706 register = self.feature_registry[subproject]
707 if self.feature_version_for_msg not in register:
708 register[self.feature_version_for_msg] = set()
709
710 feature_key = (self.feature_name, location)
711 if feature_key in register[self.feature_version_for_msg]:
712 # Don't warn about the same feature multiple times
713 # FIXME: This is needed to prevent duplicate warnings, but also
714 # means we won't warn about a feature used in multiple places.
715 return
716 register[self.feature_version_for_msg].add(feature_key)
717 # Target version is new enough, don't warn even if it is registered for notice
718 if self.check_version(tv, self.feature_version):
719 return
720 self.log_usage_warning(tv, location)
721
722 @classmethod
723 def report(cls, subproject: str) -> None:
724 if subproject not in cls.feature_registry:
725 return
726 warning_str = cls.get_warning_str_prefix(cls.get_target_version(subproject))
727 notice_str = cls.get_notice_str_prefix(cls.get_target_version(subproject))
728 fv = cls.feature_registry[subproject]
729 tv = cls.get_target_version(subproject)
730 for version in sorted(fv.keys()):
731 message = ', '.join(sorted({f"'{i[0]}'" for i in fv[version]}))
732 if cls.check_version(tv, version):
733 notice_str += '\n * {}: {{{}}}'.format(version, message)
734 else:
735 warning_str += '\n * {}: {{{}}}'.format(version, message)
736 if '\n' in notice_str:
737 mlog.notice(notice_str, fatal=False)
738 if '\n' in warning_str:
739 mlog.warning(warning_str)
740
741 def log_usage_warning(self, tv: MesonVersionTarget, location: T.Optional['mparser.BaseNode']) -> None:
742 raise InterpreterException('log_usage_warning not implemented')
743
744 @staticmethod
745 def get_warning_str_prefix(tv: MesonVersionTarget) -> str:
746 raise InterpreterException('get_warning_str_prefix not implemented')
747
748 @staticmethod
749 def get_notice_str_prefix(tv: MesonVersionTarget) -> str:
750 raise InterpreterException('get_notice_str_prefix not implemented')
751
752 def __call__(self, f: TV_func) -> TV_func:
753 @wraps(f)
754 def wrapped(*wrapped_args: T.Any, **wrapped_kwargs: T.Any) -> T.Any:
755 node, _, _, subproject = get_callee_args(wrapped_args)
756 if subproject is None:
757 raise AssertionError(f'{wrapped_args!r}')
758 self.use(subproject, node)
759 return f(*wrapped_args, **wrapped_kwargs)
760 return T.cast('TV_func', wrapped)
761
762 @classmethod
763 def single_use(cls, feature_name: str, version: str, subproject: 'SubProject',
764 extra_message: str = '', location: T.Optional['mparser.BaseNode'] = None) -> None:
765 """Oneline version that instantiates and calls use()."""
766 cls(feature_name, version, extra_message).use(subproject, location)
767
768
769 class FeatureNew(FeatureCheckBase):
770 """Checks for new features"""
771
772 # Class variable, shared across all instances
773 #
774 # Format: {subproject: {feature_version_for_msg: set(feature_names)}}
775 feature_registry = {}
776
777 @staticmethod
778 def check_version(target_version: MesonVersionTarget, feature_version: str) -> bool:
779 if isinstance(target_version, mesonlib.Range):
780 return mesonlib.version_compare_condition_with_min(target_version, feature_version)
781 else:
782 # Warn for anything newer than the current semver base slot.
783 major = coredata.version.split('.', maxsplit=1)[0]
784 return mesonlib.version_compare(feature_version, f'<{major}.0')
785
786 @staticmethod
787 def get_warning_str_prefix(tv: MesonVersionTarget) -> str:
788 if isinstance(tv, mesonlib.Range) and tv.min is not None:
789 return f'Project specifies a minimum meson_version \'{tv}\' but uses features which were added in newer versions:'
790 else:
791 return 'Project specifies no minimum version but uses features which were added in versions:'
792
793 @staticmethod
794 def get_notice_str_prefix(tv: MesonVersionTarget) -> str:
795 return ''
796
797 def log_usage_warning(self, tv: MesonVersionTarget, location: T.Optional['mparser.BaseNode']) -> None:
798 if isinstance(tv, mesonlib.Range) and tv.min is not None:
799 prefix = f"Project targets '{tv}'"
800 else:
801 prefix = 'Project does not target a minimum version'
802 args = [
803 prefix,
804 'but uses feature introduced in',
805 f"'{self.feature_version_for_msg}':",
806 f'{self.feature_name}.',
807 ]
808 if self.extra_message:
809 args.append(self.extra_message)
810 mlog.warning(*args, location=location)
811
812 class FeatureDeprecated(FeatureCheckBase):
813 """Checks for deprecated features"""
814
815 # Class variable, shared across all instances
816 #
817 # Format: {subproject: {feature_version_for_msg: set(feature_names)}}
818 feature_registry = {}
819 emit_notice = True
820
821 @staticmethod
822 def check_version(target_version: MesonVersionTarget, feature_version: str) -> bool:
823 if isinstance(target_version, mesonlib.Range):
824 # For deprecation checks we need to return the inverse of FeatureNew checks
825 return not mesonlib.version_compare_condition_with_min(target_version, feature_version)
826 else:
827 # Always warn for functionality deprecated in the current semver slot (i.e. the current version).
828 return False
829
830 @staticmethod
831 def get_warning_str_prefix(tv: MesonVersionTarget) -> str:
832 return 'Deprecated features used:'
833
834 @staticmethod
835 def get_notice_str_prefix(tv: MesonVersionTarget) -> str:
836 return 'Future-deprecated features used:'
837
838 def log_usage_warning(self, tv: MesonVersionTarget, location: T.Optional['mparser.BaseNode']) -> None:
839 if isinstance(tv, mesonlib.Range):
840 prefix = f"Project targets '{tv}'"
841 else:
842 prefix = 'Project does not target a minimum version'
843 args = [
844 prefix,
845 'but uses feature deprecated since',
846 f"'{self.feature_version_for_msg}':",
847 f'{self.feature_name}.',
848 ]
849 if self.extra_message:
850 args.append(self.extra_message)
851 mlog.warning(*args, location=location)
852
853
854 class FeatureBroken(FeatureCheckBase):
855 """Checks for broken features"""
856
857 # Class variable, shared across all instances
858 #
859 # Format: {subproject: {feature_version_for_msg: set(feature_names)}}
860 feature_registry = {}
861 unconditional = True
862
863 @staticmethod
864 def check_version(target_version: MesonVersionTarget, feature_version: str) -> bool:
865 # always warn for broken stuff
866 return False
867
868 @staticmethod
869 def get_warning_str_prefix(tv: MesonVersionTarget) -> str:
870 return 'Broken features used:'
871
872 @staticmethod
873 def get_notice_str_prefix(tv: MesonVersionTarget) -> str:
874 return ''
875
876 def log_usage_warning(self, tv: MesonVersionTarget, location: T.Optional['mparser.BaseNode']) -> None:
877 args = [
878 'Project uses feature that was always broken,',
879 'and is now deprecated since',
880 f"'{self.feature_version_for_msg}':",
881 f'{self.feature_name}.',
882 ]
883 if self.extra_message:
884 args.append(self.extra_message)
885 mlog.deprecation(*args, location=location)
886
887
888 # This cannot be a dataclass due to https://github.com/python/mypy/issues/5374
889 class FeatureCheckKwargsBase(metaclass=mesonlib.SimpleABC):
890
891 @property
892 @abc.abstractmethod
893 def feature_check_class(self) -> T.Type[FeatureCheckBase]:
894 pass
895
896 def __init__(self, feature_name: str, feature_version: str,
897 kwargs: T.List[str], extra_message: T.Optional[str] = None):
898 self.feature_name = feature_name
899 self.feature_version = feature_version
900 self.kwargs = kwargs
901 self.extra_message = extra_message
902
903 def __call__(self, f: TV_func) -> TV_func:
904 @wraps(f)
905 def wrapped(*wrapped_args: T.Any, **wrapped_kwargs: T.Any) -> T.Any:
906 node, _, kwargs, subproject = get_callee_args(wrapped_args)
907 if subproject is None:
908 raise AssertionError(f'{wrapped_args!r}')
909 for arg in self.kwargs:
910 if arg not in kwargs:
911 continue
912 name = arg + ' arg in ' + self.feature_name
913 self.feature_check_class.single_use(
914 name, self.feature_version, subproject, self.extra_message, node)
915 return f(*wrapped_args, **wrapped_kwargs)
916 return T.cast('TV_func', wrapped)
917
918 class FeatureNewKwargs(FeatureCheckKwargsBase):
919 feature_check_class = FeatureNew
920
921 class FeatureDeprecatedKwargs(FeatureCheckKwargsBase):
922 feature_check_class = FeatureDeprecated