Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion explain_my_code/adapters/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -1041,6 +1041,13 @@ def parse(self, source: str) -> ParseResult:
diagnostics.append(
Diagnostic(message="Explained the portion above the error.", severity="info")
)
except MemoryError as exc:
# CPython's parser reports a stack overflow on extreme nesting as MemoryError
# (bare on 3.11, "Python source too complex to parse" from 3.12). Input is
# capped at MAX_SOURCE_BYTES, so this is that condition, not a real OOM. It is
# the same as our own passes hitting the recursion limit and is reported the
# same way, by the caller.
raise RecursionError(str(exc) or "parser stack overflowed") from exc

lowerer = PythonLowerer(source)
root = lowerer.lower(tree)
Expand All @@ -1066,7 +1073,7 @@ def _parse_longest_prefix(source: str) -> ast.Module | None:
for end in range(len(lines) - 1, 0, -1):
try:
return ast.parse("\n".join(lines[:end]))
except SyntaxError:
except (SyntaxError, MemoryError, RecursionError):
continue
return None

Expand Down
8 changes: 5 additions & 3 deletions explain_my_code/adapters/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,17 @@
)

try:
# SqlglotError, not ParseError: an unterminated string or comment fails in the
# tokenizer and raises TokenError, which is a sibling of ParseError.
import sqlglot
from sqlglot import expressions as exp
from sqlglot.errors import ParseError
from sqlglot.errors import SqlglotError

SQLGLOT_AVAILABLE = True
except ImportError: # pragma: no cover
sqlglot = None # type: ignore[assignment]
exp = None # type: ignore[assignment]
ParseError = Exception # type: ignore[assignment,misc]
SqlglotError = Exception # type: ignore[assignment,misc]
SQLGLOT_AVAILABLE = False


Expand Down Expand Up @@ -596,7 +598,7 @@ def parse(self, source: str) -> ParseResult:
diagnostics: list[Diagnostic] = []
try:
statements = sqlglot.parse(source)
except ParseError as error:
except SqlglotError as error:
diagnostics.append(Diagnostic(f"Could not parse SQL: {error}", severity="error"))
return ParseResult(
root, Language.SQL, source, diagnostics, self.parser_name, degraded=True
Expand Down
80 changes: 66 additions & 14 deletions explain_my_code/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,23 @@

import re
import time
from collections.abc import Callable
from dataclasses import dataclass, field
from functools import partial
from typing import Any

from explain_my_code.adapters.base import get_adapter, load_all, registered_languages
from explain_my_code.analysis.pipeline import Analysis, analyze
from explain_my_code.ir import Annotation, Diagnostic, Language, Level, ParseResult
from explain_my_code.ir import (
Annotation,
Diagnostic,
Kind,
Language,
Level,
Node,
ParseResult,
Span,
)
from explain_my_code.narrate.annotate import LineExplanation, annotate, line_view, summarize

load_all()
Expand Down Expand Up @@ -158,19 +169,17 @@ def explain(
language = Language(language)

timings: dict[str, float] = {}

started = time.perf_counter()
parsed: ParseResult = get_adapter(language).parse(code)
timings["parse"] = (time.perf_counter() - started) * 1000

started = time.perf_counter()
analysis = analyze(parsed)
timings["analyze"] = (time.perf_counter() - started) * 1000

started = time.perf_counter()
annotations = annotate(parsed, analysis, level)
summary = summarize(analysis, level)
timings["explain"] = (time.perf_counter() - started) * 1000
adapter = get_adapter(language)
try:
parsed, analysis, annotations, summary = _static_pass(adapter.parse, code, level, timings)
except RecursionError:
# The lowering and analysis passes recurse over the tree, so pathological
# nesting (a thousand-term `a + b + ...` chain, thousands of nested brackets)
# can exhaust the interpreter's recursion limit. That is reported the way a
# parse failure is, instead of failing the whole request.
timings.clear()
too_deep = partial(_too_deep_to_explain, language=language, parser=adapter.parser_name)
parsed, analysis, annotations, summary = _static_pass(too_deep, code, level, timings)

enrichment = None
if enrich:
Expand Down Expand Up @@ -205,6 +214,49 @@ def explain(
)


TOO_DEEP_MESSAGE = (
"This code is nested too deeply to explain: an expression or block goes hundreds of "
"levels deep (a very long `a + b + c + ...` chain counts). Split it up and try again."
)


def _static_pass(
parse: Callable[[str], ParseResult], code: str, level: Level, timings: dict[str, float]
) -> tuple[ParseResult, Analysis, list[Annotation], str]:
started = time.perf_counter()
parsed = parse(code)
timings["parse"] = (time.perf_counter() - started) * 1000

started = time.perf_counter()
analysis = analyze(parsed)
timings["analyze"] = (time.perf_counter() - started) * 1000

started = time.perf_counter()
annotations = annotate(parsed, analysis, level)
summary = summarize(analysis, level)
timings["explain"] = (time.perf_counter() - started) * 1000
return parsed, analysis, annotations, summary


def _too_deep_to_explain(source: str, *, language: Language, parser: str) -> ParseResult:
"""An empty, degraded parse that carries the reason as an error diagnostic."""
lines = source.splitlines()
root = Node(
kind=Kind.MODULE,
span=Span(1, 0, max(len(lines), 1), 0),
name="module",
meta={"unparsed": True},
)
return ParseResult(
root,
language,
source,
[Diagnostic(TOO_DEEP_MESSAGE, severity="error")],
parser,
degraded=True,
)


def supported_languages() -> list[dict[str, Any]]:
out = []
for language in registered_languages():
Expand Down
15 changes: 15 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,21 @@ def test_analyze_returns_metrics_without_prose():
assert body["analysis"]["metrics"]["cyclomatic"] == 1


@pytest.mark.parametrize(
"payload",
[
{"code": "SELECT 'never closed", "language": "sql"},
{"code": "x = " + " + ".join(["a"] * 1_000) + "\n", "language": "python"},
],
ids=["sql-token-error", "deep-python"],
)
@pytest.mark.parametrize("path", ["/v1/explain", "/v1/explain/all-levels", "/v1/analyze"])
def test_hostile_input_gets_a_degraded_answer_not_a_500(path, payload):
response = TestClient(app, raise_server_exceptions=False).post(path, json=payload)
assert response.status_code == 200
assert any(d["severity"] == "error" for d in response.json()["diagnostics"])


def test_detect_endpoint():
body = client.post("/v1/detect", json={"code": "#include <cstdio>\nint main(){}"}).json()
assert body["language"] == "cpp"
Expand Down
41 changes: 41 additions & 0 deletions tests/test_explain.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,47 @@ def test_syntax_error_is_reported_not_raised():
assert any(d.severity == "error" for d in result.diagnostics)


@pytest.mark.parametrize(
"source",
["SELECT 'unterminated", 'SELECT "unterminated', "SELECT a FROM t /* unterminated"],
ids=["single-quote", "double-quote", "block-comment"],
)
def test_sql_that_fails_to_tokenize_is_reported_not_raised(source):
"""sqlglot raises TokenError, not ParseError, when a string or comment never ends."""
result = explain(source, language=Language.SQL)
assert result.analysis.degraded
assert any(d.severity == "error" for d in result.diagnostics)


DEEP_INPUTS = {
"python-long-chain": (Language.PYTHON, "x = " + " + ".join(["a"] * 1_000) + "\n"),
"python-parser-overflow": (Language.PYTHON, "x = " + "-" * 10_000 + "1\n"),
"javascript-nested-arrays": (Language.JAVASCRIPT, "const x = " + "[" * 3_000 + "]" * 3_000 + ";\n"),
"java-nested-parens": (
Language.JAVA, "class A { int f() { return " + "(" * 3_000 + "1" + ")" * 3_000 + "; } }\n"
),
"cpp-nested-parens": (Language.CPP, "int f() { return " + "(" * 3_000 + "1" + ")" * 3_000 + "; }\n"),
"sql-nested-parens": (Language.SQL, "SELECT " + "(" * 500 + "1" + ")" * 500 + ";\n"),
}


@pytest.mark.parametrize("language,source", list(DEEP_INPUTS.values()), ids=list(DEEP_INPUTS))
def test_pathologically_deep_nesting_is_reported_not_raised(language, source):
"""These used to escape `explain()` as RecursionError (or MemoryError from CPython's
own parser), which the API turned into a bare 500."""
result = explain(source, language=language)
assert result.analysis.degraded
assert any("nested too deeply" in d.message for d in result.diagnostics)
assert isinstance(result.summary, str)
assert result.to_dict()["degraded"] is True


def test_moderately_deep_code_is_still_explained():
result = explain("x = " + " + ".join(["a"] * 150) + "\n", language=Language.PYTHON)
assert not result.analysis.degraded
assert result.lines


def test_supported_languages_are_all_available():
for entry in supported_languages():
assert entry["available"], f"{entry['id']} is not available"
Expand Down
Loading