expression.py 11 KB

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