Debian Codegraph @

hypothesis-python/src/hypothesis/internal/filtering.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 """Tools for understanding predicates, to satisfy them by construction.
12
13 For example::
14
15 integers().filter(lambda x: x >= 0) -> integers(min_value=0)
16
17 This is intractable in general, but reasonably easy for simple cases involving
18 numeric bounds, strings with length or regex constraints, and collection lengths -
19 and those are precisely the most common cases. When they arise in e.g. Pandas
20 dataframes, it's also pretty painful to do the constructive version by hand in
21 a library; so we prefer to share all the implementation effort here.
22 See https://github.com/HypothesisWorks/hypothesis/issues/2701 for details.
23 """
24
25 import ast
26 import inspect
27 import math
28 import operator
29 import sys
30 from collections.abc import Callable, Collection
31 from decimal import Decimal
32 from fractions import Fraction
33 from functools import partial
34 from typing import Any, NamedTuple, TypeVar
35
36 from hypothesis.internal.compat import ceil, floor
37 from hypothesis.internal.floats import next_down, next_up
38 from hypothesis.internal.lambda_sources import lambda_description
39 from hypothesis.internal.reflection import get_pretty_function_description
40
41 if sys.version_info[:2] >= (3, 14):
42 from functools import Placeholder
43 else: # pragma: no cover
44 Placeholder = object()
45
46 Ex = TypeVar("Ex")
47 Predicate = Callable[[Ex], bool]
48
49
50 class ConstructivePredicate(NamedTuple):
51 """Return constraints to the appropriate strategy, and the predicate if needed.
52
53 For example::
54
55 integers().filter(lambda x: x >= 0)
56 -> {"min_value": 0"}, None
57
58 integers().filter(lambda x: x >= 0 and x % 7)
59 -> {"min_value": 0}, lambda x: x % 7
60
61 At least in principle - for now we usually return the predicate unchanged
62 if needed.
63
64 We have a separate get-predicate frontend for each "group" of strategies; e.g.
65 for each numeric type, for strings, for bytes, for collection sizes, etc.
66 """
67
68 constraints: dict[str, Any]
69 predicate: Predicate | None
70
71 @classmethod
72 def unchanged(cls, predicate: Predicate) -> "ConstructivePredicate":
73 return cls({}, predicate)
74
75 def __repr__(self) -> str:
76 fn = get_pretty_function_description(self.predicate)
77 return f"{self.__class__.__name__}(constraints={self.constraints!r}, predicate={fn})"
78
79
80 ARG = object()
81
82
83 def convert(node: ast.AST, argname: str) -> object:
84 if isinstance(node, ast.Name):
85 if node.id != argname:
86 raise ValueError("Non-local variable")
87 return ARG
88 if isinstance(node, ast.Call):
89 if (
90 isinstance(node.func, ast.Name)
91 and node.func.id == "len"
92 and len(node.args) == 1
93 ):
94 # error unless comparison is to the len *of the lambda arg*
95 return convert(node.args[0], argname)
96 return ast.literal_eval(node)
97
98
99 def comp_to_constraints(x: ast.AST, op: ast.AST, y: ast.AST, *, argname: str) -> dict:
100 a = convert(x, argname)
101 b = convert(y, argname)
102 num = (int, float)
103 if not (a is ARG and isinstance(b, num)) and not (isinstance(a, num) and b is ARG):
104 # It would be possible to work out if comparisons between two literals
105 # are always true or false, but it's too rare to be worth the complexity.
106 # (and we can't even do `arg == arg`, because what if it's NaN?)
107 raise ValueError("Can't analyse this comparison")
108
109 of_len = {"len": True} if isinstance(x, ast.Call) or isinstance(y, ast.Call) else {}
110
111 if isinstance(op, ast.Lt):
112 if a is ARG:
113 return {"max_value": b, "exclude_max": True, **of_len}
114 return {"min_value": a, "exclude_min": True, **of_len}
115 elif isinstance(op, ast.LtE):
116 if a is ARG:
117 return {"max_value": b, **of_len}
118 return {"min_value": a, **of_len}
119 elif isinstance(op, ast.Eq):
120 if a is ARG:
121 return {"min_value": b, "max_value": b, **of_len}
122 return {"min_value": a, "max_value": a, **of_len}
123 elif isinstance(op, ast.GtE):
124 if a is ARG:
125 return {"min_value": b, **of_len}
126 return {"max_value": a, **of_len}
127 elif isinstance(op, ast.Gt):
128 if a is ARG:
129 return {"min_value": b, "exclude_min": True, **of_len}
130 return {"max_value": a, "exclude_max": True, **of_len}
131 raise ValueError("Unhandled comparison operator") # e.g. ast.Ne
132
133
134 def merge_preds(*con_predicates: ConstructivePredicate) -> ConstructivePredicate:
135 # This function is just kinda messy. Unfortunately the neatest way
136 # to do this is just to roll out each case and handle them in turn.
137 base = {
138 "min_value": -math.inf,
139 "max_value": math.inf,
140 "exclude_min": False,
141 "exclude_max": False,
142 }
143 predicate = None
144 for kw, p in con_predicates:
145 assert (
146 not p or not predicate or p is predicate
147 ), "Can't merge two partially-constructive preds"
148 predicate = p or predicate
149 if "min_value" in kw:
150 if kw["min_value"] > base["min_value"]:
151 base["exclude_min"] = kw.get("exclude_min", False)
152 base["min_value"] = kw["min_value"]
153 elif kw["min_value"] == base["min_value"]:
154 base["exclude_min"] |= kw.get("exclude_min", False)
155 if "max_value" in kw:
156 if kw["max_value"] < base["max_value"]:
157 base["exclude_max"] = kw.get("exclude_max", False)
158 base["max_value"] = kw["max_value"]
159 elif kw["max_value"] == base["max_value"]:
160 base["exclude_max"] |= kw.get("exclude_max", False)
161
162 has_len = {"len" in kw for kw, _ in con_predicates if kw}
163 assert len(has_len) <= 1, "can't mix numeric with length constraints"
164 if has_len == {True}:
165 base["len"] = True
166
167 if not base["exclude_min"]:
168 del base["exclude_min"]
169 if base["min_value"] == -math.inf:
170 del base["min_value"]
171 if not base["exclude_max"]:
172 del base["exclude_max"]
173 if base["max_value"] == math.inf:
174 del base["max_value"]
175 return ConstructivePredicate(base, predicate)
176
177
178 def numeric_bounds_from_ast(
179 tree: ast.AST, argname: str, fallback: ConstructivePredicate
180 ) -> ConstructivePredicate:
181 """Take an AST; return a ConstructivePredicate.
182
183 >>> lambda x: x >= 0
184 {"min_value": 0}, None
185 >>> lambda x: x < 10
186 {"max_value": 10, "exclude_max": True}, None
187 >>> lambda x: len(x) >= 5
188 {"min_value": 5, "len": True}, None
189 >>> lambda x: x >= y
190 {}, lambda x: x >= y
191
192 See also https://greentreesnakes.readthedocs.io/en/latest/
193 """
194 if isinstance(tree, ast.Compare):
195 ops = tree.ops
196 vals = tree.comparators
197 comparisons = [(tree.left, ops[0], vals[0])]
198 for i, (op, val) in enumerate(zip(ops[1:], vals[1:], strict=True), start=1):
199 comparisons.append((vals[i - 1], op, val))
200 bounds = []
201 for comp in comparisons:
202 try:
203 constraints = comp_to_constraints(*comp, argname=argname)
204 # Because `len` could be redefined in the enclosing scope, we *always*
205 # have to apply the condition as a filter, in addition to rewriting.
206 pred = fallback.predicate if "len" in constraints else None
207 bounds.append(ConstructivePredicate(constraints, pred))
208 except ValueError:
209 bounds.append(fallback)
210 return merge_preds(*bounds)
211
212 if isinstance(tree, ast.BoolOp) and isinstance(tree.op, ast.And):
213 return merge_preds(
214 *(numeric_bounds_from_ast(node, argname, fallback) for node in tree.values)
215 )
216
217 return fallback
218
219
220 def get_numeric_predicate_bounds(predicate: Predicate) -> ConstructivePredicate:
221 """Shared logic for understanding numeric bounds.
222
223 We then specialise this in the other functions below, to ensure that e.g.
224 all the values are representable in the types that we're planning to generate
225 so that the strategy validation doesn't complain.
226 """
227 unchanged = ConstructivePredicate.unchanged(predicate)
228 if (
229 isinstance(predicate, partial)
230 and not predicate.keywords
231 and (
232 len(predicate.args) == 1
233 or (predicate.args[0] is Placeholder and len(predicate.args) == 2)
234 )
235 ):
236 if len(predicate.args) == 1:
237 arg = predicate.args[0]
238 func = predicate.func
239 else: # pragma: no cover # Python 3.14+ only
240 assert predicate.args[0] is Placeholder
241 arg = predicate.args[1]
242 func = { # reverses the table below; eq is unchanged
243 operator.lt: operator.gt,
244 operator.le: operator.ge,
245 operator.ge: operator.le,
246 operator.gt: operator.lt,
247 }.get(predicate.func, predicate.func)
248 assert func not in (min_len, max_len) # sanity-check; these are private
249
250 if (
251 (isinstance(arg, Decimal) and Decimal.is_snan(arg))
252 or not isinstance(arg, (int, float, Fraction, Decimal))
253 or math.isnan(arg)
254 ):
255 return unchanged
256 options = {
257 # We're talking about op(arg, x) - the reverse of our usual intuition!
258 operator.lt: {"min_value": arg, "exclude_min": True}, # lambda x: arg < x
259 operator.le: {"min_value": arg}, # lambda x: arg <= x
260 operator.eq: {"min_value": arg, "max_value": arg}, # lambda x: arg == x
261 operator.ge: {"max_value": arg}, # lambda x: arg >= x
262 operator.gt: {"max_value": arg, "exclude_max": True}, # lambda x: arg > x
263 # Special-case our default predicates for length bounds
264 min_len: {"min_value": arg, "len": True},
265 max_len: {"max_value": arg, "len": True},
266 }
267 if func in options:
268 return ConstructivePredicate(options[func], None)
269
270 # This section is a little complicated, but stepping through with comments should
271 # help to clarify it. We start by finding the source code for our predicate and
272 # parsing it to an abstract syntax tree; if this fails for any reason we bail out
273 # and fall back to standard rejection sampling (a running theme).
274 try:
275 if predicate.__name__ == "<lambda>":
276 source = lambda_description(predicate)
277 else:
278 source = inspect.getsource(predicate)
279 tree: ast.AST = ast.parse(source)
280 except Exception:
281 return unchanged
282
283 # Dig down to the relevant subtree - our tree is probably a Module containing
284 # either a FunctionDef, or an Expr which in turn contains a lambda definition.
285 while isinstance(tree, ast.Module) and len(tree.body) == 1:
286 tree = tree.body[0]
287 while isinstance(tree, ast.Expr):
288 tree = tree.value
289
290 if isinstance(tree, ast.Lambda) and len(tree.args.args) == 1:
291 return numeric_bounds_from_ast(tree.body, tree.args.args[0].arg, unchanged)
292 elif isinstance(tree, ast.FunctionDef) and len(tree.args.args) == 1:
293 if len(tree.body) != 1 or not isinstance(tree.body[0], ast.Return):
294 # If the body of the function is anything but `return <expr>`,
295 # i.e. as simple as a lambda, we can't process it (yet).
296 return unchanged
297 argname = tree.args.args[0].arg
298 body = tree.body[0].value
299 assert isinstance(body, ast.AST)
300 return numeric_bounds_from_ast(body, argname, unchanged)
301 return unchanged
302
303
304 def get_integer_predicate_bounds(predicate: Predicate) -> ConstructivePredicate:
305 constraints, predicate = get_numeric_predicate_bounds(predicate)
306
307 if "min_value" in constraints:
308 if constraints["min_value"] == -math.inf:
309 del constraints["min_value"]
310 elif math.isinf(constraints["min_value"]):
311 return ConstructivePredicate({"min_value": 1, "max_value": -1}, None)
312 elif constraints["min_value"] != int(constraints["min_value"]):
313 constraints["min_value"] = ceil(constraints["min_value"])
314 elif constraints.get("exclude_min", False):
315 constraints["min_value"] = int(constraints["min_value"]) + 1
316
317 if "max_value" in constraints:
318 if constraints["max_value"] == math.inf:
319 del constraints["max_value"]
320 elif math.isinf(constraints["max_value"]):
321 return ConstructivePredicate({"min_value": 1, "max_value": -1}, None)
322 elif constraints["max_value"] != int(constraints["max_value"]):
323 constraints["max_value"] = floor(constraints["max_value"])
324 elif constraints.get("exclude_max", False):
325 constraints["max_value"] = int(constraints["max_value"]) - 1
326
327 kw_categories = {"min_value", "max_value", "len"}
328 constraints = {k: v for k, v in constraints.items() if k in kw_categories}
329 return ConstructivePredicate(constraints, predicate)
330
331
332 def get_float_predicate_bounds(predicate: Predicate) -> ConstructivePredicate:
333 constraints, predicate = get_numeric_predicate_bounds(predicate)
334
335 if "min_value" in constraints:
336 min_value = constraints["min_value"]
337 constraints["min_value"] = float(constraints["min_value"])
338 if min_value < constraints["min_value"] or (
339 min_value == constraints["min_value"]
340 and constraints.get("exclude_min", False)
341 ):
342 constraints["min_value"] = next_up(constraints["min_value"])
343
344 if "max_value" in constraints:
345 max_value = constraints["max_value"]
346 constraints["max_value"] = float(constraints["max_value"])
347 if max_value > constraints["max_value"] or (
348 max_value == constraints["max_value"]
349 and constraints.get("exclude_max", False)
350 ):
351 constraints["max_value"] = next_down(constraints["max_value"])
352
353 constraints = {
354 k: v for k, v in constraints.items() if k in {"min_value", "max_value"}
355 }
356 return ConstructivePredicate(constraints, predicate)
357
358
359 def max_len(size: int, element: Collection[object]) -> bool:
360 return len(element) <= size
361
362
363 def min_len(size: int, element: Collection[object]) -> bool:
364 return size <= len(element)