File size: 11,689 Bytes
a4edccc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 | 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()
|