LoLBench / cpython_16 /tests /private /eval_tests_aug.patch
lolbench26's picture
Publish LoLBench Harbor tasks from artifact branch (part 2)
a4edccc verified
Raw History Blame Contribute Delete
11.7 kB
diff --git a/Lib/test/test_pep798_parser_stability_aug.py b/Lib/test/test_pep798_parser_stability_aug.py
new file mode 100644
index 0000000..b54b787
--- /dev/null
+++ b/Lib/test/test_pep798_parser_stability_aug.py
@@ -0,0 +1,162 @@
+"""Augmented P2P tests for the PEP 798 bundle.
+
+These exercise the regenerated PEG parser across a broad slice of existing
+Python syntax — they pass on the pre-solution interpreter (none of the code
+below uses PEP 798 forms) and still pass post-solution, pinning that the
+grammar regeneration did not disturb pre-existing parsing behavior while
+walking a wide range of parser.c rules for coverage.
+"""
+
+import ast
+import unittest
+
+
+# A deterministic corpus touching many grammar rules: statements, decorators,
+# pattern matching, type params, f-strings, slices, lambda, star-args,
+# with/try/except*, walrus, comprehensions (classic forms), annotations.
+CORPUS = r'''
+from __future__ import annotations
+import os, sys as system
+from os import (path, sep)
+
+CONST: int = 0x10 + 0o7 + 0b1 + 1_000 - .5j.imag
+
+@staticmethod
+def deco(): ...
+
+class Meta(type): ...
+
+class C(Meta, metaclass=Meta):
+ """doc"""
+ x: int = 1
+ def method(self, a, b=2, /, c=3, *args, d, e=5, **kw) -> "C":
+ global CONST
+ nonlocal_target = lambda q, *, r=1: (q, r)
+ y = [i for i in range(3) if i]
+ z = {k: v for k, v in zip("ab", y)}
+ s = {frozenset({1, 2})}
+ g = (w for w in y)
+ t = a if b else c
+ f = f"{a!r:>{b}} {'lit'} {a=}"
+ m = b"bytes" rb"raw"
+ sl = y[::2], y[1:], y[:1], y[0]
+ star_call = print(*y, **{})
+ unpack_assign, *rest = [1, 2, 3]
+ (p := 9)
+ del nonlocal_target
+ return self
+
+async def aio():
+ async with open(os.devnull) as fh:
+ pass
+ async for _ in agen():
+ break
+ await coro()
+
+def agen(): ...
+def coro(): ...
+
+def matcher(obj):
+ match obj:
+ case [1, 2, *rest]:
+ return rest
+ case {"k": v, **extra}:
+ return v, extra
+ case C(x=1) | None:
+ return None
+ case str() as s if s:
+ return s
+ case _:
+ return obj
+
+def generic[T, *Ts, **P](x: T) -> T:
+ type Alias[U] = list[U]
+ return x
+
+try:
+ 1 / 0
+except* ZeroDivisionError as eg:
+ pass
+finally:
+ pass
+
+while False:
+ continue
+else:
+ pass
+
+for i in range(1):
+ break
+else:
+ pass
+
+with open(os.devnull) as a, open(os.devnull) as b:
+ pass
+
+if CONST:
+ pass
+elif system:
+ pass
+else:
+ assert True, "msg"
+
+yield_holder = lambda: (x for x in ())
+'''
+
+
+class ParserStabilityAugTests(unittest.TestCase):
+ def test_broad_syntax_corpus_compiles_and_roundtrips(self):
+ tree = ast.parse(CORPUS)
+ compile(tree, "<pep798-corpus>", "exec")
+ # unparse → reparse round-trip walks the AST and the parser again
+ rendered = ast.unparse(tree)
+ reparsed = ast.parse(rendered)
+ compile(reparsed, "<pep798-corpus-2>", "exec")
+
+ def test_classic_comprehensions_unchanged(self):
+ ns = {}
+ exec(
+ "lc=[i*i for i in range(4)]; sc={i%2 for i in range(4)};"
+ "dc={i: -i for i in range(3)}; ge=sum(i for i in range(4))",
+ ns,
+ )
+ self.assertEqual(ns["lc"], [0, 1, 4, 9])
+ self.assertEqual(ns["sc"], {0, 1})
+ self.assertEqual(ns["dc"], {0: 0, 1: -1, 2: -2})
+ self.assertEqual(ns["ge"], 6)
+
+ def test_classic_call_and_display_unpacking_unchanged(self):
+ # Pre-PEP-798 star/double-star forms (displays + calls) unchanged.
+ a, b = [1, 2], {"x": 3}
+ self.assertEqual([*a, 9], [1, 2, 9])
+ self.assertEqual({*a, 9}, {1, 2, 9})
+ self.assertEqual((*a, 9), (1, 2, 9))
+ self.assertEqual({**b, "y": 4}, {"x": 3, "y": 4})
+ self.assertEqual(dict(**b), {"x": 3})
+
+ def test_unpacking_remains_illegal_outside_element_position(self):
+ # These are SyntaxError both pre- and post-PEP-798: the PEP only
+ # legalizes * / ** at the top level of the comprehension element.
+ for bad in (
+ "{*x: 1 for x in y}", # starred dict-comprehension key
+ "[x, *y for y in z]", # star not at top level of the element
+ "[(*y) for y in z]", # parenthesized star is not a valid expr
+ ):
+ with self.subTest(bad=bad):
+ with self.assertRaises(SyntaxError):
+ compile(bad, "<pep798-bad>", "eval")
+
+ def test_parser_error_positions_stable(self):
+ for bad, needle in (
+ ("def f(:", "invalid syntax"),
+ ("x = [1, 2", "was never closed"),
+ ("class :", "invalid syntax"),
+ ):
+ with self.subTest(bad=bad):
+ with self.assertRaises(SyntaxError) as cm:
+ compile(bad, "<bad>", "exec")
+ self.assertIn(needle, str(cm.exception))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/Lib/test/test_pep798_unpacking_aug.py b/Lib/test/test_pep798_unpacking_aug.py
new file mode 100644
index 0000000..79ae774
--- /dev/null
+++ b/Lib/test/test_pep798_unpacking_aug.py
@@ -0,0 +1,158 @@
+"""Augmented F2P tests for PEP 798 (unpacking in comprehensions).
+
+Every test drives the documented PEP 798 syntax forms — ``*`` in list/set
+comprehensions and generator expressions, ``**`` in dict comprehensions, and
+their ``async for`` variants — through plain compilation and evaluation. No
+PR-internal symbol is referenced; the new syntax itself is the documented
+public surface, so each test fails with SyntaxError on the pre-solution
+interpreter and passes once PEP 798 is implemented.
+"""
+
+import ast
+import asyncio
+import subprocess
+import sys
+import textwrap
+import unittest
+
+
+async def _agen(items):
+ for item in items:
+ yield item
+
+
+class UnpackingComprehensionAugTests(unittest.TestCase):
+ def run_async(self, coro):
+ return asyncio.run(coro)
+
+ def test_setcomp_star_unpacks_each_iterable(self):
+ # PEP 798: {*expr for x in it} merges each iterable into the set
+ # (set.update semantics). Guards both the setcomp grammar rule and
+ # the SET_UPDATE opcode selection.
+ result = eval("{*t for t in [(1, 2), (2, 3), ()]}")
+ self.assertEqual(result, {1, 2, 3})
+
+ # An unhashable iterable element must still unpack (update), not be
+ # added as a single element (add would raise TypeError for a list).
+ result = eval("{*lst for lst in [[1, 2], [3]]}")
+ self.assertEqual(result, {1, 2, 3})
+
+ def test_listcomp_and_genexp_star_flatten(self):
+ # Documented list-comprehension and generator-expression forms.
+ self.assertEqual(eval("[*t for t in [(1, 2), (), (3,)]]"), [1, 2, 3])
+ gen = eval("(*t for t in [(1, 2), (3,)])")
+ self.assertEqual(next(gen), 1)
+ self.assertEqual(list(gen), [2, 3])
+
+ def test_dictcomp_double_star_merges_with_update_semantics(self):
+ # {**d for d in dicts}: dict.update semantics — later values win,
+ # duplicate keys are allowed.
+ dicts = [{1: "a"}, {2: "b"}, {1: "c"}]
+ result = eval("{**d for d in dicts}", {"dicts": dicts})
+ self.assertEqual(result, {1: "c", 2: "b"})
+
+ def test_dictcomp_double_star_compiles_from_ast(self):
+ # The AST for {**d for d in ds} carries DictComp.value == None; the
+ # compiler's AST validation must accept it. Run in a subprocess so a
+ # validation crash on a broken interpreter is a clean test failure
+ # rather than taking down the test runner.
+ code = textwrap.dedent(
+ """
+ import ast
+ tree = ast.parse('{**d for d in ds}', mode='eval')
+ compiled = compile(tree, '<pep798>', 'eval')
+ result = eval(compiled, {'ds': [{1: 2}, {3: 4}, {1: 0}]})
+ assert result == {1: 0, 3: 4}, result
+ print('OK')
+ """
+ )
+ proc = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True, text=True, timeout=60,
+ )
+ self.assertEqual(proc.returncode, 0, proc.stderr)
+ self.assertIn("OK", proc.stdout)
+
+ def test_async_listcomp_star_extends(self):
+ async def main():
+ return [*item async for item in _agen([(1, 2), (3,), ()])]
+
+ self.assertEqual(self.run_async(main()), [1, 2, 3])
+
+ def test_async_setcomp_star_updates(self):
+ async def main():
+ return {*item async for item in _agen([(1, 2), (2, 3)])}
+
+ self.assertEqual(self.run_async(main()), {1, 2, 3})
+
+ def test_async_genexp_star_flattens(self):
+ async def main():
+ agen = (*item async for item in _agen([(1,), (2, 3)]))
+ return [x async for x in agen]
+
+ self.assertEqual(self.run_async(main()), [1, 2, 3])
+
+ def test_async_dictcomp_double_star_allows_duplicate_keys(self):
+ # DICT_UPDATE semantics in the async path: duplicates allowed,
+ # right-most wins. Run in a subprocess so a broken interpreter that
+ # mis-selects the merge opcode (which can crash the process) is a
+ # clean test failure rather than taking down the test runner.
+ code = textwrap.dedent(
+ """
+ import asyncio
+
+ async def agen(items):
+ for item in items:
+ yield item
+
+ async def main():
+ return {**d async for d in agen([{1: "a"}, {2: "b"}, {1: "c"}])}
+
+ result = asyncio.run(main())
+ assert result == {1: "c", 2: "b"}, result
+ print("OK")
+ """
+ )
+ proc = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True, text=True, timeout=60,
+ )
+ self.assertEqual(proc.returncode, 0, proc.stderr)
+ self.assertIn("OK", proc.stdout)
+
+ def test_nested_and_conditional_unpacking_forms(self):
+ # Conditional clauses and nested fors combine with unpacking.
+ self.assertEqual(
+ eval("[*t for t in [(1, 2), (3, 4), (5,)] if len(t) == 2]"),
+ [1, 2, 3, 4],
+ )
+ self.assertEqual(
+ eval("[*t for pair in [((1,), (2, 3))] for t in pair]"),
+ [1, 2, 3],
+ )
+ self.assertEqual(
+ eval("{**d for ds in [[{1: 2}], [{3: 4}]] for d in ds}"),
+ {1: 2, 3: 4},
+ )
+
+ def test_ast_shapes_of_unpacking_comprehensions(self):
+ # ast.parse produces the documented node shapes: the DictComp node
+ # for ** has value=None per the updated ASDL, and a starred setcomp
+ # element is a Starred node that compiles and evaluates.
+ # (ast.unparse of the ** form is not exercised: the reference patch
+ # does not extend _ast_unparse.py for value=None DictComp nodes.)
+ tree = ast.parse("{**d for d in ds}", mode="eval")
+ comp = tree.body
+ self.assertIsInstance(comp, ast.DictComp)
+ self.assertIsNone(comp.value)
+ self.assertEqual(len(comp.generators), 1)
+
+ tree = ast.parse("{*t for t in ts}", mode="eval")
+ self.assertIsInstance(tree.body, ast.SetComp)
+ self.assertIsInstance(tree.body.elt, ast.Starred)
+ compiled = compile(tree, "<pep798-ast>", "eval")
+ self.assertEqual(eval(compiled, {"ts": [(1, 2), (3,)]}), {1, 2, 3})
+
+
+if __name__ == "__main__":
+ unittest.main()