Debian Codegraph @

src/_pytest/mark/expression.py

raw
1 r"""Evaluate match expressions, as used by `-k` and `-m`.
2
3 The grammar is:
4
5 expression: expr? EOF
6 expr: and_expr ('or' and_expr)*
7 and_expr: not_expr ('and' not_expr)*
8 not_expr: 'not' not_expr | '(' expr ')' | ident kwargs?
9
10 ident: (\w|:|\+|-|\.|\[|\]|\\|/)+
11 kwargs: ('(' name '=' value ( ', ' name '=' value )* ')')
12 name: a valid ident, but not a reserved keyword
13 value: (unescaped) string literal | (-)?[0-9]+ | 'False' | 'True' | 'None'
14
15 The semantics are:
16
17 - Empty expression evaluates to False.
18 - ident evaluates to True or False according to a provided matcher function.
19 - ident with parentheses and keyword arguments evaluates to True or False according to a provided matcher function.
20 - or/and/not evaluate according to the usual boolean semantics.
21 """
22
23 from __future__ import annotations
24
25 import ast
26 from collections.abc import Iterator
27 from collections.abc import Mapping
28 from collections.abc import Sequence
29 import dataclasses
30 import enum
31 import keyword
32 import re
33 import types
34 from typing import Final
35 from typing import final
36 from typing import Literal
37 from typing import NoReturn
38 from typing import overload
39 from typing import Protocol
40
41
42 __all__ = [
43 "Expression",
44 "ExpressionMatcher",
45 ]
46
47
48 FILE_NAME: Final = "<pytest match expression>"
49
50
51 class TokenType(enum.Enum):
52 LPAREN = "left parenthesis"
53 RPAREN = "right parenthesis"
54 OR = "or"
55 AND = "and"
56 NOT = "not"
57 IDENT = "identifier"
58 EOF = "end of input"
59 EQUAL = "="
60 STRING = "string literal"
61 COMMA = ","
62
63
64 @dataclasses.dataclass(frozen=True)
65 class Token:
66 __slots__ = ("pos", "type", "value")
67 type: TokenType
68 value: str
69 pos: int
70
71
72 class Scanner:
73 __slots__ = ("current", "input", "tokens")
74
75 def __init__(self, input: str) -> None:
76 self.input = input
77 self.tokens = self.lex(input)
78 self.current = next(self.tokens)
79
80 def lex(self, input: str) -> Iterator[Token]:
81 pos = 0
82 while pos < len(input):
83 if input[pos] in (" ", "\t"):
84 pos += 1
85 elif input[pos] == "(":
86 yield Token(TokenType.LPAREN, "(", pos)
87 pos += 1
88 elif input[pos] == ")":
89 yield Token(TokenType.RPAREN, ")", pos)
90 pos += 1
91 elif input[pos] == "=":
92 yield Token(TokenType.EQUAL, "=", pos)
93 pos += 1
94 elif input[pos] == ",":
95 yield Token(TokenType.COMMA, ",", pos)
96 pos += 1
97 elif (quote_char := input[pos]) in ("'", '"'):
98 end_quote_pos = input.find(quote_char, pos + 1)
99 if end_quote_pos == -1:
100 raise SyntaxError(
101 f'closing quote "{quote_char}" is missing',
102 (FILE_NAME, 1, pos + 1, input),
103 )
104 value = input[pos : end_quote_pos + 1]
105 if (backslash_pos := value.find("\\")) != -1:
106 raise SyntaxError(
107 r'escaping with "\" not supported in marker expression',
108 (FILE_NAME, 1, pos + backslash_pos + 1, input),
109 )
110 yield Token(TokenType.STRING, value, pos)
111 pos += len(value)
112 else:
113 match = re.match(r"(:?\w|:|\+|-|\.|\[|\]|\\|/)+", input[pos:])
114 if match:
115 value = match.group(0)
116 if value == "or":
117 yield Token(TokenType.OR, value, pos)
118 elif value == "and":
119 yield Token(TokenType.AND, value, pos)
120 elif value == "not":
121 yield Token(TokenType.NOT, value, pos)
122 else:
123 yield Token(TokenType.IDENT, value, pos)
124 pos += len(value)
125 else:
126 raise SyntaxError(
127 f'unexpected character "{input[pos]}"',
128 (FILE_NAME, 1, pos + 1, input),
129 )
130 yield Token(TokenType.EOF, "", pos)
131
132 @overload
133 def accept(self, type: TokenType, *, reject: Literal[True]) -> Token: ...
134
135 @overload
136 def accept(
137 self, type: TokenType, *, reject: Literal[False] = False
138 ) -> Token | None: ...
139
140 def accept(self, type: TokenType, *, reject: bool = False) -> Token | None:
141 if self.current.type is type:
142 token = self.current
143 if token.type is not TokenType.EOF:
144 self.current = next(self.tokens)
145 return token
146 if reject:
147 self.reject((type,))
148 return None
149
150 def reject(self, expected: Sequence[TokenType]) -> NoReturn:
151 raise SyntaxError(
152 "expected {}; got {}".format(
153 " OR ".join(type.value for type in expected),
154 self.current.type.value,
155 ),
156 (FILE_NAME, 1, self.current.pos + 1, self.input),
157 )
158
159
160 # True, False and None are legal match expression identifiers,
161 # but illegal as Python identifiers. To fix this, this prefix
162 # is added to identifiers in the conversion to Python AST.
163 IDENT_PREFIX = "$"
164
165
166 def expression(s: Scanner) -> ast.Expression:
167 if s.accept(TokenType.EOF):
168 ret: ast.expr = ast.Constant(False)
169 else:
170 ret = expr(s)
171 s.accept(TokenType.EOF, reject=True)
172 return ast.fix_missing_locations(ast.Expression(ret))
173
174
175 def expr(s: Scanner) -> ast.expr:
176 ret = and_expr(s)
177 while s.accept(TokenType.OR):
178 rhs = and_expr(s)
179 ret = ast.BoolOp(ast.Or(), [ret, rhs])
180 return ret
181
182
183 def and_expr(s: Scanner) -> ast.expr:
184 ret = not_expr(s)
185 while s.accept(TokenType.AND):
186 rhs = not_expr(s)
187 ret = ast.BoolOp(ast.And(), [ret, rhs])
188 return ret
189
190
191 def not_expr(s: Scanner) -> ast.expr:
192 if s.accept(TokenType.NOT):
193 return ast.UnaryOp(ast.Not(), not_expr(s))
194 if s.accept(TokenType.LPAREN):
195 ret = expr(s)
196 s.accept(TokenType.RPAREN, reject=True)
197 return ret
198 ident = s.accept(TokenType.IDENT)
199 if ident:
200 name = ast.Name(IDENT_PREFIX + ident.value, ast.Load())
201 if s.accept(TokenType.LPAREN):
202 ret = ast.Call(func=name, args=[], keywords=all_kwargs(s))
203 s.accept(TokenType.RPAREN, reject=True)
204 else:
205 ret = name
206 return ret
207
208 s.reject((TokenType.NOT, TokenType.LPAREN, TokenType.IDENT))
209
210
211 BUILTIN_MATCHERS = {"True": True, "False": False, "None": None}
212
213
214 def single_kwarg(s: Scanner) -> ast.keyword:
215 keyword_name = s.accept(TokenType.IDENT, reject=True)
216 if not keyword_name.value.isidentifier():
217 raise SyntaxError(
218 f"not a valid python identifier {keyword_name.value}",
219 (FILE_NAME, 1, keyword_name.pos + 1, s.input),
220 )
221 if keyword.iskeyword(keyword_name.value):
222 raise SyntaxError(
223 f"unexpected reserved python keyword `{keyword_name.value}`",
224 (FILE_NAME, 1, keyword_name.pos + 1, s.input),
225 )
226 s.accept(TokenType.EQUAL, reject=True)
227
228 if value_token := s.accept(TokenType.STRING):
229 value: str | int | bool | None = value_token.value[1:-1] # strip quotes
230 else:
231 value_token = s.accept(TokenType.IDENT, reject=True)
232 if (number := value_token.value).isdigit() or (
233 number.startswith("-") and number[1:].isdigit()
234 ):
235 value = int(number)
236 elif value_token.value in BUILTIN_MATCHERS:
237 value = BUILTIN_MATCHERS[value_token.value]
238 else:
239 raise SyntaxError(
240 f'unexpected character/s "{value_token.value}"',
241 (FILE_NAME, 1, value_token.pos + 1, s.input),
242 )
243
244 ret = ast.keyword(keyword_name.value, ast.Constant(value))
245 return ret
246
247
248 def all_kwargs(s: Scanner) -> list[ast.keyword]:
249 ret = [single_kwarg(s)]
250 while s.accept(TokenType.COMMA):
251 ret.append(single_kwarg(s))
252 return ret
253
254
255 class ExpressionMatcher(Protocol):
256 """A callable which, given an identifier and optional kwargs, should return
257 whether it matches in an :class:`Expression` evaluation.
258
259 Should be prepared to handle arbitrary strings as input.
260
261 If no kwargs are provided, the expression of the form `foo`.
262 If kwargs are provided, the expression is of the form `foo(1, b=True, "s")`.
263
264 If the expression is not supported (e.g. don't want to accept the kwargs
265 syntax variant), should raise :class:`~pytest.UsageError`.
266
267 Example::
268
269 def matcher(name: str, /, **kwargs: str | int | bool | None) -> bool:
270 # Match `cat`.
271 if name == "cat" and not kwargs:
272 return True
273 # Match `dog(barks=True)`.
274 if name == "dog" and kwargs == {"barks": False}:
275 return True
276 return False
277 """
278
279 def __call__(self, name: str, /, **kwargs: str | int | bool | None) -> bool: ...
280
281
282 @dataclasses.dataclass
283 class MatcherNameAdapter:
284 matcher: ExpressionMatcher
285 name: str
286
287 def __bool__(self) -> bool:
288 return self.matcher(self.name)
289
290 def __call__(self, **kwargs: str | int | bool | None) -> bool:
291 return self.matcher(self.name, **kwargs)
292
293
294 class MatcherAdapter(Mapping[str, MatcherNameAdapter]):
295 """Adapts a matcher function to a locals mapping as required by eval()."""
296
297 def __init__(self, matcher: ExpressionMatcher) -> None:
298 self.matcher = matcher
299
300 def __getitem__(self, key: str) -> MatcherNameAdapter:
301 return MatcherNameAdapter(matcher=self.matcher, name=key[len(IDENT_PREFIX) :])
302
303 def __iter__(self) -> Iterator[str]:
304 raise NotImplementedError()
305
306 def __len__(self) -> int:
307 raise NotImplementedError()
308
309
310 @final
311 class Expression:
312 """A compiled match expression as used by -k and -m.
313
314 The expression can be evaluated against different matchers.
315 """
316
317 __slots__ = ("_code", "input")
318
319 def __init__(self, input: str, code: types.CodeType) -> None:
320 #: The original input line, as a string.
321 self.input: Final = input
322 self._code: Final = code
323
324 @classmethod
325 def compile(cls, input: str) -> Expression:
326 """Compile a match expression.
327
328 :param input: The input expression - one line.
329
330 :raises SyntaxError: If the expression is malformed.
331 """
332 astexpr = expression(Scanner(input))
333 code = compile(
334 astexpr,
335 filename="<pytest match expression>",
336 mode="eval",
337 )
338 return Expression(input, code)
339
340 def evaluate(self, matcher: ExpressionMatcher) -> bool:
341 """Evaluate the match expression.
342
343 :param matcher:
344 A callback which determines whether an identifier matches or not.
345 See the :class:`ExpressionMatcher` protocol for details and example.
346
347 :returns: Whether the expression matches or not.
348
349 :raises UsageError:
350 If the matcher doesn't support the expression. Cannot happen if the
351 matcher supports all expressions.
352 """
353 return bool(eval(self._code, {"__builtins__": {}}, MatcherAdapter(matcher)))