From bea01328702253f6757cbf7926911d36ca4c6351 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 06:59:42 +0000 Subject: [PATCH] Stop re-parsing a broken Python file once per line When a paste has a syntax error, the adapter salvages the longest prefix that parses. It did that by dropping one line at a time and re-parsing, so an error near the top of a large file re-parsed it thousands of times: 197KB broken on line 1 took 7.0s, all of it in `ast.parse`. A prefix that still contains the line the SyntaxError was reported on fails the same way, so each failed attempt now jumps to just above the reported line. On ~1,500 randomly broken stdlib files (Python 3.11, 3.12 and 3.13) the salvaged tree is identical to the old one every time. The 197KB case now takes 4ms. Node.walk is also iterative now. The recursive generator passed every node up through one frame per ancestor, which costs O(nodes * depth); on deeply nested input (40 lines of 300-term sums) explain() goes from 7.3s to 5.4s. On ordinary code the difference is within noise. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UigC7feaY8NkAy9oay3GDW --- explain_my_code/adapters/python.py | 18 ++++++++++---- explain_my_code/ir.py | 15 ++++++++--- tests/test_adapters.py | 40 ++++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+), 9 deletions(-) diff --git a/explain_my_code/adapters/python.py b/explain_my_code/adapters/python.py index 02a287d..01f58bf 100644 --- a/explain_my_code/adapters/python.py +++ b/explain_my_code/adapters/python.py @@ -1026,7 +1026,7 @@ def parse(self, source: str) -> ParseResult: severity="error", ) ) - partial = _parse_longest_prefix(source) + partial = _parse_longest_prefix(source, exc.lineno) if partial is None: lines = source.splitlines() root = Node( @@ -1056,18 +1056,26 @@ def parse(self, source: str) -> ParseResult: ) -def _parse_longest_prefix(source: str) -> ast.Module | None: +def _parse_longest_prefix(source: str, error_line: int | None = None) -> ast.Module | None: """Salvage a partial tree from broken input. Someone pasting a snippet mid-edit should still get an explanation of the lines that do parse, rather than a blank page. + + A prefix that still contains the line a SyntaxError was reported on fails the same + way, so each failed attempt jumps to just above the reported line instead of + retrying one line shorter. Trimming a line at a time re-parsed the file once per + line: about seven seconds for a 200KB file broken near the top. """ lines = source.splitlines() - for end in range(len(lines) - 1, 0, -1): + end = len(lines) - 1 + if error_line: + end = min(end, error_line - 1) + while end > 0: try: return ast.parse("\n".join(lines[:end])) - except SyntaxError: - continue + except SyntaxError as exc: + end = min(end, exc.lineno) - 1 if exc.lineno else end - 1 return None diff --git a/explain_my_code/ir.py b/explain_my_code/ir.py index 56f81af..328095a 100644 --- a/explain_my_code/ir.py +++ b/explain_my_code/ir.py @@ -270,10 +270,17 @@ def extend(self, children: list[Node]) -> Node: return self def walk(self) -> Iterator[Node]: - """Pre-order traversal, self first.""" - yield self - for child in self.children: - yield from child.walk() + """Pre-order traversal, self first. + + Iterative on purpose. A recursive generator hands every node up through one + `yield from` frame per ancestor, so a full walk cost O(nodes * depth), and the + analysis passes walk the tree a few dozen times per request. + """ + stack = [self] + while stack: + node = stack.pop() + yield node + stack.extend(reversed(node.children)) def find(self, *kinds: Kind) -> Iterator[Node]: wanted = set(kinds) diff --git a/tests/test_adapters.py b/tests/test_adapters.py index 9d0cb6a..c8f4f59 100644 --- a/tests/test_adapters.py +++ b/tests/test_adapters.py @@ -201,6 +201,46 @@ def test_broken_python_still_explains_the_prefix(): assert "good" in names, "salvageable prefix was discarded" +@pytest.mark.parametrize( + "source,kept", + [ + ("def a():\n return 1\n\ndef b(:\n pass\n\ndef c():\n return 3\n", {"a"}), + ("def a():\n return 1\n\nx = foo(\n\ndef c():\n return 3\n", {"a"}), + ("def a():\n return 1\n\ndef b():\n return 2\n\nif x\n", {"a", "b"}), + ("def a():\n return 1\n\ndef b():\n", {"a"}), + ('def a():\n return 1\n\ns = """never closed\n\ndef c():\n return 3\n', {"a"}), + ], + ids=["bad-def", "unclosed-call", "last-line", "missing-body-at-eof", "unterminated-string"], +) +def test_broken_python_keeps_everything_above_the_error(source, kept): + result = get_adapter(Language.PYTHON).parse(source) + assert {n.name for n in result.root.walk() if n.kind in CALLABLE_KINDS} == kept + + +def test_salvaging_a_large_broken_file_does_not_reparse_it_line_by_line(monkeypatch): + """Trimming one line per attempt re-parsed a 200KB file thousands of times.""" + import ast + + calls = [] + real_parse = ast.parse + monkeypatch.setattr(ast, "parse", lambda text, *a, **k: calls.append(1) or real_parse(text, *a, **k)) + body = "".join(f"def f{i}(x):\n return x + {i}\n\n" for i in range(2_000)) + result = get_adapter(Language.PYTHON).parse("x = (\ny = 1\n" + body) + assert any(d.severity == "error" for d in result.diagnostics) + assert len(calls) <= 3 + + +def test_walk_is_pre_order(): + result = get_adapter(Language.PYTHON).parse(SNIPPETS[Language.PYTHON]) + + def recursive(node): + yield node + for child in node.children: + yield from recursive(child) + + assert [n.id for n in result.root.walk()] == [n.id for n in recursive(result.root)] + + def test_empty_source_is_not_a_crash(): for language in SNIPPETS: result = get_adapter(language).parse("")