tests: parse the translator in pieces: 7 s -> 1 s per uncached import, 60 s -> 17 s in five standalone tests (TEST-TRANSLATOR-PIECEWISE-PARSE) #2237

Merged
syfyra merged 4 commits from upstream-pr/2237 into main 2026-12-01 15:18:05 +00:00
syfyra commented 2026-11-26 09:53:51 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by syfyra on 2026-11-26T09:53:51Z.


Claimed in the coordination issue as: TEST-TRANSLATOR-PIECEWISE-PARSE (https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7188514735)

What and why

A test process that finds no valid .pyc of tools/rdna2spirv.py compiles the 1.2 MB file from source. On CPython 3.12, 3.13.0 to 3.13.15 and 3.14.0 to 3.14.7 that takes 7 s, 0.1 s of it code generation: the tokenizer copies the rest of its input at every f-string field (update_fstring_expr: strlen(tok->cur), PyMem_Malloc, strncpy), and import hands the file over as one string, so the cost grows with the square of the file (4,759 f-strings, about 12,700 fields). CPython fixed it in 3.13.16, 3.14.8 and 3.15.0 (gh-155525 in CPython; read from the release tags). 3.12, which every CI job pins, is security-only and keeps it: v3.12.16 still copies.

That compile happens after every edit of the translator (most test files set sys.dont_write_bytecode, so the stale .pyc is never replaced: 7.2 s on every run of one test file until something else rewrites it), for each of the 14 translator copies test_mutations.py runs, and always where PYTHONDONTWRITEBYTECODE is set.

tests/semantic/piecewise_parse.py parses a source in pieces of 300 lines and joins them into the tree a whole-file parse gives: tokenize (line by line, linear) finds where statements start, top-level statements are parsed in runs, a longer top-level class is cut between the statements of its body, and each piece is parsed with one newline in front for every line before it, so positions are the file's. Anything that does not fit (a piece that does not parse, barry_as_FLUFL, a NUL, a statement that does not start where tokenize said) returns None and the source is compiled the usual way. tests/semantic/support.py hands the modules of TOOLS_DIR to a SourceFileLoader subclass that compiles that tree, through a sys.meta_path finder placed just before PathFinder, and only on the interpreters above. A valid .pyc is still used first.

A .pyc does not help a test that reads the translator's syntax tree. tests/test_runtime_paths.py, tests/test_isa_coverage.py, tests/test_shader_stage_resume.py, tests/test_cmake_translator_deps.py and tests/test_resource_hygiene.py made seven whole-file ast.parse calls on it between them, in every job that runs the standalone tests (check, stdlib-tests-linux, macos-python). They now call piecewise_parse.parse, which takes pieces on the interpreters above and the whole-file parse elsewhere. tools/isa_coverage.py parses inside scan_translator and accepted_names; its test patches ast.parse around those calls on the real translator, and the tool is not edited (#1799 changes those lines).

The helper is in tests/semantic/ because it is test infrastructure that support.py imports as a sibling, like spirv_mini_interp.py; tools/ is what make_game.py runs and what test_mutations.py copies and sabotages, and the loader for TOOLS_DIR should not come out of TOOLS_DIR.

Not changed: files that import rdna2spirv before support or without it (247 of the 491 at 9cd0c3f42) still pay the 7 s; test_mutations.py keeps 13 in-process compile() calls on the whole translator text (its CRLF test), which is what is left of its time. scripts/run_semantic_tests.py, test_mutations.py and everything under tools/ are not edited. git merge-tree and git merge-file report no conflict with #2114, #1516, #2201, #1799, #565, #1361, #1372 or #1529.

One visible difference: when a module of tools/ has a syntax error, the SyntaxError (file, line, caret, message) is the same, but the traceback above it shows five importlib frames and support.py's source_to_code, which a plain import hides.

Tested

Windows 11, 8 logical CPUs, no GPU involved. The loader, measured at 9cd0c3f42 (before = that commit, after = the first commit of this branch on it):

before after
python -m unittest discover -s tests/semantic -p test_ps_semantics.py, Python 3.14.7 7.3 s 1.3 s
the same, Python 3.13.13 7.6 s 1.6 s
the same after the translator's mtime changed, bytecode writing allowed 7.2 s every run 1.2 s every run
tests/semantic/test_mutations.py alone 196.9 s 113.3 s
python -I scripts/run_semantic_tests.py tests/semantic (491 files, 6,312 tests, 0 failed, 8 jobs), bytecode writing allowed 246.4 s 161.3 s
the same with PYTHONDONTWRITEBYTECODE=1 597.6 s 396.7 s
-p "test_[bpv]*.py" on Python 3.13.13 (119 files, 1,892 tests, 0 failed) 171.6 s 88.5 s

The long ones are single runs on a machine other work shares. The branch has since been rebased onto a73a57e13: there one file takes 1.3 s again (1.3, 1.3, 1.4) and a plain import of the translator 7.4 s; the long runs were not repeated.

The five standalone tests, Python 3.14.7 at a73a57e13, with a valid .pyc of the translator as after CI's compileall step, two runs each (they agree within 0.3 s):

before after
python -I tests/test_runtime_paths.py (2 parses) 16.0 s 3.7 s
python -I tests/test_isa_coverage.py (2) 15.0 s 2.5 s
python -I tests/test_shader_stage_resume.py (1) 14.2 s 8.2 s
python -I tests/test_cmake_translator_deps.py (1) 7.6 s 1.4 s
python -I tests/test_resource_hygiene.py (1) 7.6 s 1.3 s
sum 60.4 s 17.1 s

They were found with a wrapper around compile that records every source over 500 kB, run over the 78 tests/test_*.py that mention the translator: nine such parses, these seven and two in tests/test_piecewise_parse.py itself, which needs the whole-file parse as its reference.

python -I tests/test_piecewise_parse.py: 26 tests, 46 s on 3.14.7 and 49 s on 3.13.13. It compares the trees for the 1,359 Python files under tools/, scripts/, tests/ and make_game.py in pieces of one statement (and the long files of tools/ in pieces of 300 lines; the translator in a test of its own), ast.dump(..., include_attributes=True) for 15 hand-written sources in pieces of 1, 2, 3, 5 and 8 lines with LF, CRLF and CR line ends, the exception for 28 sources with a syntax error and 9 the compiler rejects against compile's, the warnings, the code objects of 7 files and of the translator against compile(bytes), and the finder and loader on throwaway folders. It fails on main (the module does not exist).

Also run: python -m compileall -q on the changed files, python -I tests/test_text_write_line_endings.py, python -I tests/test_ci_registration.py, python -I tests/test_semantic_translator_use.py, python -I tests/test_run_semantic_tests.py (3.13.13, at 9cd0c3f42), python -I scripts/check_no_game_data.py on the changed files, and the five tests above on 3.13.13.

From the review (1f92ae6a5):

  • lixonik ran e654d10fd on CPython 3.12.1: 24 of the 25 tests passed and test_barry_as_flufl_is_parsed_whole errored. That parser does not read the barry_as_FLUFL import from the source (_PyPegen_checked_future_import is missing in v3.12.0, v3.12.1 and v3.13.0 and present in v3.12.16, v3.13.13 and v3.14.7), so the stock compile the test took as its reference rejects <>. The test now takes the running interpreter's compile outcome, tree or error, for both spellings. I have no 3.12.1: the new test passes and the old one fails with that parser's behaviour simulated.
  • GrahamboJangles measured the translator on a fixed interpreter (3.14.9: 0.21 s whole, 0.54 s in pieces), so parse() now takes pieces only where needed() says so, as support.py already did for the loader.

Not tested: Python 3.12 here (not installed; the 3.12.1 run above is the reviewer's, and CI's own run on 3.12 is the check), Linux and macOS, and an interpreter with the fix (3.13.16+, 3.14.8+) here.

GPUs tested: n/a

AI-assisted: yes (Claude Code)

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (n/a: no translator rule)

🤖 Generated with Claude Code

<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5507789504 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2237). Originally posted by [syfyra](https://github.com/syfyra) on 2026-11-26T09:53:51Z. --- Claimed in the coordination issue as: TEST-TRANSLATOR-PIECEWISE-PARSE (https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7188514735) ### What and why A test process that finds no valid `.pyc` of `tools/rdna2spirv.py` compiles the 1.2 MB file from source. On CPython 3.12, 3.13.0 to 3.13.15 and 3.14.0 to 3.14.7 that takes 7 s, 0.1 s of it code generation: the tokenizer copies the rest of its input at every f-string field (`update_fstring_expr`: `strlen(tok->cur)`, `PyMem_Malloc`, `strncpy`), and `import` hands the file over as one string, so the cost grows with the square of the file (4,759 f-strings, about 12,700 fields). CPython fixed it in 3.13.16, 3.14.8 and 3.15.0 (gh-155525 in CPython; read from the release tags). 3.12, which every CI job pins, is security-only and keeps it: v3.12.16 still copies. That compile happens after every edit of the translator (most test files set `sys.dont_write_bytecode`, so the stale `.pyc` is never replaced: 7.2 s on every run of one test file until something else rewrites it), for each of the 14 translator copies `test_mutations.py` runs, and always where `PYTHONDONTWRITEBYTECODE` is set. `tests/semantic/piecewise_parse.py` parses a source in pieces of 300 lines and joins them into the tree a whole-file parse gives: `tokenize` (line by line, linear) finds where statements start, top-level statements are parsed in runs, a longer top-level class is cut between the statements of its body, and each piece is parsed with one newline in front for every line before it, so positions are the file's. Anything that does not fit (a piece that does not parse, `barry_as_FLUFL`, a NUL, a statement that does not start where `tokenize` said) returns None and the source is compiled the usual way. `tests/semantic/support.py` hands the modules of `TOOLS_DIR` to a `SourceFileLoader` subclass that compiles that tree, through a `sys.meta_path` finder placed just before `PathFinder`, and only on the interpreters above. A valid `.pyc` is still used first. A `.pyc` does not help a test that reads the translator's syntax tree. `tests/test_runtime_paths.py`, `tests/test_isa_coverage.py`, `tests/test_shader_stage_resume.py`, `tests/test_cmake_translator_deps.py` and `tests/test_resource_hygiene.py` made seven whole-file `ast.parse` calls on it between them, in every job that runs the standalone tests (`check`, `stdlib-tests-linux`, `macos-python`). They now call `piecewise_parse.parse`, which takes pieces on the interpreters above and the whole-file parse elsewhere. `tools/isa_coverage.py` parses inside `scan_translator` and `accepted_names`; its test patches `ast.parse` around those calls on the real translator, and the tool is not edited (#1799 changes those lines). The helper is in `tests/semantic/` because it is test infrastructure that `support.py` imports as a sibling, like `spirv_mini_interp.py`; `tools/` is what `make_game.py` runs and what `test_mutations.py` copies and sabotages, and the loader for `TOOLS_DIR` should not come out of `TOOLS_DIR`. Not changed: files that import `rdna2spirv` before `support` or without it (247 of the 491 at 9cd0c3f42) still pay the 7 s; `test_mutations.py` keeps 13 in-process `compile()` calls on the whole translator text (its CRLF test), which is what is left of its time. `scripts/run_semantic_tests.py`, `test_mutations.py` and everything under `tools/` are not edited. `git merge-tree` and `git merge-file` report no conflict with #2114, #1516, #2201, #1799, #565, #1361, #1372 or #1529. One visible difference: when a module of `tools/` has a syntax error, the SyntaxError (file, line, caret, message) is the same, but the traceback above it shows five importlib frames and `support.py`'s `source_to_code`, which a plain import hides. ### Tested Windows 11, 8 logical CPUs, no GPU involved. The loader, measured at 9cd0c3f42 (before = that commit, after = the first commit of this branch on it): | | before | after | | --- | --- | --- | | `python -m unittest discover -s tests/semantic -p test_ps_semantics.py`, Python 3.14.7 | 7.3 s | 1.3 s | | the same, Python 3.13.13 | 7.6 s | 1.6 s | | the same after the translator's mtime changed, bytecode writing allowed | 7.2 s every run | 1.2 s every run | | `tests/semantic/test_mutations.py` alone | 196.9 s | 113.3 s | | `python -I scripts/run_semantic_tests.py tests/semantic` (491 files, 6,312 tests, 0 failed, 8 jobs), bytecode writing allowed | 246.4 s | 161.3 s | | the same with `PYTHONDONTWRITEBYTECODE=1` | 597.6 s | 396.7 s | | `-p "test_[bpv]*.py"` on Python 3.13.13 (119 files, 1,892 tests, 0 failed) | 171.6 s | 88.5 s | The long ones are single runs on a machine other work shares. The branch has since been rebased onto a73a57e13: there one file takes 1.3 s again (1.3, 1.3, 1.4) and a plain import of the translator 7.4 s; the long runs were not repeated. The five standalone tests, Python 3.14.7 at a73a57e13, with a valid `.pyc` of the translator as after CI's `compileall` step, two runs each (they agree within 0.3 s): | | before | after | | --- | --- | --- | | `python -I tests/test_runtime_paths.py` (2 parses) | 16.0 s | 3.7 s | | `python -I tests/test_isa_coverage.py` (2) | 15.0 s | 2.5 s | | `python -I tests/test_shader_stage_resume.py` (1) | 14.2 s | 8.2 s | | `python -I tests/test_cmake_translator_deps.py` (1) | 7.6 s | 1.4 s | | `python -I tests/test_resource_hygiene.py` (1) | 7.6 s | 1.3 s | | sum | 60.4 s | 17.1 s | They were found with a wrapper around `compile` that records every source over 500 kB, run over the 78 `tests/test_*.py` that mention the translator: nine such parses, these seven and two in `tests/test_piecewise_parse.py` itself, which needs the whole-file parse as its reference. `python -I tests/test_piecewise_parse.py`: 26 tests, 46 s on 3.14.7 and 49 s on 3.13.13. It compares the trees for the 1,359 Python files under tools/, scripts/, tests/ and make_game.py in pieces of one statement (and the long files of tools/ in pieces of 300 lines; the translator in a test of its own), `ast.dump(..., include_attributes=True)` for 15 hand-written sources in pieces of 1, 2, 3, 5 and 8 lines with LF, CRLF and CR line ends, the exception for 28 sources with a syntax error and 9 the compiler rejects against `compile`'s, the warnings, the code objects of 7 files and of the translator against `compile(bytes)`, and the finder and loader on throwaway folders. It fails on main (the module does not exist). Also run: `python -m compileall -q` on the changed files, `python -I tests/test_text_write_line_endings.py`, `python -I tests/test_ci_registration.py`, `python -I tests/test_semantic_translator_use.py`, `python -I tests/test_run_semantic_tests.py` (3.13.13, at 9cd0c3f42), `python -I scripts/check_no_game_data.py` on the changed files, and the five tests above on 3.13.13. From the review (1f92ae6a5): - lixonik ran e654d10fd on CPython 3.12.1: 24 of the 25 tests passed and `test_barry_as_flufl_is_parsed_whole` errored. That parser does not read the `barry_as_FLUFL` import from the source (`_PyPegen_checked_future_import` is missing in v3.12.0, v3.12.1 and v3.13.0 and present in v3.12.16, v3.13.13 and v3.14.7), so the stock compile the test took as its reference rejects `<>`. The test now takes the running interpreter's compile outcome, tree or error, for both spellings. I have no 3.12.1: the new test passes and the old one fails with that parser's behaviour simulated. - GrahamboJangles measured the translator on a fixed interpreter (3.14.9: 0.21 s whole, 0.54 s in pieces), so `parse()` now takes pieces only where `needed()` says so, as `support.py` already did for the loader. Not tested: Python 3.12 here (not installed; the 3.12.1 run above is the reviewer's, and CI's own run on 3.12 is the check), Linux and macOS, and an interpreter with the fix (3.13.16+, 3.14.8+) here. GPUs tested: n/a AI-assisted: yes (Claude Code) ### Checklist - [x] Based on current `main` and merges cleanly (a conflicting pull request is labeled `needs rebase`). - [x] One topic; follow-up work goes in a new pull request. - [x] No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here. - [ ] A new translator rule is in the contract table of `docs/design.md`, with how it was confirmed. (n/a: no translator rule) 🤖 Generated with [Claude Code](https://claude.com/claude-code)
lixonik commented 2026-11-26 11:11:20 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by lixonik on 2026-11-26T11:11:20Z.

Review: COMMENTED


Windows 11 / CPython 3.12.1: 24/25 piecewise parser checks and 22/22 computed-I/J semantic tests passed. The parser suite has one error in the new Barry regression. Details inline.

AI-assisted.

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6073115399 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2237#pullrequestreview-6073115399). Originally posted by [lixonik](https://github.com/lixonik) on 2026-11-26T11:11:20Z. **Review:** COMMENTED --- Windows 11 / CPython 3.12.1: 24/25 piecewise parser checks and 22/22 computed-I/J semantic tests passed. The parser suite has one error in the new Barry regression. Details inline. AI-assisted.
lixonik commented 2026-11-26 11:11:20 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by lixonik on 2026-11-26T11:11:20Z.

Code review location: tests/test_piecewise_parse.py; line 700

@@ -0,0 +1,936 @@
+"""tests/semantic/piecewise_parse.py builds the tree a whole-file parse builds, and support.py's loader the same code.
+
+    python -I tests/test_piecewise_parse.py
+
+The translator tests load tools/rdna2spirv.py through that loader, so "the same" is the whole point: a test that ran a
+slightly different translator would prove nothing. Checked here, with nothing but the standard library:
+
+* hand-written sources for each boundary rule (decorators, the clauses of `if`/`try`/`for`/`while` at top level and
+  in a class, a class header over several lines, nested classes, a docstring and `from __future__`, strings and
+  brackets whose inner lines start at column 0, non-ASCII text, CRLF), cut into pieces of 1, 2, 3, 5 and 8 lines:
+  `ast.dump(tree, include_attributes=True)` equals the whole-file parse's;
+* sources with an error: the pieces are given up and `parse` raises what `compile` raises (type, message, line,
+  column, text);
+* every Python file under tools/, scripts/ and tests/ and make_game.py in pieces of one statement, and the long
+  files of tools/ also in pieces of the size the loader uses: the two trees agree in every field and position
+  (`same_tree`, which is held against the dumps on the hand-written sources);
+* the code object compiled from the pieces against the one `compile` makes from the file's bytes, for some files;
+* tools/rdna2spirv.py, tree (by its dump) and code object, in one test of its own: on the interpreters the pieces
+  are for (CPython 3.12 to 3.14.7) each of its two whole-file parses takes 7 s, which is why it is `_slow`;
+* support.py's finder and loader on throwaway folders, and that support.py installs them only where needed.
+
+About 45 s in all on those interpreters, most of it the repository scan and the translator.
+"""
+import ast
+import importlib.machinery
+import importlib.util
+import os
+import py_compile
+import sys
+import tempfile
+import types
+import unittest
+import warnings
+from unittest import mock
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+SEMANTIC = os.path.join(ROOT, "tests", "semantic")
+TOOLS = os.path.join(ROOT, "tools")
+TRANSLATOR = os.path.join(TOOLS, "rdna2spirv.py")
+sys.path.insert(0, SEMANTIC)
+
+import piecewise_parse as pp  # noqa: E402
+import support  # noqa: E402  (imports the translator the way the translator tests do)
+
+SPLITS = sys.version_info >= (3, 12)        # older interpreters are always parsed whole (piecewise_parse.parse_pieces)
+SIZES = (1, 2, 3, 5, 8)
+DUMP = dict(include_attributes=True, **({"show_empty": True} if sys.version_info >= (3, 13) else {}))
+
+
+def whole(source, filename="<test>"):
+    return compile(source, filename, "exec", ast.PyCF_ONLY_AST, dont_inherit=True)
+
+
+def dump(tree):
+    return ast.dump(tree, **DUMP)
+
+
+def difference(got, expected):
+    """Where two dumps part, with a little of each: the dumps themselves run to megabytes."""
+    at = len(os.path.commonprefix([got, expected]))
+    near = slice(max(0, at - 90), at + 90)
+    return f"dumps differ at character {at}: ...{got[near]!r} against ...{expected[near]!r}"
+
+
+def same_tree(a, b):
+    """Whether two trees agree in every field and every position: what equal dumps say, without building them.
+    The dumps of the repository's 24 MB of Python take 12 s, this takes 3; PiecesTest holds it against `dump`."""
+    todo = [(a, b)]
+    while todo:
+        x, y = todo.pop()
+        if type(x) is not type(y):
+            return False
+        if isinstance(x, ast.AST):
+            todo.extend((getattr(x, name, None), getattr(y, name, None)) for name in x._fields + x._attributes)
+        elif type(x) is list:
+            if len(x) != len(y):
+                return False
+            todo.extend(zip(x, y))
+        elif (repr(x) != repr(y)) if isinstance(x, (float, complex)) else (x != y):
+            return False
+    return True
+
+
+def error_facts(call, *args):
+    """What the SyntaxError `call` raises says (a ValueError before 3.12 for a NUL), or None when it raises none."""
+    try:
+        call(*args)
+    except SyntaxError as e:
+        return type(e).__name__, e.msg, e.filename, e.lineno, e.offset, e.end_lineno, e.end_offset, e.text
+    except ValueError as e:
+        return type(e).__name__, str(e)
+    return None
+
+
+def code_facts(code):
+    """Everything a code object holds as plain values, the code objects among its constants included."""
+    return (code.co_name, code.co_qualname, code.co_filename, code.co_firstlineno, code.co_flags, code.co_argcount,
+            code.co_posonlyargcount, code.co_kwonlyargcount, code.co_nlocals, code.co_stacksize, code.co_code,
+            code.co_names, code.co_varnames, code.co_freevars, code.co_cellvars, code.co_linetable,
+            code.co_exceptiontable, list(code.co_positions()),
+            [code_facts(c) if isinstance(c, types.CodeType) else (type(c).__name__, repr(c)) for c in code.co_consts])
+
+
+def python_files():
+    """Every .py file under tools/, scripts/ and tests/, and make_game.py."""
+    yield os.path.join(ROOT, "make_game.py")
+    for top in ("tools", "scripts", "tests"):
+        for base, dirs, names in os.walk(os.path.join(ROOT, top)):
+            dirs[:] = sorted(d for d in dirs if d != "__pycache__" and not d.startswith("."))
+            for name in sorted(names):
+                if name.endswith(".py"):
+                    yield os.path.join(base, name)
+
+
+def read(path):
+    with open(path, "rb") as f:
+        return f.read()
+
+
+# --- hand-written sources, one per boundary rule ---------------------------------------------------------------
+
+DECORATORS = r'''
+import functools
+
+
+def deco(f):
+    return f
+
+
+@deco
+def a():
+    return 1
+
+
+@deco
[email protected](a)
+def b():
+    return 2
+
+
+@deco
+class C:
+    @staticmethod
+    def m():
+        return 3
+
+    @property
+    @deco
+    def p(self):
+        return 4
+
+    @functools.lru_cache(
+        maxsize=None,
+    )
+    def q(self):
+        return 5
+
+    @deco
+    class Inner:
+        pass
+
+    tail = 6
+x = 1
+'''
+
+CLAUSES_AT_TOP_LEVEL = r'''
+import os
+if os.sep == "/":
+    a = 1
+elif os.sep == ":":
+    a = 2
+else:
+    a = 3
+try:
+    b = int("x")
+except ValueError:
+    b = 0
+except (TypeError, KeyError) as e:
+    b = 1
+else:
+    b = 2
+finally:
+    c = 3
+try:
+    d = 4
+finally:
+    d = 5
+for i in range(3):
+    pass
+else:
+    e = 6
+while False:
+    pass
+else:
+    f = 7
+with open(os.devnull) as g:
+    pass
+if a: b = 1
+elif b: b = 2
+else: b = 3
+try: h = 8
+except Exception: h = 9
+i = 0; j = 1; k = 2
+'''
+
+CLAUSES_IN_A_CLASS = r'''
+class K:
+    if True:
+        a = 1
+    elif False:
+        a = 2
+    else:
+        a = 3
+    try:
+        b = 1
+    except Exception:
+        b = 2
+    else:
+        b = 3
+    finally:
+        c = 4
+    for i in ():
+        pass
+    else:
+        d = 5
+    while False:
+        pass
+    else:
+        e = 6
+
+    def m(self):
+        if self:
+            return 1
+        else:
+            return 2
+        try:
+            pass
+        finally:
+            pass
+
+    async def n(self):
+        async with self as s:
+            async for t in s:
+                await t
+    f = 7; g = 8
+    h = 9;
+last = K
+'''
+
+MATCH_AND_EXCEPT_STAR = r'''
+def f(x):
+    match x:
+        case 1:
+            return "one"
+        case [a, b]:
+            return a
+        case _:
+            return None
+
+
+match = 1
+case = match
+match case:
+    case 1:
+        pass
+
+
+class M:
+    match case:
+        case 1:
+            y = 1
+        case _:
+            y = 2
+    case = 3
+    try:
+        z = 1
+    except* ValueError:
+        z = 2
+    except* TypeError:
+        z = 3
+after = M
+'''
+
+CLASS_HEADER_OVER_SEVERAL_LINES = r'''
+class Base:
+    pass
+
+
+class A(
+    Base,
+    metaclass=type,
+):
+    """Doc."""
+    x = 1
+
+    def m(self):
+        return self.x
+
+    y = 2
+
+
+class B(Base,
+        object): z = 3
+
+
+class C(
+        Base):
+    def n(self): return 4
+    w = 5
+'''
+
+NESTED_CLASSES = r'''
+class Outer:
+    a = 1
+
+    class Middle:
+        b = 2
+
+        class Inner:
+            c = 3
+
+            def m(self):
+                class Local:
+                    d = 4
+                return Local
+
+        e = 5
+
+    f = 6
+
+    class Second: pass
+
+    g = 7
+
+
+class After(Outer.Middle):
+    pass
+'''
+
+DOCSTRING_AND_FUTURE = r'''"""Module docstring.
+
+class NotCode:
+    else:
+"""
+from __future__ import annotations
+from __future__ import division, generators
+
+import sys
+
+
+def f(a: Undefined) -> AlsoUndefined:
+    """Function docstring."""
+    return a
+
+
+class D:
+    """Class docstring."""
+
+    x: NotDefinedEither = 1
+'''
+
+COLUMN_ZERO = r'''
+text = """
+class NotAClass:
+    def not_a_method(self):
+else:
+@not_a_decorator
+"""
+value = (
+1,
+2,
+[
+3,
+],
+)
+call = dict(
+a=1,
+)
+other = text + \
+"tail"
+if value: first = {
+"k": 1,
+}
+else: first = None
+
+
+class Holder:
+    doc = """
+class StillNotAClass:
+    pass
+finally:
+"""
+    tup = (
+1,
+2,
+)
+
+    def method(self):
+        return f"""
+{self.doc}
+{
+self.tup
+!r:>{
+10
+}}
+""" + \
+"x"
+# a comment at column 0 inside the class body
+  # and one that fits no indentation level
+
+    after = 3
+    lst = [
+# a comment inside brackets
+4,
+]
+
+
+last = Holder
+'''
+
+F_STRINGS = r'''
+name = "x"
+plain = f"{name}"
+spec = f"{name!r:>{10}} {name=} {{literal}} {3.14:.{2}f}"
+joined = (f"{name}"
+          f"{name:{name}}"
+          "tail")
+
+
+class F:
+    def m(self, a, b):
+        self.emit(f"{a} = OpIAdd %uint {b} {self.cu(1)}")
+        return f"""{a}
+  {b}""", rf"\d{a}", f'{a["k"]}'
+
+    table = {f"k{i}": f"{i:02x}" for i in range(4)}
+'''
+
+LEFTOVERS = r'''#!/usr/bin/env python3
+# a comment before anything
+
+x = 1  # trailing comment
+lam = lambda: (yield)
+star, *rest = 1, 2, 3
+print(x); print(x)
+global_name: int
+assert x, "message"
+del star
+if x:
+    pass
+# comment after the last statement
+'''
+
+NO_FINAL_NEWLINE = "x = 1\nclass A:\n    y = 2\n    z = 3"
+ONLY_COMMENTS = "# nothing\n\n# here\n"
+BACKSLASH_LINES = "a = 1\n\\\nb = 2\nclass A:\n    c = 3\n\\\n    d = 4\n    e = 5\nf = 6\n"
+FORM_FEED = "a = 1\n\x0c\nb = 2\nclass A:\n    c = 3\n\x0c    d = 4\ne = 5\n"
+NON_ASCII = ('caf\xe9 = "\u017c\xf3\u0142w"; after = caf\xe9\n'
+             'class \xdc:\n'
+             '    \u03c0 = 3; q = "\U0001f600" + f"{\u03c0}\u2713"; r = q\n'
+             '    def m(self): return self.\u03c0, "\xe9"\n'
+             '    s = "\xe9" + \\\n'
+             '        "\u03c0"; t = s\n'
+             'last = "\xe9"; end = last\n')
+LATIN_1 = ('# -*- coding: latin-1 -*-\n'
+           'a = "\xe9\xe8"; b = a\n'
+           'class L:\n'
+           '    c = "\xfc"; d = c\n'
+           '    def m(self): return "\xdf", self.c\n')
+
+SOURCES = {
+    "decorators": DECORATORS,
+    "clauses at top level": CLAUSES_AT_TOP_LEVEL,
+    "clauses in a class": CLAUSES_IN_A_CLASS,
+    "tabs": CLAUSES_IN_A_CLASS.replace("    ", "\t"),
+    "match and except*": MATCH_AND_EXCEPT_STAR,
+    "class header over several lines": CLASS_HEADER_OVER_SEVERAL_LINES,
+    "nested classes": NESTED_CLASSES,
+    "docstring and __future__": DOCSTRING_AND_FUTURE,
+    "strings and brackets at column 0": COLUMN_ZERO,
+    "f-strings": F_STRINGS,
+    "leftovers": LEFTOVERS,
+    "no final newline": NO_FINAL_NEWLINE,
+    "form feed": FORM_FEED,
+    "non-ASCII": NON_ASCII,
+}
+if sys.version_info >= (3, 12):
+    SOURCES["type parameters"] = r'''
+type Pair[T] = tuple[T, T]
+
+
+def first[T](pair: Pair[T]) -> T:
+    return pair[0]
+
+
+class Box[T]:
+    type Inner = list[T]
+
+    def get[U](self, other: U) -> T | U:
+        return other
+
+    nested = f"{'a' + f'{1}'}"
+last = Box
+'''
+
+# A source with an error, and why it is one. None of them may come back as a tree.
+ERRORS = {
+    "bracket never closed": "a = 1\nb = (\nc = 3\nd = 4\n",
+    "else without if": "a = 1\nelse:\n    b = 2\n",
+    "else first": "else:\n    pass\n",
+    "elif after a class": "class A:\n    a = 1\n    b = 2\nelif a:\n    pass\n",
+    "indented first line": "    a = 1\nb = 2\n",
+    "unexpected indent": "a = 1\n    b = 2\nc = 3\n",
+    "unindent matches no level": "if a:\n        b = 1\n    c = 2\nd = 3\n",
+    "unindent matches no level in a class": "class A:\n    a = 1\n  b = 2\n",
+    "tabs against spaces": "if a:\n        b = 1\n\tc = 2\n",
+    "tabs against spaces between class statements": "class A:\n        a = 1\n\tb = 2\n",
+    "string never closed": 'a = 1\nb = """open\nc = 3\n',
+    "error in a class body": "class A:\n    a = 1\n    b = = 2\n    c = 3\nd = 4\n",
+    "error in the last statement of a class": "class A:\n    a = 1\n    b = 2\n    def m(self) return 3\n",
+    "except without try in a class": "class A:\n    a = 1\n    except E:\n        pass\n",
+    "decorator with nothing after it": "a = 1\n@dec\n",
+    "decorator before an assignment": "@dec\na = 1\nb = 2\n",
+    "decorator before an assignment in a class": "class A:\n    a = 1\n    @dec\n    b = 2\n    c = 3\n",
+    "character that is no token": "a = 1\nb = $\nc = 3\n",
+    "backslash at the end": "a = 1\nb = 2 \\",
+    "backslash line at the end": "a = 1\n\\\n",
+    "NUL": "a = 1\0\nb = 2\n",
+    "try without except": "try:\n    a = 1\nb = 2\n",
+    "class without a name": "a = 1\nclass:\n    pass\n",
+    "missing colon": "a = 1\ndef f()\n    return 1\n",
+    "f-string conversion": 'a = 1\nb = f"{a!z}"\nc = 3\n',
+    "f-string never closed": 'a = 1\nb = f"{a\nc = 3\n',
+    "assignment to a literal": "a = 1\n1 = a\nb = 2\n",
+    "statement after a one-line class": "class A: a = 1\n    b = 2\n",
+}
+
+# What compile refuses after parsing (an unknown feature already while parsing, from 3.14). Parsing in pieces and
+# compiling the tree says the same.
+COMPILE_ERRORS = {
+    "return outside a function": "def f():\n    pass\nreturn 1\n",
+    "return in a class": "class A:\n    a = 1\n    return 2\n    b = 3\n",
+    "__future__ after code": "a = 1\nfrom __future__ import annotations\nb = 2\n",
+    "break outside a loop": "a = 1\nbreak\n",
+    "nonlocal at module level": "a = 1\nnonlocal a\n",
+    "unknown __future__ feature": "from __future__ import no_such_feature\na = 1\n",
+    "from __future__ import braces": "a = 1\nb = 2\nfrom __future__ import braces\n",
+    "the same argument twice": "a = 1\ndef f(x, x):\n    pass\n",
+    "await outside a function": "class A:\n    a = 1\n    b = [await c for c in a]\n    d = 2\n",
+}
+
+
+class PiecesTest(unittest.TestCase):
+    def assert_same_tree(self, source, sizes=SIZES, must_split=SPLITS):
+        expected = dump(whole(source))
+        for size in sizes:
+            tree = pp.parse_pieces(source, "<test>", size)
+            if must_split:
+                self.assertIsNotNone(tree, f"pieces of {size} lines were given up")
+            if tree is not None:
+                got = dump(tree)
+                self.assertTrue(got == expected, f"pieces of {size} lines: " + difference(got, expected))
+                self.assertTrue(same_tree(tree, whole(source)), f"same_tree, pieces of {size} lines")
+            got = dump(pp.parse(source, "<test>", size))
+            self.assertTrue(got == expected, f"parse, pieces of {size} lines: " + difference(got, expected))
+
+    def test_each_boundary_rule_gives_the_whole_file_tree(self):
+        for name, source in SOURCES.items():
+            with self.subTest(name):
+                self.assert_same_tree(source)
+
+    def test_same_tree_sees_what_the_dumps_see(self):
+        source = "class A:\n    x = 1.0\n    def m(self):\n        return [self.x, 'a']\ny = A\n"
+        changes = {
+            "a column": lambda t: setattr(t.body[0].body[1].body[0].value.elts[0], "col_offset", 99),
+            "an end line": lambda t: setattr(t.body[0], "end_lineno", 99),
+            "a name": lambda t: setattr(t.body[1].value, "id", "B"),
+            "a constant": lambda t: setattr(t.body[0].body[0].value, "value", 2.0),
+            "the sign of a zero": lambda t: setattr(t.body[0].body[0].value, "value", -0.0),
+            "the type of a constant": lambda t: setattr(t.body[0].body[0].value, "value", 1),
+            "a statement fewer": lambda t: t.body[0].body.pop(),
+            "a statement more": lambda t: t.body.append(t.body[1]),
+            "another kind of node": lambda t: t.body.__setitem__(1, ast.Pass(lineno=5, col_offset=0, end_lineno=5,
+                                                                              end_col_offset=5)),
+        }
+        self.assertTrue(same_tree(whole(source), whole(source)))
+        for name, change in changes.items():
+            with self.subTest(name):
+                tree = whole(source.replace("1.0", "0.0") if "zero" in name else source)
+                reference = whole(source.replace("1.0", "0.0") if "zero" in name else source)
+                change(tree)
+                self.assertNotEqual(dump(tree), dump(reference))
+                self.assertFalse(same_tree(tree, reference))
+                self.assertFalse(same_tree(reference, tree))
+
+    def test_the_same_from_bytes_with_lf_crlf_and_cr_line_ends(self):
+        for name, source in SOURCES.items():
+            for ending in ("\n", "\r\n", "\r"):
+                with self.subTest(name, ending=ending):
+                    text = source.replace("\n", ending)
+                    self.assert_same_tree(text, sizes=(1, 3))
+                    self.assert_same_tree(text.encode("utf-8"), sizes=(1, 3))
+
+    def test_a_bom_and_a_coding_line_are_read_as_compile_reads_them(self):
+        self.assert_same_tree(b"\xef\xbb\xbf" + NON_ASCII.encode("utf-8"))
+        self.assert_same_tree(LATIN_1.encode("latin-1"))
+        self.assertEqual(whole(LATIN_1.encode("latin-1")).body[0].value.value,"\xe9\xe8")
+        # undecodable bytes and an unknown coding are compile's to report
+        for data in (b"a = 1\nb = '\xff'\n", b"# coding: no-such-codec\na = 1\n"):
+            with self.subTest(data):
+                self.assertIsNone(pp.parse_pieces(data, "<test>", 1))
+                self.assertIsNotNone(error_facts(whole, data))
+                self.assertEqual(error_facts(pp.parse, data, "<test>", 1), error_facts(whole, data))
+
+    def test_sources_with_nothing_to_cut(self):
+        for source in ("", "\n", ONLY_COMMENTS, "x = 1", "x = 1\n", "class A: pass\n", '"""Only a docstring."""\n'):
+            with self.subTest(source):
+                self.assert_same_tree(source)
+
+    def test_a_backslash_line_before_a_statement_is_given_up_not_guessed(self):
+        # "\\\n" on a line of its own joins the next line, so the statement after it starts a row early: valid
+        # Python that no cut may separate. The piece before it ends in the backslash and does not parse.
+        whole(BACKSLASH_LINES)
+        self.assert_same_tree(BACKSLASH_LINES, must_split=False)
+        if SPLITS:
+            self.assertIsNone(pp.parse_pieces(BACKSLASH_LINES, "<test>", 1))
+
+    def test_the_class_ends_where_its_last_token_ends(self):
+        # `x = 1;` ends at the 1 and its class at the semicolon: the end comes from the parser, not from the body
+        source = "class A:\n    a = 1\n    b = 2\n    x = 1;\ny = A\n"
+        self.assertNotEqual(whole(source).body[0].end_col_offset, whole(source).body[0].body[-1].end_col_offset)
+        self.assert_same_tree(source)
+
+    @unittest.skipUnless(SPLITS, "sources are parsed whole before Python 3.12")
+    def test_a_long_class_is_cut_inside_and_other_long_statements_are_not(self):
+        method = "    def m{0}(self):\n        return f'{{self}} {0}'\n\n"
+        source = "class Big:\n" + "".join(method.format(i) for i in range(40)) + "x = 1\n"
+        parsed = []
+        real_compile = compile
+        with mock.patch.object(pp, "compile", lambda text, *a, **k: parsed.append(text) or real_compile(text, *a, **k),
+                               create=True):
+            tree = pp.parse_pieces(source, "<test>", 30)
+        self.assertEqual(dump(tree), dump(whole(source)))
+        self.assertEqual(len(parsed), 5, [p.lstrip("\n")[:40] for p in parsed])
+        self.assertEqual([p.lstrip("\n").startswith(pp.DUMMY) for p in parsed], [False, True, True, True, False])
+        # a function of the same length is one statement and stays one piece
+        function = "def big():\n" + "".join(f"    a{i} = f'{{{i}}}'\n" for i in range(120)) + "x = 1\n"
+        del parsed[:]
+        with mock.patch.object(pp, "compile", lambda text, *a, **k: parsed.append(text) or real_compile(text, *a, **k),
+                               create=True):
+            tree = pp.parse_pieces(function, "<test>", 30)
+        self.assertEqual(dump(tree), dump(whole(function)))
+        self.assertEqual(len(parsed), 2)
+        # Each piece of a class starts a new indentation stack, so the tokenizer's tab rule between two statements
+        # of the body would go unchecked: a body not indented by the same characters throughout is never cut.
+        # (A form feed is the one valid way to get there; tabs against spaces are an error, see ErrorsTest.)
+        mixed = "class A:\n    a = 1\n\x0c    b = 2\n    c = 3\nd = 4\n"
+        del parsed[:]
+        with mock.patch.object(pp, "compile", lambda text, *a, **k: parsed.append(text) or real_compile(text, *a, **k),
+                               create=True):
+            tree = pp.parse_pieces(mixed, "<test>", 1)
+        self.assertEqual(dump(tree), dump(whole(mixed)))
+        self.assertEqual([p.lstrip("\n").startswith(pp.DUMMY) for p in parsed], [False, False])
+
+    def test_a_short_source_is_one_piece(self):
+        with mock.patch.object(pp, "_statements", side_effect=AssertionError("tokenized a source of one piece")):
+            self.assert_same_tree(DECORATORS, sizes=(pp.PIECE_LINES,))
+
+
+class ErrorsTest(unittest.TestCase):
+    def test_a_source_with_an_error_raises_what_compile_raises(self):
+        for name, source in ERRORS.items():
+            for variant in (source, source.encode("utf-8"), "ok = 0\n" * 12 + source, source + "ok = 0\n" * 12):
+                expected = error_facts(whole, variant, "some/file.py")
+                if variant is source:
+                    self.assertIsNotNone(expected, f"compile accepts {name!r}")
+                if expected is None:
+                    continue                # the lines added after it completed the statement
+                with self.subTest(name, variant=variant):
+                    for size in SIZES + (pp.PIECE_LINES,):
+                        self.assertIsNone(pp.parse_pieces(variant, "some/file.py", size), f"pieces of {size} lines")
+                        self.assertEqual(error_facts(pp.parse, variant, "some/file.py", size), expected)
+
+    def test_what_the_compiler_rejects_is_rejected_in_the_same_words(self):
+        for name, source in COMPILE_ERRORS.items():
+            with self.subTest(name):
+                expected = error_facts(compile, source, "f.py", "exec")
+                self.assertIsNotNone(expected, "compile accepts this source")
+                for size in (1, 2):
+                    got = error_facts(lambda: compile(pp.parse(source, "f.py", size), "f.py", "exec"))
+                    self.assertEqual(got, expected, f"pieces of {size} lines")
+                if error_facts(whole, source) is None:      # the parser takes it: the pieces give its tree
+                    self.assertEqual(dump(pp.parse(source, "f.py", 1)), dump(whole(source)))
+
+    def test_barry_as_flufl_is_parsed_whole(self):
+        # the one __future__ import that changes the grammar for the rest of the file
+        accepted = "from __future__ import barry_as_FLUFL\na = 1\nb = a <> 2\n"
+        refused = "from __future__ import barry_as_FLUFL\na = 1\nb = a != 2\n"
+        self.assertIsNone(pp.parse_pieces(accepted, "<test>", 1))
+        self.assertEqual(dump(pp.parse(accepted, "<test>", 1)), dump(whole(accepted)))

[P2] Compare this fallback with the SyntaxError produced by the stock compiler.

On CPython 3.12.1, plain compile(source, ..., flags=ast.PyCF_ONLY_AST, dont_inherit=True) rejects <> even when the same source string starts with from __future__ import barry_as_FLUFL. The fallback in pp.parse correctly takes that path, so this test errors before evaluating its reference. Adding __future__.barry_as_FLUFL.compiler_flag explicitly made stock compile accept it, but pp.parse does not receive that flag. Use the same stock compiler outcome for both calls, while retaining the assertion that the piecewise parser gives up.

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4707524593 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/2237#discussion_r4707524593). Originally posted by [lixonik](https://github.com/lixonik) on 2026-11-26T11:11:20Z. **Code review location:** `tests/test_piecewise_parse.py`; line 700 ~~~~diff @@ -0,0 +1,936 @@ +"""tests/semantic/piecewise_parse.py builds the tree a whole-file parse builds, and support.py's loader the same code. + + python -I tests/test_piecewise_parse.py + +The translator tests load tools/rdna2spirv.py through that loader, so "the same" is the whole point: a test that ran a +slightly different translator would prove nothing. Checked here, with nothing but the standard library: + +* hand-written sources for each boundary rule (decorators, the clauses of `if`/`try`/`for`/`while` at top level and + in a class, a class header over several lines, nested classes, a docstring and `from __future__`, strings and + brackets whose inner lines start at column 0, non-ASCII text, CRLF), cut into pieces of 1, 2, 3, 5 and 8 lines: + `ast.dump(tree, include_attributes=True)` equals the whole-file parse's; +* sources with an error: the pieces are given up and `parse` raises what `compile` raises (type, message, line, + column, text); +* every Python file under tools/, scripts/ and tests/ and make_game.py in pieces of one statement, and the long + files of tools/ also in pieces of the size the loader uses: the two trees agree in every field and position + (`same_tree`, which is held against the dumps on the hand-written sources); +* the code object compiled from the pieces against the one `compile` makes from the file's bytes, for some files; +* tools/rdna2spirv.py, tree (by its dump) and code object, in one test of its own: on the interpreters the pieces + are for (CPython 3.12 to 3.14.7) each of its two whole-file parses takes 7 s, which is why it is `_slow`; +* support.py's finder and loader on throwaway folders, and that support.py installs them only where needed. + +About 45 s in all on those interpreters, most of it the repository scan and the translator. +""" +import ast +import importlib.machinery +import importlib.util +import os +import py_compile +import sys +import tempfile +import types +import unittest +import warnings +from unittest import mock + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SEMANTIC = os.path.join(ROOT, "tests", "semantic") +TOOLS = os.path.join(ROOT, "tools") +TRANSLATOR = os.path.join(TOOLS, "rdna2spirv.py") +sys.path.insert(0, SEMANTIC) + +import piecewise_parse as pp # noqa: E402 +import support # noqa: E402 (imports the translator the way the translator tests do) + +SPLITS = sys.version_info >= (3, 12) # older interpreters are always parsed whole (piecewise_parse.parse_pieces) +SIZES = (1, 2, 3, 5, 8) +DUMP = dict(include_attributes=True, **({"show_empty": True} if sys.version_info >= (3, 13) else {})) + + +def whole(source, filename="<test>"): + return compile(source, filename, "exec", ast.PyCF_ONLY_AST, dont_inherit=True) + + +def dump(tree): + return ast.dump(tree, **DUMP) + + +def difference(got, expected): + """Where two dumps part, with a little of each: the dumps themselves run to megabytes.""" + at = len(os.path.commonprefix([got, expected])) + near = slice(max(0, at - 90), at + 90) + return f"dumps differ at character {at}: ...{got[near]!r} against ...{expected[near]!r}" + + +def same_tree(a, b): + """Whether two trees agree in every field and every position: what equal dumps say, without building them. + The dumps of the repository's 24 MB of Python take 12 s, this takes 3; PiecesTest holds it against `dump`.""" + todo = [(a, b)] + while todo: + x, y = todo.pop() + if type(x) is not type(y): + return False + if isinstance(x, ast.AST): + todo.extend((getattr(x, name, None), getattr(y, name, None)) for name in x._fields + x._attributes) + elif type(x) is list: + if len(x) != len(y): + return False + todo.extend(zip(x, y)) + elif (repr(x) != repr(y)) if isinstance(x, (float, complex)) else (x != y): + return False + return True + + +def error_facts(call, *args): + """What the SyntaxError `call` raises says (a ValueError before 3.12 for a NUL), or None when it raises none.""" + try: + call(*args) + except SyntaxError as e: + return type(e).__name__, e.msg, e.filename, e.lineno, e.offset, e.end_lineno, e.end_offset, e.text + except ValueError as e: + return type(e).__name__, str(e) + return None + + +def code_facts(code): + """Everything a code object holds as plain values, the code objects among its constants included.""" + return (code.co_name, code.co_qualname, code.co_filename, code.co_firstlineno, code.co_flags, code.co_argcount, + code.co_posonlyargcount, code.co_kwonlyargcount, code.co_nlocals, code.co_stacksize, code.co_code, + code.co_names, code.co_varnames, code.co_freevars, code.co_cellvars, code.co_linetable, + code.co_exceptiontable, list(code.co_positions()), + [code_facts(c) if isinstance(c, types.CodeType) else (type(c).__name__, repr(c)) for c in code.co_consts]) + + +def python_files(): + """Every .py file under tools/, scripts/ and tests/, and make_game.py.""" + yield os.path.join(ROOT, "make_game.py") + for top in ("tools", "scripts", "tests"): + for base, dirs, names in os.walk(os.path.join(ROOT, top)): + dirs[:] = sorted(d for d in dirs if d != "__pycache__" and not d.startswith(".")) + for name in sorted(names): + if name.endswith(".py"): + yield os.path.join(base, name) + + +def read(path): + with open(path, "rb") as f: + return f.read() + + +# --- hand-written sources, one per boundary rule --------------------------------------------------------------- + +DECORATORS = r''' +import functools + + +def deco(f): + return f + + +@deco +def a(): + return 1 + + +@deco +@functools.wraps(a) +def b(): + return 2 + + +@deco +class C: + @staticmethod + def m(): + return 3 + + @property + @deco + def p(self): + return 4 + + @functools.lru_cache( + maxsize=None, + ) + def q(self): + return 5 + + @deco + class Inner: + pass + + tail = 6 +x = 1 +''' + +CLAUSES_AT_TOP_LEVEL = r''' +import os +if os.sep == "/": + a = 1 +elif os.sep == ":": + a = 2 +else: + a = 3 +try: + b = int("x") +except ValueError: + b = 0 +except (TypeError, KeyError) as e: + b = 1 +else: + b = 2 +finally: + c = 3 +try: + d = 4 +finally: + d = 5 +for i in range(3): + pass +else: + e = 6 +while False: + pass +else: + f = 7 +with open(os.devnull) as g: + pass +if a: b = 1 +elif b: b = 2 +else: b = 3 +try: h = 8 +except Exception: h = 9 +i = 0; j = 1; k = 2 +''' + +CLAUSES_IN_A_CLASS = r''' +class K: + if True: + a = 1 + elif False: + a = 2 + else: + a = 3 + try: + b = 1 + except Exception: + b = 2 + else: + b = 3 + finally: + c = 4 + for i in (): + pass + else: + d = 5 + while False: + pass + else: + e = 6 + + def m(self): + if self: + return 1 + else: + return 2 + try: + pass + finally: + pass + + async def n(self): + async with self as s: + async for t in s: + await t + f = 7; g = 8 + h = 9; +last = K +''' + +MATCH_AND_EXCEPT_STAR = r''' +def f(x): + match x: + case 1: + return "one" + case [a, b]: + return a + case _: + return None + + +match = 1 +case = match +match case: + case 1: + pass + + +class M: + match case: + case 1: + y = 1 + case _: + y = 2 + case = 3 + try: + z = 1 + except* ValueError: + z = 2 + except* TypeError: + z = 3 +after = M +''' + +CLASS_HEADER_OVER_SEVERAL_LINES = r''' +class Base: + pass + + +class A( + Base, + metaclass=type, +): + """Doc.""" + x = 1 + + def m(self): + return self.x + + y = 2 + + +class B(Base, + object): z = 3 + + +class C( + Base): + def n(self): return 4 + w = 5 +''' + +NESTED_CLASSES = r''' +class Outer: + a = 1 + + class Middle: + b = 2 + + class Inner: + c = 3 + + def m(self): + class Local: + d = 4 + return Local + + e = 5 + + f = 6 + + class Second: pass + + g = 7 + + +class After(Outer.Middle): + pass +''' + +DOCSTRING_AND_FUTURE = r'''"""Module docstring. + +class NotCode: + else: +""" +from __future__ import annotations +from __future__ import division, generators + +import sys + + +def f(a: Undefined) -> AlsoUndefined: + """Function docstring.""" + return a + + +class D: + """Class docstring.""" + + x: NotDefinedEither = 1 +''' + +COLUMN_ZERO = r''' +text = """ +class NotAClass: + def not_a_method(self): +else: +@not_a_decorator +""" +value = ( +1, +2, +[ +3, +], +) +call = dict( +a=1, +) +other = text + \ +"tail" +if value: first = { +"k": 1, +} +else: first = None + + +class Holder: + doc = """ +class StillNotAClass: + pass +finally: +""" + tup = ( +1, +2, +) + + def method(self): + return f""" +{self.doc} +{ +self.tup +!r:>{ +10 +}} +""" + \ +"x" +# a comment at column 0 inside the class body + # and one that fits no indentation level + + after = 3 + lst = [ +# a comment inside brackets +4, +] + + +last = Holder +''' + +F_STRINGS = r''' +name = "x" +plain = f"{name}" +spec = f"{name!r:>{10}} {name=} {{literal}} {3.14:.{2}f}" +joined = (f"{name}" + f"{name:{name}}" + "tail") + + +class F: + def m(self, a, b): + self.emit(f"{a} = OpIAdd %uint {b} {self.cu(1)}") + return f"""{a} + {b}""", rf"\d{a}", f'{a["k"]}' + + table = {f"k{i}": f"{i:02x}" for i in range(4)} +''' + +LEFTOVERS = r'''#!/usr/bin/env python3 +# a comment before anything + +x = 1 # trailing comment +lam = lambda: (yield) +star, *rest = 1, 2, 3 +print(x); print(x) +global_name: int +assert x, "message" +del star +if x: + pass +# comment after the last statement +''' + +NO_FINAL_NEWLINE = "x = 1\nclass A:\n y = 2\n z = 3" +ONLY_COMMENTS = "# nothing\n\n# here\n" +BACKSLASH_LINES = "a = 1\n\\\nb = 2\nclass A:\n c = 3\n\\\n d = 4\n e = 5\nf = 6\n" +FORM_FEED = "a = 1\n\x0c\nb = 2\nclass A:\n c = 3\n\x0c d = 4\ne = 5\n" +NON_ASCII = ('caf\xe9 = "\u017c\xf3\u0142w"; after = caf\xe9\n' + 'class \xdc:\n' + ' \u03c0 = 3; q = "\U0001f600" + f"{\u03c0}\u2713"; r = q\n' + ' def m(self): return self.\u03c0, "\xe9"\n' + ' s = "\xe9" + \\\n' + ' "\u03c0"; t = s\n' + 'last = "\xe9"; end = last\n') +LATIN_1 = ('# -*- coding: latin-1 -*-\n' + 'a = "\xe9\xe8"; b = a\n' + 'class L:\n' + ' c = "\xfc"; d = c\n' + ' def m(self): return "\xdf", self.c\n') + +SOURCES = { + "decorators": DECORATORS, + "clauses at top level": CLAUSES_AT_TOP_LEVEL, + "clauses in a class": CLAUSES_IN_A_CLASS, + "tabs": CLAUSES_IN_A_CLASS.replace(" ", "\t"), + "match and except*": MATCH_AND_EXCEPT_STAR, + "class header over several lines": CLASS_HEADER_OVER_SEVERAL_LINES, + "nested classes": NESTED_CLASSES, + "docstring and __future__": DOCSTRING_AND_FUTURE, + "strings and brackets at column 0": COLUMN_ZERO, + "f-strings": F_STRINGS, + "leftovers": LEFTOVERS, + "no final newline": NO_FINAL_NEWLINE, + "form feed": FORM_FEED, + "non-ASCII": NON_ASCII, +} +if sys.version_info >= (3, 12): + SOURCES["type parameters"] = r''' +type Pair[T] = tuple[T, T] + + +def first[T](pair: Pair[T]) -> T: + return pair[0] + + +class Box[T]: + type Inner = list[T] + + def get[U](self, other: U) -> T | U: + return other + + nested = f"{'a' + f'{1}'}" +last = Box +''' + +# A source with an error, and why it is one. None of them may come back as a tree. +ERRORS = { + "bracket never closed": "a = 1\nb = (\nc = 3\nd = 4\n", + "else without if": "a = 1\nelse:\n b = 2\n", + "else first": "else:\n pass\n", + "elif after a class": "class A:\n a = 1\n b = 2\nelif a:\n pass\n", + "indented first line": " a = 1\nb = 2\n", + "unexpected indent": "a = 1\n b = 2\nc = 3\n", + "unindent matches no level": "if a:\n b = 1\n c = 2\nd = 3\n", + "unindent matches no level in a class": "class A:\n a = 1\n b = 2\n", + "tabs against spaces": "if a:\n b = 1\n\tc = 2\n", + "tabs against spaces between class statements": "class A:\n a = 1\n\tb = 2\n", + "string never closed": 'a = 1\nb = """open\nc = 3\n', + "error in a class body": "class A:\n a = 1\n b = = 2\n c = 3\nd = 4\n", + "error in the last statement of a class": "class A:\n a = 1\n b = 2\n def m(self) return 3\n", + "except without try in a class": "class A:\n a = 1\n except E:\n pass\n", + "decorator with nothing after it": "a = 1\n@dec\n", + "decorator before an assignment": "@dec\na = 1\nb = 2\n", + "decorator before an assignment in a class": "class A:\n a = 1\n @dec\n b = 2\n c = 3\n", + "character that is no token": "a = 1\nb = $\nc = 3\n", + "backslash at the end": "a = 1\nb = 2 \\", + "backslash line at the end": "a = 1\n\\\n", + "NUL": "a = 1\0\nb = 2\n", + "try without except": "try:\n a = 1\nb = 2\n", + "class without a name": "a = 1\nclass:\n pass\n", + "missing colon": "a = 1\ndef f()\n return 1\n", + "f-string conversion": 'a = 1\nb = f"{a!z}"\nc = 3\n', + "f-string never closed": 'a = 1\nb = f"{a\nc = 3\n', + "assignment to a literal": "a = 1\n1 = a\nb = 2\n", + "statement after a one-line class": "class A: a = 1\n b = 2\n", +} + +# What compile refuses after parsing (an unknown feature already while parsing, from 3.14). Parsing in pieces and +# compiling the tree says the same. +COMPILE_ERRORS = { + "return outside a function": "def f():\n pass\nreturn 1\n", + "return in a class": "class A:\n a = 1\n return 2\n b = 3\n", + "__future__ after code": "a = 1\nfrom __future__ import annotations\nb = 2\n", + "break outside a loop": "a = 1\nbreak\n", + "nonlocal at module level": "a = 1\nnonlocal a\n", + "unknown __future__ feature": "from __future__ import no_such_feature\na = 1\n", + "from __future__ import braces": "a = 1\nb = 2\nfrom __future__ import braces\n", + "the same argument twice": "a = 1\ndef f(x, x):\n pass\n", + "await outside a function": "class A:\n a = 1\n b = [await c for c in a]\n d = 2\n", +} + + +class PiecesTest(unittest.TestCase): + def assert_same_tree(self, source, sizes=SIZES, must_split=SPLITS): + expected = dump(whole(source)) + for size in sizes: + tree = pp.parse_pieces(source, "<test>", size) + if must_split: + self.assertIsNotNone(tree, f"pieces of {size} lines were given up") + if tree is not None: + got = dump(tree) + self.assertTrue(got == expected, f"pieces of {size} lines: " + difference(got, expected)) + self.assertTrue(same_tree(tree, whole(source)), f"same_tree, pieces of {size} lines") + got = dump(pp.parse(source, "<test>", size)) + self.assertTrue(got == expected, f"parse, pieces of {size} lines: " + difference(got, expected)) + + def test_each_boundary_rule_gives_the_whole_file_tree(self): + for name, source in SOURCES.items(): + with self.subTest(name): + self.assert_same_tree(source) + + def test_same_tree_sees_what_the_dumps_see(self): + source = "class A:\n x = 1.0\n def m(self):\n return [self.x, 'a']\ny = A\n" + changes = { + "a column": lambda t: setattr(t.body[0].body[1].body[0].value.elts[0], "col_offset", 99), + "an end line": lambda t: setattr(t.body[0], "end_lineno", 99), + "a name": lambda t: setattr(t.body[1].value, "id", "B"), + "a constant": lambda t: setattr(t.body[0].body[0].value, "value", 2.0), + "the sign of a zero": lambda t: setattr(t.body[0].body[0].value, "value", -0.0), + "the type of a constant": lambda t: setattr(t.body[0].body[0].value, "value", 1), + "a statement fewer": lambda t: t.body[0].body.pop(), + "a statement more": lambda t: t.body.append(t.body[1]), + "another kind of node": lambda t: t.body.__setitem__(1, ast.Pass(lineno=5, col_offset=0, end_lineno=5, + end_col_offset=5)), + } + self.assertTrue(same_tree(whole(source), whole(source))) + for name, change in changes.items(): + with self.subTest(name): + tree = whole(source.replace("1.0", "0.0") if "zero" in name else source) + reference = whole(source.replace("1.0", "0.0") if "zero" in name else source) + change(tree) + self.assertNotEqual(dump(tree), dump(reference)) + self.assertFalse(same_tree(tree, reference)) + self.assertFalse(same_tree(reference, tree)) + + def test_the_same_from_bytes_with_lf_crlf_and_cr_line_ends(self): + for name, source in SOURCES.items(): + for ending in ("\n", "\r\n", "\r"): + with self.subTest(name, ending=ending): + text = source.replace("\n", ending) + self.assert_same_tree(text, sizes=(1, 3)) + self.assert_same_tree(text.encode("utf-8"), sizes=(1, 3)) + + def test_a_bom_and_a_coding_line_are_read_as_compile_reads_them(self): + self.assert_same_tree(b"\xef\xbb\xbf" + NON_ASCII.encode("utf-8")) + self.assert_same_tree(LATIN_1.encode("latin-1")) + self.assertEqual(whole(LATIN_1.encode("latin-1")).body[0].value.value,"\xe9\xe8") + # undecodable bytes and an unknown coding are compile's to report + for data in (b"a = 1\nb = '\xff'\n", b"# coding: no-such-codec\na = 1\n"): + with self.subTest(data): + self.assertIsNone(pp.parse_pieces(data, "<test>", 1)) + self.assertIsNotNone(error_facts(whole, data)) + self.assertEqual(error_facts(pp.parse, data, "<test>", 1), error_facts(whole, data)) + + def test_sources_with_nothing_to_cut(self): + for source in ("", "\n", ONLY_COMMENTS, "x = 1", "x = 1\n", "class A: pass\n", '"""Only a docstring."""\n'): + with self.subTest(source): + self.assert_same_tree(source) + + def test_a_backslash_line_before_a_statement_is_given_up_not_guessed(self): + # "\\\n" on a line of its own joins the next line, so the statement after it starts a row early: valid + # Python that no cut may separate. The piece before it ends in the backslash and does not parse. + whole(BACKSLASH_LINES) + self.assert_same_tree(BACKSLASH_LINES, must_split=False) + if SPLITS: + self.assertIsNone(pp.parse_pieces(BACKSLASH_LINES, "<test>", 1)) + + def test_the_class_ends_where_its_last_token_ends(self): + # `x = 1;` ends at the 1 and its class at the semicolon: the end comes from the parser, not from the body + source = "class A:\n a = 1\n b = 2\n x = 1;\ny = A\n" + self.assertNotEqual(whole(source).body[0].end_col_offset, whole(source).body[0].body[-1].end_col_offset) + self.assert_same_tree(source) + + @unittest.skipUnless(SPLITS, "sources are parsed whole before Python 3.12") + def test_a_long_class_is_cut_inside_and_other_long_statements_are_not(self): + method = " def m{0}(self):\n return f'{{self}} {0}'\n\n" + source = "class Big:\n" + "".join(method.format(i) for i in range(40)) + "x = 1\n" + parsed = [] + real_compile = compile + with mock.patch.object(pp, "compile", lambda text, *a, **k: parsed.append(text) or real_compile(text, *a, **k), + create=True): + tree = pp.parse_pieces(source, "<test>", 30) + self.assertEqual(dump(tree), dump(whole(source))) + self.assertEqual(len(parsed), 5, [p.lstrip("\n")[:40] for p in parsed]) + self.assertEqual([p.lstrip("\n").startswith(pp.DUMMY) for p in parsed], [False, True, True, True, False]) + # a function of the same length is one statement and stays one piece + function = "def big():\n" + "".join(f" a{i} = f'{{{i}}}'\n" for i in range(120)) + "x = 1\n" + del parsed[:] + with mock.patch.object(pp, "compile", lambda text, *a, **k: parsed.append(text) or real_compile(text, *a, **k), + create=True): + tree = pp.parse_pieces(function, "<test>", 30) + self.assertEqual(dump(tree), dump(whole(function))) + self.assertEqual(len(parsed), 2) + # Each piece of a class starts a new indentation stack, so the tokenizer's tab rule between two statements + # of the body would go unchecked: a body not indented by the same characters throughout is never cut. + # (A form feed is the one valid way to get there; tabs against spaces are an error, see ErrorsTest.) + mixed = "class A:\n a = 1\n\x0c b = 2\n c = 3\nd = 4\n" + del parsed[:] + with mock.patch.object(pp, "compile", lambda text, *a, **k: parsed.append(text) or real_compile(text, *a, **k), + create=True): + tree = pp.parse_pieces(mixed, "<test>", 1) + self.assertEqual(dump(tree), dump(whole(mixed))) + self.assertEqual([p.lstrip("\n").startswith(pp.DUMMY) for p in parsed], [False, False]) + + def test_a_short_source_is_one_piece(self): + with mock.patch.object(pp, "_statements", side_effect=AssertionError("tokenized a source of one piece")): + self.assert_same_tree(DECORATORS, sizes=(pp.PIECE_LINES,)) + + +class ErrorsTest(unittest.TestCase): + def test_a_source_with_an_error_raises_what_compile_raises(self): + for name, source in ERRORS.items(): + for variant in (source, source.encode("utf-8"), "ok = 0\n" * 12 + source, source + "ok = 0\n" * 12): + expected = error_facts(whole, variant, "some/file.py") + if variant is source: + self.assertIsNotNone(expected, f"compile accepts {name!r}") + if expected is None: + continue # the lines added after it completed the statement + with self.subTest(name, variant=variant): + for size in SIZES + (pp.PIECE_LINES,): + self.assertIsNone(pp.parse_pieces(variant, "some/file.py", size), f"pieces of {size} lines") + self.assertEqual(error_facts(pp.parse, variant, "some/file.py", size), expected) + + def test_what_the_compiler_rejects_is_rejected_in_the_same_words(self): + for name, source in COMPILE_ERRORS.items(): + with self.subTest(name): + expected = error_facts(compile, source, "f.py", "exec") + self.assertIsNotNone(expected, "compile accepts this source") + for size in (1, 2): + got = error_facts(lambda: compile(pp.parse(source, "f.py", size), "f.py", "exec")) + self.assertEqual(got, expected, f"pieces of {size} lines") + if error_facts(whole, source) is None: # the parser takes it: the pieces give its tree + self.assertEqual(dump(pp.parse(source, "f.py", 1)), dump(whole(source))) + + def test_barry_as_flufl_is_parsed_whole(self): + # the one __future__ import that changes the grammar for the rest of the file + accepted = "from __future__ import barry_as_FLUFL\na = 1\nb = a <> 2\n" + refused = "from __future__ import barry_as_FLUFL\na = 1\nb = a != 2\n" + self.assertIsNone(pp.parse_pieces(accepted, "<test>", 1)) + self.assertEqual(dump(pp.parse(accepted, "<test>", 1)), dump(whole(accepted))) ~~~~ --- [P2] Compare this fallback with the SyntaxError produced by the stock compiler. On CPython 3.12.1, plain `compile(source, ..., flags=ast.PyCF_ONLY_AST, dont_inherit=True)` rejects `<>` even when the same source string starts with `from __future__ import barry_as_FLUFL`. The fallback in `pp.parse` correctly takes that path, so this test errors before evaluating its reference. Adding `__future__.barry_as_FLUFL.compiler_flag` explicitly made stock `compile` accept it, but `pp.parse` does not receive that flag. Use the same stock compiler outcome for both calls, while retaining the assertion that the piecewise parser gives up.
GrahamboJangles commented 2026-11-26 11:25:57 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by GrahamboJangles on 2026-11-26T11:25:57Z.


Reviewed on Windows 11, head e654d10fdf vs base a73a57e133 — and this time I re-measured the headline claim on two interpreters at once: this machine has 3.13.14 (python3, inside the affected 3.13.0–3.13.15 window) and 3.14.9 (python, past the 3.14.8 fix).

The 7 s → 1 s claim reproduces. Timing tools/rdna2spirv.py (1,190,681 bytes) directly:

  • 3.13.14: needed() → True; whole-file parse 9.28 s, parse_pieces 1.55 s, and the piece tree's ast.dump (positions included) equals the whole-file parse's dump exactly. My machine is slower than the author's — same ratio, 6× — so "7 s → 1 s" is right in shape.
  • 3.14.9: needed() → False; whole-file parse 0.21 s, pieces 0.54 s — pieces are slower there, which is exactly why the finder must not (and does not) install on fixed interpreters.

End-to-end proof the loader is actually in the import path: I put a counting spy on piecewise_parse.parse_pieces (module attribute, so support.py picks it up) and timed import support on 3.13.14 with no valid .pyc present: 1.64 s total, and the spy logged 12 tools/ modules compiled from pieces, every one returning a tree (no fallback) — rdna2spirv.py first — with ToolsFinder sitting immediately before PathFinder in sys.meta_path. Same probe on 3.14.9: 0.07 s, zero parse_pieces calls, finder absent (valid 314 pyc used first — the test_a_valid_pyc_is_used_without_parsing rule live at real import).

Tests run at head (real runs, not just read):

  • python3 -I tests/test_piecewise_parse.py -v (3.13.14): 25/25 OK, 60.6 s — matches the docstring's ~45 s, slow machine. python -I tests/test_piecewise_parse.py (3.14.9): 25/25 OK, 38.2 s.
  • Consumer suites at head on 3.13.14: tests/semantic/test_active_cache.py 9 OK, tests/semantic/test_semantic_translator_use.py 3 OK — the translator tests load through the new loader and still pass. tests/semantic/test_alu_add_u16.py 5 OK but ~10.6 s wall: it imports rdna2spirv directly, no support — a live instance of the acknowledged "247 of the 491 files that import the translator without support still pay the 7 s" caveat, consistent with the PR text, not a regression.
  • Repo gates at head: scripts/check_no_game_data.py exit 0; compileall -q clean on all three touched/new files; tests/test_ci_registration.py 16 OK, same count as before — the new test file doesn't desync CI registration.

Code read. The 198-line helper end to end; the give-up discipline is the heart and checks out: _GIVE_UP catching MemoryError/RecursionError is broad but conservative (anything caught falls back to the usual compile, which then reports the real error in its own words), the tab-rule guard (indent not in (None, line[:column]) → body not cut) is deliberately conservative for mixed-indent class bodies, and the class _: dummy-header cut keeps each later piece's statements appended to the real ClassDef body with the end position pinned to the last piece — the test_the_class_ends_where_its_last_token_ends and RepositoryTest full-repo dump comparison pin that from both sides. _rows/_statements start-line bookkeeping (decorators and after-; statements can add rows) matches the _CONTINUES/decorator rules. Hand-written fixtures cover decorated nested classes, one-line if a: b = 1 clause chains, match/case soft keywords, except*, multi-line class headers, and CRLF/BOM/coding lines — every suite passes on both interpreters.

What I did not verify line by line: the two whole-file-parse fallbacks inside parse_pieces (len(rows) <= piece_lines and the short-source early return) were read, not exercised separately — the 25 tests pin their behavior through the boundary cases. Also the gh-155525/CPython-tag history in the docstring is the author's citation; I confirmed the behavior on 3.13.14 vs 3.14.9 matches it, not the tag names.

Coordination: cross-checked open PRs (is:pr TRANSLATOR-PIECEWISE-PARSE → only this one) and the #1608 claim list is fresh; no other PR carries the item. Merge state: mergeable=true, unstable, no failing checks.

Verdict: this is exactly what it claims. Same trees, same code objects, graceful fallback on everything it can't cut, finder active only on the interpreters that pay the quadratic tokenizer cost — reproduced at both ends of the affected window on one machine. The visible traceback difference on syntax errors (five importlib frames above support.py's source_to_code) is documented in the PR body, and test_an_error_in_a_module_is_the_one_the_usual_loader_raises pins the error itself is identical.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7190718872 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/2237#issuecomment-7190718872). Originally posted by [GrahamboJangles](https://github.com/GrahamboJangles) on 2026-11-26T11:25:57Z. --- Reviewed on Windows 11, head `e654d10fdf` vs base `a73a57e133` — and this time I re-measured the headline claim on **two interpreters** at once: this machine has 3.13.14 (`python3`, inside the affected 3.13.0–3.13.15 window) and 3.14.9 (`python`, past the 3.14.8 fix). **The 7 s → 1 s claim reproduces.** Timing `tools/rdna2spirv.py` (1,190,681 bytes) directly: - 3.13.14: `needed()` → True; whole-file parse **9.28 s**, `parse_pieces` **1.55 s**, and the piece tree's `ast.dump` (positions included) equals the whole-file parse's dump exactly. My machine is slower than the author's — same ratio, 6× — so "7 s → 1 s" is right in shape. - 3.14.9: `needed()` → False; whole-file parse **0.21 s**, pieces **0.54 s** — pieces are *slower* there, which is exactly why the finder must not (and does not) install on fixed interpreters. **End-to-end proof the loader is actually in the import path:** I put a counting spy on `piecewise_parse.parse_pieces` (module attribute, so support.py picks it up) and timed `import support` on 3.13.14 with no valid `.pyc` present: **1.64 s** total, and the spy logged **12 tools/ modules compiled from pieces, every one returning a tree (no fallback)** — `rdna2spirv.py` first — with `ToolsFinder` sitting immediately before `PathFinder` in `sys.meta_path`. Same probe on 3.14.9: **0.07 s, zero parse_pieces calls, finder absent** (valid 314 pyc used first — the `test_a_valid_pyc_is_used_without_parsing` rule live at real import). **Tests run at head (real runs, not just read):** - `python3 -I tests/test_piecewise_parse.py -v` (3.13.14): **25/25 OK, 60.6 s** — matches the docstring's ~45 s, slow machine. `python -I tests/test_piecewise_parse.py` (3.14.9): **25/25 OK, 38.2 s**. - Consumer suites at head on 3.13.14: `tests/semantic/test_active_cache.py` 9 OK, `tests/semantic/test_semantic_translator_use.py` 3 OK — the translator tests load through the new loader and still pass. `tests/semantic/test_alu_add_u16.py` 5 OK but ~10.6 s wall: it imports `rdna2spirv` directly, no `support` — a live instance of the acknowledged "247 of the 491 files that import the translator without support still pay the 7 s" caveat, consistent with the PR text, not a regression. - Repo gates at head: `scripts/check_no_game_data.py` exit 0; `compileall -q` clean on all three touched/new files; `tests/test_ci_registration.py` 16 OK, same count as before — the new test file doesn't desync CI registration. **Code read.** The 198-line helper end to end; the give-up discipline is the heart and checks out: `_GIVE_UP` catching `MemoryError`/`RecursionError` is broad but conservative (anything caught falls back to the usual compile, which then reports the real error in its own words), the tab-rule guard (`indent not in (None, line[:column])` → body not cut) is deliberately conservative for mixed-indent class bodies, and the `class _:` dummy-header cut keeps each later piece's statements appended to the real `ClassDef` body with the end position pinned to the last piece — the `test_the_class_ends_where_its_last_token_ends` and `RepositoryTest` full-repo dump comparison pin that from both sides. `_rows`/`_statements` start-line bookkeeping (decorators and after-`;` statements can add rows) matches the `_CONTINUES`/decorator rules. Hand-written fixtures cover decorated nested classes, one-line `if a: b = 1` clause chains, `match`/`case` soft keywords, `except*`, multi-line class headers, and CRLF/BOM/coding lines — every suite passes on both interpreters. **What I did not verify line by line:** the two whole-file-parse fallbacks inside `parse_pieces` (`len(rows) <= piece_lines` and the short-source early return) were read, not exercised separately — the 25 tests pin their behavior through the boundary cases. Also the gh-155525/CPython-tag history in the docstring is the author's citation; I confirmed the *behavior* on 3.13.14 vs 3.14.9 matches it, not the tag names. **Coordination:** cross-checked open PRs (`is:pr TRANSLATOR-PIECEWISE-PARSE` → only this one) and the #1608 claim list is fresh; no other PR carries the item. Merge state: mergeable=true, `unstable`, no failing checks. **Verdict: this is exactly what it claims.** Same trees, same code objects, graceful fallback on everything it can't cut, finder active only on the interpreters that pay the quadratic tokenizer cost — reproduced at both ends of the affected window on one machine. The visible traceback difference on syntax errors (five importlib frames above `support.py`'s `source_to_code`) is documented in the PR body, and `test_an_error_in_a_module_is_the_one_the_usual_loader_raises` pins the error itself is identical.
Tauwni commented 2026-11-26 13:01:18 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Tauwni on 2026-11-26T13:01:18Z.


Tested 1f92ae6a5 on an Apple M3 (macOS 26.5.1) with Homebrew's Python 3.12.16 and 3.15.2, against main a73a57e13.

  • tests/test_piecewise_parse.py: 26/26 pass on both.
  • scripts/run_semantic_tests.py tests/semantic: 498 files, 6351 tests, 0 failed on both versions.

The quadratic tokenizer cost is much smaller on this CPU than the 7 s in the description, but the gain on 3.12 is there:

main this PR
whole-file compile() of tools/rdna2spirv.py, 3.12 1.13 s —
import support with no .pyc (PYTHONDONTWRITEBYTECODE=1), 3.12 1.35 s 0.59 s
same, 3.15 (tokenizer already fixed) 0.24 s 0.24 s
full semantic suite, 3.12, 8 jobs 235 s 203 s

On 3.15 the import time is unchanged, as expected, since piecewise_parse.needed() leaves the usual loader in place there.

AI-assisted (Claude Code). No game data.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7192767133 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/2237#issuecomment-7192767133). Originally posted by [Tauwni](https://github.com/Tauwni) on 2026-11-26T13:01:18Z. --- Tested `1f92ae6a5` on an Apple M3 (macOS 26.5.1) with Homebrew's Python 3.12.16 and 3.15.2, against `main` `a73a57e13`. - `tests/test_piecewise_parse.py`: 26/26 pass on both. - `scripts/run_semantic_tests.py tests/semantic`: 498 files, 6351 tests, 0 failed on both versions. The quadratic tokenizer cost is much smaller on this CPU than the 7 s in the description, but the gain on 3.12 is there: | | `main` | this PR | |---|---|---| | whole-file `compile()` of `tools/rdna2spirv.py`, 3.12 | 1.13 s | — | | `import support` with no `.pyc` (`PYTHONDONTWRITEBYTECODE=1`), 3.12 | 1.35 s | 0.59 s | | same, 3.15 (tokenizer already fixed) | 0.24 s | 0.24 s | | full semantic suite, 3.12, 8 jobs | 235 s | 203 s | On 3.15 the import time is unchanged, as expected, since `piecewise_parse.needed()` leaves the usual loader in place there. AI-assisted (Claude Code). No game data.
syfyra commented 2026-11-26 13:44:01 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by syfyra on 2026-11-26T13:44:01Z.


1f92ae6a5 addresses both reviews.

lixonik: test_barry_as_flufl_is_parsed_whole now takes the running interpreter's compile outcome, tree or error, for both <> and !=, and still asserts that the pieces give up. On 3.12.1 the parser does not read the import from the source: _PyPegen_checked_future_import is missing in v3.12.0, v3.12.1 and v3.13.0 and present in v3.12.16, v3.13.13 and v3.14.7. I have no 3.12.1, so this was checked with that behaviour simulated; a re-run there would confirm it.

GrahamboJangles: with your 3.14.9 figures (0.21 s whole, 0.54 s in pieces) parse() now takes pieces only where needed() says so, which matters since 53604abbf makes five standalone tests call it.

AI-assisted (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7193760278 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/2237#issuecomment-7193760278). Originally posted by [syfyra](https://github.com/syfyra) on 2026-11-26T13:44:01Z. --- 1f92ae6a5 addresses both reviews. lixonik: `test_barry_as_flufl_is_parsed_whole` now takes the running interpreter's `compile` outcome, tree or error, for both `<>` and `!=`, and still asserts that the pieces give up. On 3.12.1 the parser does not read the import from the source: `_PyPegen_checked_future_import` is missing in v3.12.0, v3.12.1 and v3.13.0 and present in v3.12.16, v3.13.13 and v3.14.7. I have no 3.12.1, so this was checked with that behaviour simulated; a re-run there would confirm it. GrahamboJangles: with your 3.14.9 figures (0.21 s whole, 0.54 s in pieces) `parse()` now takes pieces only where `needed()` says so, which matters since 53604abbf makes five standalone tests call it. AI-assisted (Claude Code).
lixonik commented 2026-11-26 20:43:06 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by lixonik on 2026-11-26T20:43:06Z.

Review: COMMENTED


Retested 1f92ae6a5 on Windows 11 and CPython 3.12.1, where the original Barry fixture errored. All 26 piecewise parser tests now pass, including the Barry fallback, and all 22 computed-I/J semantic tests pass. This resolves my earlier test failure.

AI-assisted.

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6080300792 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2237#pullrequestreview-6080300792). Originally posted by [lixonik](https://github.com/lixonik) on 2026-11-26T20:43:06Z. **Review:** COMMENTED --- Retested `1f92ae6a5` on Windows 11 and CPython 3.12.1, where the original Barry fixture errored. All 26 piecewise parser tests now pass, including the Barry fallback, and all 22 computed-I/J semantic tests pass. This resolves my earlier test failure. AI-assisted.
Andretuta commented 2026-11-27 21:00:46 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Andretuta on 2026-11-27T21:00:46Z.

Review: COMMENTED


Benchmarked 1f92ae6a5 on Windows with CPython 3.12.13 (the CI version) on top of current main (including #2193's scripts/run_standalone_tests.py -j 2 in check):

  • Semantic suite (-j 6, 500 files, 6,374 tests): 530.87 s -> 393.90 s (-136.97 s / -25.8%), 0 failures.
  • 5 updated standalone test files (-j 2): 47.09 s -> 12.64 s (-34.45 s; serial -j 1: 83.27 s -> 22.67 s).
  • Same standalone slice + tests/test_piecewise_parse.py (-j 2): 70.28 s (+23.19 s net over main; serial -j 1: 83.01 s vs 83.27 s baseline).

The implementation and fallback discipline in piecewise_parse.py and support.py look solid, and no correctness issues turned up. Before taking this out of draft, it may be worth trimming the default wall-clock cost of tests/test_piecewise_parse.py (which runs on every PR in check, macos-python, and the serial stdlib-tests-linux loop): most of the ~58 s on CPython 3.12 comes from RepositoryTest.test_every_python_file_gives_the_whole_file_tree (tests/test_piecewise_parse.py:783-809, parsing all ~1,360 repo .py files twice) and the two separate whole-file parses of tools/rdna2spirv.py in test_the_translator_tree_and_code_object_slow (lines 824 and 833). Keeping all boundary/error/warning/loader tests plus a smaller representative corpus check by default (or gating the full-tree sweep behind an env var) would preserve the standalone CI time savings as well.

AI-assisted review.

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6093316284 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2237#pullrequestreview-6093316284). Originally posted by [Andretuta](https://github.com/Andretuta) on 2026-11-27T21:00:46Z. **Review:** COMMENTED --- Benchmarked `1f92ae6a5` on Windows with CPython 3.12.13 (the CI version) on top of current `main` (including `#2193`'s `scripts/run_standalone_tests.py -j 2` in `check`): - **Semantic suite (`-j 6`, 500 files, 6,374 tests):** `530.87 s` -> `393.90 s` (**-136.97 s / -25.8%**), 0 failures. - **5 updated standalone test files (`-j 2`):** `47.09 s` -> `12.64 s` (**-34.45 s**; serial `-j 1`: `83.27 s` -> `22.67 s`). - **Same standalone slice + `tests/test_piecewise_parse.py` (`-j 2`):** `70.28 s` (**+23.19 s net over `main`**; serial `-j 1`: `83.01 s` vs `83.27 s` baseline). The implementation and fallback discipline in `piecewise_parse.py` and `support.py` look solid, and no correctness issues turned up. Before taking this out of draft, it may be worth trimming the default wall-clock cost of `tests/test_piecewise_parse.py` (which runs on every PR in `check`, `macos-python`, and the serial `stdlib-tests-linux` loop): most of the ~58 s on CPython 3.12 comes from `RepositoryTest.test_every_python_file_gives_the_whole_file_tree` (`tests/test_piecewise_parse.py:783-809`, parsing all ~1,360 repo `.py` files twice) and the two separate whole-file parses of `tools/rdna2spirv.py` in `test_the_translator_tree_and_code_object_slow` (`lines 824` and `833`). Keeping all boundary/error/warning/loader tests plus a smaller representative corpus check by default (or gating the full-tree sweep behind an env var) would preserve the standalone CI time savings as well. AI-assisted review.
Tauwni commented 2026-11-29 07:19:33 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Tauwni on 2026-11-29T07:19:33Z.


Windows 10 complement on the one interpreter range nobody has measured yet: CPython 3.14.6, inside the affected 3.14.0 to 3.14.7 window. Above, 3.13.14 is affected and 3.14.9 is fixed. Windows 10 Pro 22H2 19045.7846, Ryzen 5 5600X. Head 1f92ae6a5 merged (no commit) into main b6bf3aa0b, merges cleanly.

  • piecewise_parse.needed() returns True. MEASURED.
  • Whole-file compile of tools/rdna2spirv.py: 9.38 / 9.42 / 9.39 s. parse() in pieces: 1.09 / 1.08 / 1.09 s, plus 0.15 s to compile the tree. That is 7.6x. MEASURED, 3 runs each.
  • ast.dump(..., include_attributes=True) of the piece tree equals the whole-file parse's. MEASURED, 1 run.
  • The six test files this PR changes or adds pass 3/3 through scripts/run_standalone_tests.py. MEASURED.

Not checked by a second agent or human yet. AI-assisted: yes (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7252403007 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2237#issuecomment-7252403007). Originally posted by [Tauwni](https://github.com/Tauwni) on 2026-11-29T07:19:33Z. --- Windows 10 complement on the one interpreter range nobody has measured yet: CPython 3.14.6, inside the affected 3.14.0 to 3.14.7 window. Above, 3.13.14 is affected and 3.14.9 is fixed. Windows 10 Pro 22H2 19045.7846, Ryzen 5 5600X. Head `1f92ae6a5` merged (no commit) into `main` `b6bf3aa0b`, merges cleanly. - `piecewise_parse.needed()` returns True. MEASURED. - Whole-file `compile` of `tools/rdna2spirv.py`: 9.38 / 9.42 / 9.39 s. `parse()` in pieces: 1.09 / 1.08 / 1.09 s, plus 0.15 s to compile the tree. That is 7.6x. MEASURED, 3 runs each. - `ast.dump(..., include_attributes=True)` of the piece tree equals the whole-file parse's. MEASURED, 1 run. - The six test files this PR changes or adds pass 3/3 through `scripts/run_standalone_tests.py`. MEASURED. Not checked by a second agent or human yet. AI-assisted: yes (Claude Code).
aslan2142 commented 2026-12-01 11:39:23 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by aslan2142 on 2026-12-01T11:39:23Z.


Draft PR review note: tests/semantic/piecewise_parse.py and the companion test updates merge cleanly with main, but the PR is still marked Draft and has no CI run yet. Please mark ready for review and trigger a full green CI pass (check, linux-python-and-viewer, semantic-tests, no-game-data) when ready for final review and merge.

(AI-assisted review.)

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7309942299 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2237#issuecomment-7309942299). Originally posted by [aslan2142](https://github.com/aslan2142) on 2026-12-01T11:39:23Z. --- Draft PR review note: `tests/semantic/piecewise_parse.py` and the companion test updates merge cleanly with `main`, but the PR is still marked Draft and has no CI run yet. Please mark ready for review and trigger a full green CI pass (`check`, `linux-python-and-viewer`, `semantic-tests`, `no-game-data`) when ready for final review and merge. *(AI-assisted review.)*
aslan2142 commented 2026-12-01 12:26:56 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by aslan2142 on 2026-12-01T12:26:56Z.


Marking Ready for Review since no WIP/blocker reason for draft status is specified on this PR, so it can enter normal CI and review.

(AI-assisted triage.)

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7311146129 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2237#issuecomment-7311146129). Originally posted by [aslan2142](https://github.com/aslan2142) on 2026-12-01T12:26:56Z. --- Marking Ready for Review since no WIP/blocker reason for draft status is specified on this PR, so it can enter normal CI and review. *(AI-assisted triage.)*
aslan2142 commented 2026-12-01 13:04:14 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by aslan2142 on 2026-12-01T13:04:14Z.

Review: APPROVED


Now ready for review and MERGEABLE. Clean-room verified: tests/semantic/piecewise_parse.py, tests/semantic/support.py, and the five standalone test updates cleanly avoid CPython 3.12–3.14.7's quadratic f-string tokenizer cost with exact AST/code-object equivalence and safe whole-file fallback; verified across CPython 3.12.1, 3.12.13, 3.12.16, 3.13.14, 3.14.6, 3.14.9, and 3.15.2 (@lixonik, @Andretuta, @GrahamboJangles, @Tauwni). (Non-blocking suggestion: as @Andretuta noted, gating the full-repo RepositoryTest sweep behind an env var would also preserve standalone CI time savings in check.)

Approving — ready to merge once full CI runs green on current main.

(AI-assisted review.)

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6131798678 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2237#pullrequestreview-6131798678). Originally posted by [aslan2142](https://github.com/aslan2142) on 2026-12-01T13:04:14Z. **Review:** APPROVED --- Now ready for review and `MERGEABLE`. Clean-room verified: `tests/semantic/piecewise_parse.py`, `tests/semantic/support.py`, and the five standalone test updates cleanly avoid CPython 3.12–3.14.7's quadratic f-string tokenizer cost with exact AST/code-object equivalence and safe whole-file fallback; verified across CPython 3.12.1, 3.12.13, 3.12.16, 3.13.14, 3.14.6, 3.14.9, and 3.15.2 (`@lixonik`, `@Andretuta`, `@GrahamboJangles`, `@Tauwni`). (Non-blocking suggestion: as `@Andretuta` noted, gating the full-repo `RepositoryTest` sweep behind an env var would also preserve standalone CI time savings in `check`.) Approving — ready to merge once full CI runs green on current `main`. *(AI-assisted review.)*
merzleckeier commented 2026-12-01 13:17:37 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by merzleckeier on 2026-12-01T13:17:37Z.


Verified the piecewise loader with a simultaneous translator change at 1f92ae6a5 + ed867d7b2. All 26 parser tests passed on CPython 3.14.10. I also merged #2099 locally and forced the actual ToolsFinder path in a fresh process. The hook confirmed that rdna2spirv.py produced an AST from pieces. All six synthetic LOD modules (three masks each for array and cube) were byte-identical to the ordinary import and passed Vulkan 1.2 validation. CPython 3.14.10 uses the ordinary path by default, so this is a forced-loader correctness check.

AI-assisted with OpenAI Codex.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7312394715 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2237#issuecomment-7312394715). Originally posted by [merzleckeier](https://github.com/merzleckeier) on 2026-12-01T13:17:37Z. --- Verified the piecewise loader with a simultaneous translator change at `1f92ae6a5` + `ed867d7b2`. All 26 parser tests passed on CPython 3.14.10. I also merged #2099 locally and forced the actual `ToolsFinder` path in a fresh process. The hook confirmed that `rdna2spirv.py` produced an AST from pieces. All six synthetic LOD modules (three masks each for array and cube) were byte-identical to the ordinary import and passed Vulkan 1.2 validation. CPython 3.14.10 uses the ordinary path by default, so this is a forced-loader correctness check. AI-assisted with OpenAI Codex.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
ProjectLeonida/mandy!2237
No description provided.