sr-zero 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,668 @@
1
+ """Running code: for a question about what a Python function returns, run it and pick the option that equals the
2
+ result.
3
+
4
+ The state holds the function's source (`code`) and its arguments (`input`), as Python literals. The code is never
5
+ passed to exec or eval: a small interpreter written for this walks its syntax tree. It runs only the statements and
6
+ expressions listed below, calls only the listed builtins and the listed methods of str, list, dict, set, tuple and
7
+ numbers, refuses imports, classes, generators and any name with an underscore at either end, and stops after a
8
+ budget of steps, recursion, integer size and container length. Anything else, and any doubt, means no answer.
9
+ """
10
+ import ast
11
+ import math
12
+ import operator
13
+ import string
14
+
15
+ from .. import text
16
+
17
+ NAME = "run"
18
+ CASES = {
19
+ "computed": "the option equal to what f returns when it is run on the input",
20
+ }
21
+ STEPS = 100_000
22
+ DEPTH = 60
23
+ BIG_INT_BITS = 20_000
24
+ BIG_LEN = 200_000
25
+
26
+
27
+ class Refused(Exception):
28
+ """The code does something the interpreter does not run."""
29
+
30
+
31
+ class Thrown(Exception):
32
+ """An exception raised by the code itself, carrying the Python exception it would raise."""
33
+
34
+ def __init__(self, error):
35
+ super().__init__(error)
36
+ self.error = error
37
+
38
+
39
+ class Returned(Exception):
40
+ def __init__(self, value):
41
+ super().__init__()
42
+ self.value = value
43
+
44
+
45
+ class Broke(Exception):
46
+ pass
47
+
48
+
49
+ class Continued(Exception):
50
+ pass
51
+
52
+
53
+ ERRORS = {cls.__name__: cls for cls in (Exception, ValueError, IndexError, KeyError, TypeError, ZeroDivisionError,
54
+ AttributeError, StopIteration, RuntimeError, ArithmeticError, LookupError,
55
+ AssertionError, OverflowError, NotImplementedError)}
56
+ METHODS = {
57
+ str: {"capitalize", "casefold", "center", "count", "endswith", "expandtabs", "find", "format", "index",
58
+ "isalnum", "isalpha", "isascii", "isdecimal", "isdigit", "isidentifier", "islower", "isnumeric",
59
+ "isprintable", "isspace", "istitle", "isupper", "join", "ljust", "lower", "lstrip", "partition",
60
+ "removeprefix", "removesuffix", "replace", "rfind", "rindex", "rjust", "rpartition", "rsplit", "rstrip",
61
+ "split", "splitlines", "startswith", "strip", "swapcase", "title", "translate", "upper", "zfill",
62
+ "maketrans"},
63
+ list: {"append", "clear", "copy", "count", "extend", "index", "insert", "pop", "remove", "reverse", "sort"},
64
+ dict: {"clear", "copy", "fromkeys", "get", "items", "keys", "pop", "popitem", "setdefault", "update", "values"},
65
+ set: {"add", "clear", "copy", "difference", "difference_update", "discard", "intersection",
66
+ "intersection_update", "isdisjoint", "issubset", "issuperset", "pop", "remove", "symmetric_difference",
67
+ "symmetric_difference_update", "union", "update"},
68
+ frozenset: {"copy", "difference", "intersection", "isdisjoint", "issubset", "issuperset",
69
+ "symmetric_difference", "union"},
70
+ tuple: {"count", "index"},
71
+ int: {"bit_length", "to_bytes"},
72
+ float: {"is_integer"},
73
+ bool: set(),
74
+ type(None): set(),
75
+ range: {"count", "index"},
76
+ type({}.keys()): set(),
77
+ type({}.values()): set(),
78
+ type({}.items()): set(),
79
+ }
80
+ PADDING = {"center", "ljust", "rjust", "zfill", "expandtabs", "to_bytes"}
81
+ TYPES = {str, list, dict, set, frozenset, tuple, int, float}
82
+ BINARY = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv,
83
+ ast.FloorDiv: operator.floordiv, ast.Mod: operator.mod, ast.Pow: operator.pow, ast.LShift: operator.lshift,
84
+ ast.RShift: operator.rshift, ast.BitOr: operator.or_, ast.BitXor: operator.xor, ast.BitAnd: operator.and_}
85
+ UNARY = {ast.UAdd: operator.pos, ast.USub: operator.neg, ast.Not: operator.not_, ast.Invert: operator.invert}
86
+ COMPARE = {ast.Eq: operator.eq, ast.NotEq: operator.ne, ast.Lt: operator.lt, ast.LtE: operator.le, ast.Gt: operator.gt,
87
+ ast.GtE: operator.ge, ast.Is: operator.is_, ast.IsNot: operator.is_not,
88
+ ast.In: lambda a, b: a in b, ast.NotIn: lambda a, b: a not in b}
89
+
90
+
91
+ def _private(name):
92
+ return name.startswith("_") or name.endswith("_")
93
+
94
+
95
+ def _check(value):
96
+ """Refuse values beyond the budget: huge integers and long containers."""
97
+ if isinstance(value, int) and not isinstance(value, bool) and value.bit_length() > BIG_INT_BITS:
98
+ raise Refused("integer too large")
99
+ if isinstance(value, (str, list, tuple, dict, set, frozenset, bytes)) and len(value) > BIG_LEN:
100
+ raise Refused("container too long")
101
+ return value
102
+
103
+
104
+ def _safe_format(template, *args, **kwargs):
105
+ for _, field, _, _ in string.Formatter().parse(template):
106
+ if field and ("." in field or "[" in field or "!" in field):
107
+ raise Refused("format field with attribute or index access")
108
+ return template.format(*args, **kwargs)
109
+
110
+
111
+ class Function:
112
+ """A function defined by the code (or a lambda), run by the interpreter when called."""
113
+
114
+ def __init__(self, machine, node, scope):
115
+ self.machine, self.node, self.scope = machine, node, scope
116
+ args = node.args
117
+ if args.vararg is None and args.kwarg is None and not args.kwonlyargs and not args.posonlyargs:
118
+ self.simple = True
119
+ else:
120
+ self.simple = False
121
+ self.defaults = [machine.eval(d, scope) for d in args.defaults]
122
+ self.kw_defaults = [None if d is None else machine.eval(d, scope) for d in args.kw_defaults]
123
+
124
+ def __call__(self, *values, **named):
125
+ machine = self.machine
126
+ machine.depth += 1
127
+ if machine.depth > DEPTH:
128
+ raise Refused("recursion too deep")
129
+ try:
130
+ local = dict(self.scope.chain)
131
+ env = Scope(local, self.scope.globals)
132
+ self._bind(env, values, named)
133
+ if isinstance(self.node, ast.Lambda):
134
+ return machine.eval(self.node.body, env)
135
+ try:
136
+ machine.block(self.node.body, env)
137
+ except Returned as done:
138
+ return done.value
139
+ return None
140
+ finally:
141
+ machine.depth -= 1
142
+
143
+ def _bind(self, env, values, named):
144
+ args = self.node.args
145
+ positional = [a.arg for a in args.posonlyargs + args.args]
146
+ defaults = dict(zip(positional[len(positional) - len(self.defaults):], self.defaults))
147
+ if len(values) > len(positional) and args.vararg is None:
148
+ raise Thrown(TypeError("too many positional arguments"))
149
+ for name, value in zip(positional, values):
150
+ env.set(name, value)
151
+ if args.vararg is not None:
152
+ env.set(args.vararg.arg, tuple(values[len(positional):]))
153
+ extra = {}
154
+ for name, value in named.items():
155
+ if name in positional or name in [a.arg for a in args.kwonlyargs]:
156
+ env.set(name, value)
157
+ elif args.kwarg is not None:
158
+ extra[name] = value
159
+ else:
160
+ raise Thrown(TypeError(f"unexpected keyword argument {name!r}"))
161
+ if args.kwarg is not None:
162
+ env.set(args.kwarg.arg, extra)
163
+ for name in positional:
164
+ if name not in env.local:
165
+ if name not in defaults:
166
+ raise Thrown(TypeError(f"missing argument {name!r}"))
167
+ env.set(name, defaults[name])
168
+ for arg, default in zip(args.kwonlyargs, self.kw_defaults):
169
+ if arg.arg not in env.local:
170
+ if default is None:
171
+ raise Thrown(TypeError(f"missing keyword argument {arg.arg!r}"))
172
+ env.set(arg.arg, default)
173
+
174
+
175
+ class Scope:
176
+ """Names visible to running code: a function's locals over the enclosing ones, then the module's."""
177
+
178
+ def __init__(self, local, globals_):
179
+ self.local, self.globals = local, globals_
180
+ self.chain = local
181
+
182
+ def get(self, name):
183
+ if name in self.local:
184
+ return self.local[name]
185
+ if name in self.globals:
186
+ return self.globals[name]
187
+ if name in BUILTINS:
188
+ return BUILTINS[name]
189
+ if name in ERRORS:
190
+ return ERRORS[name]
191
+ raise Thrown(NameError(name))
192
+
193
+ def set(self, name, value):
194
+ self.local[name] = value
195
+
196
+
197
+ def _sorted(values, key=None, reverse=False):
198
+ return sorted(values, key=key, reverse=reverse)
199
+
200
+
201
+ def _range(*args):
202
+ span = range(*args)
203
+ if len(span) > BIG_LEN:
204
+ raise Refused("range too long")
205
+ return span
206
+
207
+
208
+ def _pow(base, exponent, mod=None):
209
+ if mod is None and isinstance(base, int) and isinstance(exponent, int) and exponent > 0 and abs(base) > 1:
210
+ if exponent * math.log2(abs(base) + 1) > BIG_INT_BITS:
211
+ raise Refused("power too large")
212
+ return pow(base, exponent, mod)
213
+
214
+
215
+ BUILTINS = {
216
+ "abs": abs, "all": all, "any": any, "bool": bool, "chr": chr, "dict": dict, "divmod": divmod,
217
+ "enumerate": enumerate, "filter": filter, "float": float, "frozenset": frozenset, "int": int,
218
+ "isinstance": isinstance, "len": len, "list": list, "map": map, "max": max, "min": min, "ord": ord, "pow": _pow,
219
+ "range": _range, "reversed": reversed, "round": round, "set": set, "sorted": _sorted, "str": str, "sum": sum,
220
+ "tuple": tuple, "zip": zip, "repr": repr, "bin": bin, "hex": hex, "oct": oct, "iter": iter, "next": next,
221
+ "print": lambda *a, **k: None, "type": type, "hash": hash, "format": format, "callable": callable,
222
+ }
223
+ CALLABLE = set(map(id, BUILTINS.values())) | set(map(id, ERRORS.values()))
224
+
225
+
226
+ class Machine:
227
+ """The interpreter: statements and expressions of a small, safe subset of Python."""
228
+
229
+ def __init__(self, steps=STEPS):
230
+ self.steps, self.depth = steps, 0
231
+
232
+ def tick(self):
233
+ self.steps -= 1
234
+ if self.steps < 0:
235
+ raise Refused("step budget spent")
236
+
237
+ # ---- statements --------------------------------------------------------------------------------------------
238
+
239
+ def block(self, body, env):
240
+ for node in body:
241
+ self.statement(node, env)
242
+
243
+ def statement(self, node, env):
244
+ self.tick()
245
+ kind = type(node)
246
+ if kind is ast.Expr:
247
+ self.eval(node.value, env)
248
+ elif kind is ast.Assign:
249
+ value = self.eval(node.value, env)
250
+ for target in node.targets:
251
+ self.assign(target, value, env)
252
+ elif kind is ast.AugAssign:
253
+ current = self.eval(_load(node.target), env)
254
+ value = self.binary(node.op, current, self.eval(node.value, env))
255
+ self.assign(node.target, value, env)
256
+ elif kind is ast.AnnAssign:
257
+ if node.value is not None:
258
+ self.assign(node.target, self.eval(node.value, env), env)
259
+ elif kind is ast.Return:
260
+ raise Returned(None if node.value is None else self.eval(node.value, env))
261
+ elif kind is ast.If:
262
+ self.block(node.body if self.eval(node.test, env) else node.orelse, env)
263
+ elif kind is ast.For:
264
+ broke = False
265
+ for item in self.eval(node.iter, env):
266
+ self.tick()
267
+ self.assign(node.target, item, env)
268
+ try:
269
+ self.block(node.body, env)
270
+ except Broke:
271
+ broke = True
272
+ break
273
+ except Continued:
274
+ continue
275
+ if not broke:
276
+ self.block(node.orelse, env)
277
+ elif kind is ast.While:
278
+ broke = False
279
+ while self.eval(node.test, env):
280
+ self.tick()
281
+ try:
282
+ self.block(node.body, env)
283
+ except Broke:
284
+ broke = True
285
+ break
286
+ except Continued:
287
+ continue
288
+ if not broke:
289
+ self.block(node.orelse, env)
290
+ elif kind is ast.Break:
291
+ raise Broke()
292
+ elif kind is ast.Continue:
293
+ raise Continued()
294
+ elif kind is ast.Pass:
295
+ pass
296
+ elif kind is ast.FunctionDef:
297
+ if node.decorator_list:
298
+ raise Refused("decorators")
299
+ env.set(node.name, Function(self, node, env))
300
+ elif kind is ast.Try:
301
+ self.try_(node, env)
302
+ elif kind is ast.Raise:
303
+ error = self.eval(node.exc, env) if node.exc is not None else RuntimeError()
304
+ if isinstance(error, type) and issubclass(error, Exception):
305
+ error = error()
306
+ if not isinstance(error, Exception):
307
+ raise Refused("raising a non-exception")
308
+ raise Thrown(error)
309
+ elif kind is ast.Assert:
310
+ if not self.eval(node.test, env):
311
+ raise Thrown(AssertionError())
312
+ elif kind is ast.Delete:
313
+ for target in node.targets:
314
+ self.delete(target, env)
315
+ elif kind in (ast.Global, ast.Nonlocal):
316
+ raise Refused("global and nonlocal")
317
+ else:
318
+ raise Refused(f"statement {kind.__name__}")
319
+
320
+ def try_(self, node, env):
321
+ try:
322
+ self.block(node.body, env)
323
+ except Thrown as thrown:
324
+ for handler in node.handlers:
325
+ caught = ERRORS["Exception"] if handler.type is None else self.eval(handler.type, env)
326
+ caught = caught if isinstance(caught, tuple) else (caught,)
327
+ if any(isinstance(c, type) and isinstance(thrown.error, c) for c in caught):
328
+ if handler.name:
329
+ env.set(handler.name, thrown.error)
330
+ self.block(handler.body, env)
331
+ break
332
+ else:
333
+ raise
334
+ else:
335
+ self.block(node.orelse, env)
336
+ finally:
337
+ self.block(node.finalbody, env)
338
+
339
+ def assign(self, target, value, env):
340
+ kind = type(target)
341
+ if kind is ast.Name:
342
+ env.set(target.id, value)
343
+ elif kind in (ast.Tuple, ast.List):
344
+ values = list(value)
345
+ starred = [i for i, t in enumerate(target.elts) if isinstance(t, ast.Starred)]
346
+ if starred:
347
+ i = starred[0]
348
+ after = len(target.elts) - i - 1
349
+ if len(values) < len(target.elts) - 1:
350
+ raise Thrown(ValueError("not enough values to unpack"))
351
+ head, middle, tail = values[:i], values[i:len(values) - after], values[len(values) - after:]
352
+ for t, v in zip(target.elts[:i], head):
353
+ self.assign(t, v, env)
354
+ self.assign(target.elts[i].value, middle, env)
355
+ for t, v in zip(target.elts[i + 1:], tail):
356
+ self.assign(t, v, env)
357
+ else:
358
+ if len(values) != len(target.elts):
359
+ raise Thrown(ValueError("cannot unpack"))
360
+ for t, v in zip(target.elts, values):
361
+ self.assign(t, v, env)
362
+ elif kind is ast.Subscript:
363
+ container = self.eval(target.value, env)
364
+ if not isinstance(container, (list, dict)):
365
+ raise Refused("assigning into this type")
366
+ try:
367
+ container[self.index(target.slice, env)] = value
368
+ except (IndexError, KeyError, TypeError, ValueError) as error:
369
+ raise Thrown(error) from error
370
+ _check(container)
371
+ else:
372
+ raise Refused(f"assigning to {kind.__name__}")
373
+
374
+ def delete(self, target, env):
375
+ if isinstance(target, ast.Name):
376
+ if target.id not in env.local:
377
+ raise Thrown(NameError(target.id))
378
+ del env.local[target.id]
379
+ elif isinstance(target, ast.Subscript):
380
+ container = self.eval(target.value, env)
381
+ if not isinstance(container, (list, dict)):
382
+ raise Refused("deleting from this type")
383
+ try:
384
+ del container[self.index(target.slice, env)]
385
+ except (IndexError, KeyError, TypeError) as error:
386
+ raise Thrown(error) from error
387
+ else:
388
+ raise Refused("delete")
389
+
390
+ # ---- expressions -------------------------------------------------------------------------------------------
391
+
392
+ def eval(self, node, env):
393
+ self.tick()
394
+ kind = type(node)
395
+ if kind is ast.Constant:
396
+ return node.value
397
+ if kind is ast.Name:
398
+ return env.get(node.id)
399
+ if kind is ast.BinOp:
400
+ return self.binary(node.op, self.eval(node.left, env), self.eval(node.right, env))
401
+ if kind is ast.UnaryOp:
402
+ return self.guard(UNARY[type(node.op)], self.eval(node.operand, env))
403
+ if kind is ast.BoolOp:
404
+ if isinstance(node.op, ast.And):
405
+ value = True
406
+ for item in node.values:
407
+ value = self.eval(item, env)
408
+ if not value:
409
+ return value
410
+ return value
411
+ value = False
412
+ for item in node.values:
413
+ value = self.eval(item, env)
414
+ if value:
415
+ return value
416
+ return value
417
+ if kind is ast.Compare:
418
+ left = self.eval(node.left, env)
419
+ for op, right_node in zip(node.ops, node.comparators):
420
+ right = self.eval(right_node, env)
421
+ if not self.guard(COMPARE[type(op)], left, right):
422
+ return False
423
+ left = right
424
+ return True
425
+ if kind is ast.IfExp:
426
+ return self.eval(node.body if self.eval(node.test, env) else node.orelse, env)
427
+ if kind is ast.Call:
428
+ return self.call(node, env)
429
+ if kind is ast.Attribute:
430
+ return self.attribute(self.eval(node.value, env), node.attr)
431
+ if kind is ast.Subscript:
432
+ container = self.eval(node.value, env)
433
+ return self.guard(operator.getitem, container, self.index(node.slice, env))
434
+ if kind is ast.List:
435
+ return _check(self.items(node.elts, env))
436
+ if kind is ast.Tuple:
437
+ return tuple(self.items(node.elts, env))
438
+ if kind is ast.Set:
439
+ return set(self.items(node.elts, env))
440
+ if kind is ast.Dict:
441
+ out = {}
442
+ for key, value in zip(node.keys, node.values):
443
+ if key is None:
444
+ out.update(self.eval(value, env))
445
+ else:
446
+ out[self.eval(key, env)] = self.eval(value, env)
447
+ return out
448
+ if kind in (ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp):
449
+ return self.comprehension(node, env)
450
+ if kind is ast.Lambda:
451
+ return Function(self, node, env)
452
+ if kind is ast.JoinedStr:
453
+ return "".join(self.eval(v, env) if isinstance(v, ast.FormattedValue) else str(v.value)
454
+ for v in node.values)
455
+ if kind is ast.FormattedValue:
456
+ value = self.eval(node.value, env)
457
+ if node.conversion == ord("r"):
458
+ value = repr(value)
459
+ elif node.conversion == ord("s"):
460
+ value = str(value)
461
+ elif node.conversion == ord("a"):
462
+ value = ascii(value)
463
+ spec = self.eval(node.format_spec, env) if node.format_spec is not None else ""
464
+ return self.guard(format, value, spec)
465
+ if kind is ast.NamedExpr:
466
+ value = self.eval(node.value, env)
467
+ env.set(node.target.id, value)
468
+ return value
469
+ if kind is ast.Slice:
470
+ parts = (node.lower, node.upper, node.step)
471
+ return slice(*(None if part is None else self.eval(part, env) for part in parts))
472
+ raise Refused(f"expression {kind.__name__}")
473
+
474
+ def items(self, nodes, env):
475
+ out = []
476
+ for node in nodes:
477
+ if isinstance(node, ast.Starred):
478
+ out.extend(self.eval(node.value, env))
479
+ else:
480
+ out.append(self.eval(node, env))
481
+ return out
482
+
483
+ def index(self, node, env):
484
+ return self.eval(node, env)
485
+
486
+ def guard(self, fn, *args, **kwargs):
487
+ """Call a Python operation, turning its errors into the code's own exceptions."""
488
+ try:
489
+ return _check(fn(*args, **kwargs))
490
+ except (Thrown, Refused, Returned, Broke, Continued):
491
+ raise
492
+ except (ArithmeticError, LookupError, TypeError, ValueError, AttributeError, StopIteration) as error:
493
+ raise Thrown(error) from error
494
+ except RecursionError as error:
495
+ raise Refused("recursion") from error
496
+
497
+ def binary(self, op, left, right):
498
+ if isinstance(op, ast.Mult):
499
+ for seq, count in ((left, right), (right, left)):
500
+ long = isinstance(seq, (str, list, tuple)) and isinstance(count, int)
501
+ if long and len(seq) * max(count, 0) > BIG_LEN:
502
+ raise Refused("product too long")
503
+ if isinstance(op, ast.Pow) and isinstance(left, int) and isinstance(right, int) and right > 0:
504
+ if abs(left) > 1 and right * math.log2(abs(left) + 1) > BIG_INT_BITS:
505
+ raise Refused("power too large")
506
+ if isinstance(op, ast.LShift) and isinstance(right, int) and right > BIG_INT_BITS:
507
+ raise Refused("shift too large")
508
+ if isinstance(op, ast.Mod) and isinstance(left, str):
509
+ raise Refused("printf formatting")
510
+ return self.guard(BINARY[type(op)], left, right)
511
+
512
+ def attribute(self, value, name):
513
+ if _private(name):
514
+ raise Refused("private attribute")
515
+ if isinstance(value, type) and value in TYPES and name in METHODS[value]:
516
+ method = getattr(value, name)
517
+ return lambda *a, **k: self.guard(method, *a, **k)
518
+ allowed = METHODS.get(type(value))
519
+ if allowed is None or name not in allowed:
520
+ if isinstance(value, Exception) and name == "args":
521
+ return value.args
522
+ raise Refused(f"attribute {name} of {type(value).__name__}")
523
+ if type(value) is str and name == "format":
524
+ return lambda *a, **k: _check(_safe_format(value, *a, **k))
525
+ method = getattr(value, name)
526
+ if name in PADDING:
527
+ def padded(*a, **k):
528
+ if any(isinstance(x, int) and x > BIG_LEN for x in list(a) + list(k.values())):
529
+ raise Refused("padding too long")
530
+ return self.guard(method, *a, **k)
531
+ return padded
532
+ return lambda *a, **k: self.guard(method, *a, **k)
533
+
534
+ def call(self, node, env):
535
+ fn = self.eval(node.func, env)
536
+ args = self.items(node.args, env)
537
+ named = {}
538
+ for keyword in node.keywords:
539
+ if keyword.arg is None:
540
+ named.update(self.eval(keyword.value, env))
541
+ else:
542
+ named[keyword.arg] = self.eval(keyword.value, env)
543
+ if isinstance(fn, Function):
544
+ return fn(*args, **named)
545
+ if callable(fn) and (id(fn) in CALLABLE or getattr(fn, "__name__", "") in ("<lambda>", "padded")):
546
+ if fn is type and len(args) != 1:
547
+ raise Refused("type() with more than one argument")
548
+ return self.guard(fn, *args, **named)
549
+ raise Refused("calling this")
550
+
551
+ def comprehension(self, node, env):
552
+ local = Scope(dict(env.local), env.globals)
553
+ out = [] if not isinstance(node, ast.DictComp) else {}
554
+
555
+ def walk(i):
556
+ if i == len(node.generators):
557
+ if isinstance(node, ast.DictComp):
558
+ out[self.eval(node.key, local)] = self.eval(node.value, local)
559
+ else:
560
+ out.append(self.eval(node.elt, local))
561
+ _check(out)
562
+ return
563
+ generator = node.generators[i]
564
+ if generator.is_async:
565
+ raise Refused("async")
566
+ for item in self.eval(generator.iter, local):
567
+ self.tick()
568
+ self.assign(generator.target, item, local)
569
+ if all(self.eval(test, local) for test in generator.ifs):
570
+ walk(i + 1)
571
+
572
+ walk(0)
573
+ if isinstance(node, ast.SetComp):
574
+ return set(out)
575
+ if isinstance(node, ast.GeneratorExp):
576
+ return iter(out)
577
+ return out
578
+
579
+
580
+ def _load(target):
581
+ """The expression that reads what an augmented assignment writes."""
582
+ if isinstance(target, ast.Name):
583
+ return ast.Name(id=target.id, ctx=ast.Load())
584
+ if isinstance(target, ast.Subscript):
585
+ return ast.Subscript(value=target.value, slice=target.slice, ctx=ast.Load())
586
+ raise Refused("augmented assignment target")
587
+
588
+
589
+ def run(code, arguments):
590
+ """What f(arguments) returns, as ("value", result) or ("raised", exception name); None when it is not run."""
591
+ try:
592
+ tree = ast.parse(code)
593
+ call = ast.parse(f"f({arguments})", mode="eval").body
594
+ except (SyntaxError, ValueError, RecursionError):
595
+ return None
596
+ if not isinstance(call, ast.Call):
597
+ return None
598
+ try:
599
+ values = [ast.literal_eval(a) for a in call.args]
600
+ named = {k.arg: ast.literal_eval(k.value) for k in call.keywords if k.arg}
601
+ except (ValueError, SyntaxError, TypeError, RecursionError):
602
+ return None
603
+ machine = Machine()
604
+ env = Scope({}, {})
605
+ env.globals = env.local
606
+ try:
607
+ for node in tree.body:
608
+ if isinstance(node, (ast.Import, ast.ImportFrom, ast.ClassDef, ast.AsyncFunctionDef)):
609
+ return None
610
+ machine.statement(node, env)
611
+ f = env.local.get("f")
612
+ if not isinstance(f, Function):
613
+ return None
614
+ return "value", f(*values, **named)
615
+ except Thrown as thrown:
616
+ return "raised", type(thrown.error).__name__
617
+ except (Refused, Returned, Broke, Continued, RecursionError, MemoryError):
618
+ return None
619
+ except Exception: # noqa: BLE001 - anything the interpreter did not foresee means no answer
620
+ return None
621
+
622
+
623
+ def same(result, option):
624
+ """Whether an option's literal equals the result, of the same type all the way down."""
625
+ if type(result) is not type(option):
626
+ return False
627
+ if isinstance(result, (list, tuple)):
628
+ return len(result) == len(option) and all(same(a, b) for a, b in zip(result, option))
629
+ if isinstance(result, dict):
630
+ return result.keys() == option.keys() and all(same(result[k], option[k]) for k in result)
631
+ if isinstance(result, float):
632
+ return result == option or (math.isnan(result) and math.isnan(option))
633
+ return result == option
634
+
635
+
636
+ def propose(request, key):
637
+ """(option key, case) or None."""
638
+ data = request.data
639
+ if not isinstance(data, dict) or not isinstance(data.get("code"), str) or "input" not in data:
640
+ return None
641
+ if "def f" not in data["code"]:
642
+ return None
643
+ arguments = data["input"] if isinstance(data["input"], str) else repr(data["input"])
644
+ found = request.once(NAME, lambda r: run(data["code"], arguments))
645
+ if found is None or found[0] != "value":
646
+ return None
647
+ question = request.questions[key]
648
+ matches = []
649
+ for option, description in question_options(question):
650
+ try:
651
+ value = ast.literal_eval(description)
652
+ except (ValueError, SyntaxError, TypeError, RecursionError, MemoryError):
653
+ continue
654
+ if same(found[1], value):
655
+ matches.append(option)
656
+ return (matches[0], "computed") if len(matches) == 1 else None
657
+
658
+
659
+ def question_options(question):
660
+ """(key, the option's literal text as given) of a choice question."""
661
+ criteria = question.get("criteria")
662
+ if not isinstance(criteria, dict):
663
+ return []
664
+ return [(k, text.flatten(v) if v is not None else k) for k, v in criteria.items()]
665
+
666
+
667
+ def describe(case):
668
+ return CASES.get(case, case)