expression.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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
  7. ident: (\w|:|\+|-|\.|\[|\]|\\|/)+
  8. The semantics are:
  9. - Empty expression evaluates to False.
  10. - ident evaluates to True of False according to a provided matcher function.
  11. - or/and/not evaluate according to the usual boolean semantics.
  12. """
  13. import ast
  14. import dataclasses
  15. import enum
  16. import re
  17. import sys
  18. import types
  19. from typing import Callable
  20. from typing import Iterator
  21. from typing import Mapping
  22. from typing import NoReturn
  23. from typing import Optional
  24. from typing import Sequence
  25. if sys.version_info >= (3, 8):
  26. astNameConstant = ast.Constant
  27. else:
  28. astNameConstant = ast.NameConstant
  29. __all__ = [
  30. "Expression",
  31. "ParseError",
  32. ]
  33. class TokenType(enum.Enum):
  34. LPAREN = "left parenthesis"
  35. RPAREN = "right parenthesis"
  36. OR = "or"
  37. AND = "and"
  38. NOT = "not"
  39. IDENT = "identifier"
  40. EOF = "end of input"
  41. @dataclasses.dataclass(frozen=True)
  42. class Token:
  43. __slots__ = ("type", "value", "pos")
  44. type: TokenType
  45. value: str
  46. pos: int
  47. class ParseError(Exception):
  48. """The expression contains invalid syntax.
  49. :param column: The column in the line where the error occurred (1-based).
  50. :param message: A description of the error.
  51. """
  52. def __init__(self, column: int, message: str) -> None:
  53. self.column = column
  54. self.message = message
  55. def __str__(self) -> str:
  56. return f"at column {self.column}: {self.message}"
  57. class Scanner:
  58. __slots__ = ("tokens", "current")
  59. def __init__(self, input: str) -> None:
  60. self.tokens = self.lex(input)
  61. self.current = next(self.tokens)
  62. def lex(self, input: str) -> Iterator[Token]:
  63. pos = 0
  64. while pos < len(input):
  65. if input[pos] in (" ", "\t"):
  66. pos += 1
  67. elif input[pos] == "(":
  68. yield Token(TokenType.LPAREN, "(", pos)
  69. pos += 1
  70. elif input[pos] == ")":
  71. yield Token(TokenType.RPAREN, ")", pos)
  72. pos += 1
  73. else:
  74. match = re.match(r"(:?\w|:|\+|-|\.|\[|\]|\\|/)+", input[pos:])
  75. if match:
  76. value = match.group(0)
  77. if value == "or":
  78. yield Token(TokenType.OR, value, pos)
  79. elif value == "and":
  80. yield Token(TokenType.AND, value, pos)
  81. elif value == "not":
  82. yield Token(TokenType.NOT, value, pos)
  83. else:
  84. yield Token(TokenType.IDENT, value, pos)
  85. pos += len(value)
  86. else:
  87. raise ParseError(
  88. pos + 1,
  89. f'unexpected character "{input[pos]}"',
  90. )
  91. yield Token(TokenType.EOF, "", pos)
  92. def accept(self, type: TokenType, *, reject: bool = False) -> Optional[Token]:
  93. if self.current.type is type:
  94. token = self.current
  95. if token.type is not TokenType.EOF:
  96. self.current = next(self.tokens)
  97. return token
  98. if reject:
  99. self.reject((type,))
  100. return None
  101. def reject(self, expected: Sequence[TokenType]) -> NoReturn:
  102. raise ParseError(
  103. self.current.pos + 1,
  104. "expected {}; got {}".format(
  105. " OR ".join(type.value for type in expected),
  106. self.current.type.value,
  107. ),
  108. )
  109. # True, False and None are legal match expression identifiers,
  110. # but illegal as Python identifiers. To fix this, this prefix
  111. # is added to identifiers in the conversion to Python AST.
  112. IDENT_PREFIX = "$"
  113. def expression(s: Scanner) -> ast.Expression:
  114. if s.accept(TokenType.EOF):
  115. ret: ast.expr = astNameConstant(False)
  116. else:
  117. ret = expr(s)
  118. s.accept(TokenType.EOF, reject=True)
  119. return ast.fix_missing_locations(ast.Expression(ret))
  120. def expr(s: Scanner) -> ast.expr:
  121. ret = and_expr(s)
  122. while s.accept(TokenType.OR):
  123. rhs = and_expr(s)
  124. ret = ast.BoolOp(ast.Or(), [ret, rhs])
  125. return ret
  126. def and_expr(s: Scanner) -> ast.expr:
  127. ret = not_expr(s)
  128. while s.accept(TokenType.AND):
  129. rhs = not_expr(s)
  130. ret = ast.BoolOp(ast.And(), [ret, rhs])
  131. return ret
  132. def not_expr(s: Scanner) -> ast.expr:
  133. if s.accept(TokenType.NOT):
  134. return ast.UnaryOp(ast.Not(), not_expr(s))
  135. if s.accept(TokenType.LPAREN):
  136. ret = expr(s)
  137. s.accept(TokenType.RPAREN, reject=True)
  138. return ret
  139. ident = s.accept(TokenType.IDENT)
  140. if ident:
  141. return ast.Name(IDENT_PREFIX + ident.value, ast.Load())
  142. s.reject((TokenType.NOT, TokenType.LPAREN, TokenType.IDENT))
  143. class MatcherAdapter(Mapping[str, bool]):
  144. """Adapts a matcher function to a locals mapping as required by eval()."""
  145. def __init__(self, matcher: Callable[[str], bool]) -> None:
  146. self.matcher = matcher
  147. def __getitem__(self, key: str) -> bool:
  148. return self.matcher(key[len(IDENT_PREFIX) :])
  149. def __iter__(self) -> Iterator[str]:
  150. raise NotImplementedError()
  151. def __len__(self) -> int:
  152. raise NotImplementedError()
  153. class Expression:
  154. """A compiled match expression as used by -k and -m.
  155. The expression can be evaluated against different matchers.
  156. """
  157. __slots__ = ("code",)
  158. def __init__(self, code: types.CodeType) -> None:
  159. self.code = code
  160. @classmethod
  161. def compile(self, input: str) -> "Expression":
  162. """Compile a match expression.
  163. :param input: The input expression - one line.
  164. """
  165. astexpr = expression(Scanner(input))
  166. code: types.CodeType = compile(
  167. astexpr,
  168. filename="<pytest match expression>",
  169. mode="eval",
  170. )
  171. return Expression(code)
  172. def evaluate(self, matcher: Callable[[str], bool]) -> bool:
  173. """Evaluate the match expression.
  174. :param matcher:
  175. Given an identifier, should return whether it matches or not.
  176. Should be prepared to handle arbitrary strings as input.
  177. :returns: Whether the expression matches or not.
  178. """
  179. ret: bool = eval(self.code, {"__builtins__": {}}, MatcherAdapter(matcher))
  180. return ret