diff --git a/explain_my_code/adapters/python.py b/explain_my_code/adapters/python.py index eef0e55..b9877fd 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( @@ -1063,18 +1063,28 @@ 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, MemoryError, RecursionError): - continue + except SyntaxError as exc: + end = min(end, exc.lineno) - 1 if exc.lineno else end - 1 + except (MemoryError, RecursionError): + 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("")