expression.py 6.3 KB

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