From 168128d0cd300f455285ad39678877c53b14e1a3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 06:43:57 +0000 Subject: [PATCH 1/2] Make the tree-sitter adapters' language overrides actually run Two bugs in the shared tree-sitter walk meant per-language code never ran: - `_COMMON_META` bound the base-class builder functions, so `JavaAdapter._meta_call` and `CppAdapter._meta_member`/`_meta_index` were dead code. Every Java call had an empty callee and receiver, so the UI said "Calls `the function` on `the object`", known costs never applied, and naive Java `fib` was not flagged exponential the way the Python and C++ ones are. C++ member and index access read the wrong fields (index key was the container name). - `recurse_into` dropped the `name` child with `c is not name_field`, but py-tree-sitter returns a new wrapper on every access, so the check never matched. Each definition got a NAME child of its own name, which counted as a use: no JavaScript variable could ever be reported as unused. C++ functions had the same duplicate via their declarator. The builder table now holds method names resolved on `self`, node comparison uses `!=`, and C++ callables descend into their parameter list rather than the whole declarator. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UigC7feaY8NkAy9oay3GDW --- explain_my_code/adapters/cpp.py | 13 ++++++ explain_my_code/adapters/javascript.py | 2 +- explain_my_code/adapters/treesitter.py | 61 ++++++++++++++------------ tests/test_adapters.py | 40 +++++++++++++++++ tests/test_analysis.py | 16 +++++++ 5 files changed, 103 insertions(+), 29 deletions(-) diff --git a/explain_my_code/adapters/cpp.py b/explain_my_code/adapters/cpp.py index 5a9a618..4499abf 100644 --- a/explain_my_code/adapters/cpp.py +++ b/explain_my_code/adapters/cpp.py @@ -169,6 +169,19 @@ def recurse_into(self, ts_node, kind): # type: ignore[override] if (value := _field(declarator, "value")) is not None ] return [] + if kind in {Kind.FUNCTION, Kind.METHOD, Kind.CONSTRUCTOR}: + # The name sits at the bottom of the declarator chain rather than in a + # `name` field. Descend into the parameter list only, so the function's + # own name does not come back as a NAME child. + declarator = _field(ts_node, "declarator") + function_declarator = _find_function_declarator(ts_node) + params = ( + _field(function_declarator, "parameters") + if function_declarator is not None + else None + ) + rest = [c for c in ts_node.named_children if c != declarator] + return [params, *rest] if params is not None else rest return super().recurse_into(ts_node, kind) def _catch_type(self, ts_node) -> str: # type: ignore[override] diff --git a/explain_my_code/adapters/javascript.py b/explain_my_code/adapters/javascript.py index 121ae4e..87b129a 100644 --- a/explain_my_code/adapters/javascript.py +++ b/explain_my_code/adapters/javascript.py @@ -139,7 +139,7 @@ def recurse_into(self, ts_node, kind): # type: ignore[override] children = super().recurse_into(ts_node, kind) if kind in {Kind.FUNCTION, Kind.METHOD, Kind.CONSTRUCTOR, Kind.LAMBDA}: params = _field(ts_node, "parameters") - children = [c for c in children if c is not params] + children = [c for c in children if c != params] return children def synth_children(self, ts_node, kind): # type: ignore[override] diff --git a/explain_my_code/adapters/treesitter.py b/explain_my_code/adapters/treesitter.py index 5ac33fb..cef3618 100644 --- a/explain_my_code/adapters/treesitter.py +++ b/explain_my_code/adapters/treesitter.py @@ -305,7 +305,9 @@ def recurse_into(self, ts_node: TSNode, kind: Kind) -> list[TSNode]: name_field = _field(ts_node, "name") if name_field is None: return list(ts_node.named_children) - return [c for c in ts_node.named_children if c is not name_field] + # `!=`, not `is not`: py-tree-sitter hands out a fresh wrapper object on every + # access, so identity never matches even for the same node. + return [c for c in ts_node.named_children if c != name_field] def _param_nodes(self, ts_node: TSNode, owner: str, params: list[dict[str, Any]]) -> list[Node]: holder = _field(ts_node, "parameters") or _field(ts_node, "declarator") @@ -373,8 +375,10 @@ def name_for(self, ts_node: TSNode, kind: Kind) -> str | None: # -- meta ------------------------------------------------------------------ def meta_for(self, ts_node: TSNode, kind: Kind) -> dict[str, Any]: + # Looked up by name on `self`, so a language's own `_meta_call` (Java keeps the + # callee in `name`, not `function`) replaces the shared builder. base = _COMMON_META.get(kind) - meta = base(self, ts_node) if base else {} + meta = getattr(self, base)(ts_node) if base else {} hook = getattr(self, f"meta_{kind.value}", None) if hook is not None: meta.update(hook(ts_node)) @@ -632,30 +636,31 @@ def _meta_new(self, ts_node: TSNode) -> dict[str, Any]: "initializer_list": "list", } -#: Kind -> shared meta builder. Language subclasses override with `meta_` hooks. -_COMMON_META: dict[Kind, Callable[[TreeSitterAdapter, TSNode], dict[str, Any]]] = { - Kind.CALL: TreeSitterAdapter._meta_call, - Kind.METHOD_CALL: TreeSitterAdapter._meta_call, - Kind.BINOP: TreeSitterAdapter._meta_binary, - Kind.COMPARE: TreeSitterAdapter._meta_binary, - Kind.BOOLOP: TreeSitterAdapter._meta_binary, - Kind.UNOP: TreeSitterAdapter._meta_unary, - Kind.ASSIGN: TreeSitterAdapter._meta_assign, - Kind.AUG_ASSIGN: TreeSitterAdapter._meta_assign, - Kind.BRANCH: TreeSitterAdapter._meta_branch, - Kind.LOOP_WHILE: TreeSitterAdapter._meta_while, - Kind.LOOP_DO: TreeSitterAdapter._meta_while, - Kind.LOOP_FOR: TreeSitterAdapter._meta_classic_for, - Kind.LOOP_FOREACH: TreeSitterAdapter._meta_foreach, - Kind.RETURN: TreeSitterAdapter._meta_return, - Kind.ATTRIBUTE: TreeSitterAdapter._meta_member, - Kind.INDEX: TreeSitterAdapter._meta_index, - Kind.TERNARY: TreeSitterAdapter._meta_ternary, - Kind.THROW: TreeSitterAdapter._meta_throw, - Kind.TRY: TreeSitterAdapter._meta_try, - Kind.CATCH: TreeSitterAdapter._meta_catch, - Kind.LITERAL: TreeSitterAdapter._meta_literal, - Kind.SWITCH: TreeSitterAdapter._meta_switch, - Kind.COLLECTION: TreeSitterAdapter._meta_collection, - Kind.NEW: TreeSitterAdapter._meta_new, +#: Kind -> name of the shared meta builder. A language subclass can override the builder +#: itself (`_meta_call`) or extend it with a `meta_` hook. +_COMMON_META: dict[Kind, str] = { + Kind.CALL: "_meta_call", + Kind.METHOD_CALL: "_meta_call", + Kind.BINOP: "_meta_binary", + Kind.COMPARE: "_meta_binary", + Kind.BOOLOP: "_meta_binary", + Kind.UNOP: "_meta_unary", + Kind.ASSIGN: "_meta_assign", + Kind.AUG_ASSIGN: "_meta_assign", + Kind.BRANCH: "_meta_branch", + Kind.LOOP_WHILE: "_meta_while", + Kind.LOOP_DO: "_meta_while", + Kind.LOOP_FOR: "_meta_classic_for", + Kind.LOOP_FOREACH: "_meta_foreach", + Kind.RETURN: "_meta_return", + Kind.ATTRIBUTE: "_meta_member", + Kind.INDEX: "_meta_index", + Kind.TERNARY: "_meta_ternary", + Kind.THROW: "_meta_throw", + Kind.TRY: "_meta_try", + Kind.CATCH: "_meta_catch", + Kind.LITERAL: "_meta_literal", + Kind.SWITCH: "_meta_switch", + Kind.COLLECTION: "_meta_collection", + Kind.NEW: "_meta_new", } diff --git a/tests/test_adapters.py b/tests/test_adapters.py index 9d0cb6a..b181e5e 100644 --- a/tests/test_adapters.py +++ b/tests/test_adapters.py @@ -185,6 +185,46 @@ def test_finds_an_import(parsed): assert imports[0].meta.get("module") +def test_calls_name_their_callee(parsed): + """Every adapter must fill `callee`: the call graph, the cost model and the + phrasebook all read it. Java's own builder used to be bypassed, leaving it empty.""" + language, result = parsed + if language is Language.SQL: + pytest.skip("covered by the SQL function tests") + fib = next(n for n in result.root.walk() if n.kind in CALLABLE_KINDS and n.name == "fib") + calls = [n for n in fib.walk() if n.kind in {Kind.CALL, Kind.METHOD_CALL}] + assert [c.meta["callee"] for c in calls] == ["fib", "fib"] + assert all(c.meta["args"] for c in calls) + + +def test_definitions_do_not_repeat_their_own_name_as_a_child(parsed): + """The `name` field is already the node's name; emitting it again as a NAME child + reads as a use of that name, which hid every unused JS variable.""" + _, result = parsed + for node in result.root.walk(): + if node.kind in CALLABLE_KINDS | {Kind.CLASS, Kind.DECL} and node.name: + names = [c.name for c in node.children if c.kind is Kind.NAME] + assert node.name not in names, f"{node.kind.value} `{node.name}` repeats its name" + + +def test_java_calls_keep_their_receiver(): + result = get_adapter(Language.JAVA).parse( + "class A { void f(int x) { System.out.println(x); } }" + ) + call = next(n for n in result.root.walk() if n.kind is Kind.METHOD_CALL) + assert (call.meta["callee"], call.meta["receiver"]) == ("println", "System.out") + assert call.meta["is_builtin"] + + +def test_cpp_member_and_index_read_cpp_field_names(): + """C++ calls the object `argument`, not `object`; its own builders say so.""" + result = get_adapter(Language.CPP).parse("int f(Point* p, int* v, int i) { return p->x + v[i]; }") + member = next(n for n in result.root.walk() if n.kind is Kind.ATTRIBUTE) + index = next(n for n in result.root.walk() if n.kind is Kind.INDEX) + assert (member.meta["object"], member.meta["attribute"], member.meta["via_pointer"]) == ("p", "x", True) + assert (index.meta["container"], index.meta["key"]) == ("v", "i") + + def test_keyword_inside_a_string_is_not_a_construct(): """The v1 regression: `# for` and `"if"` are not control flow.""" source = 'message = "if you can for loop while true"\n# for while if\n' diff --git a/tests/test_analysis.py b/tests/test_analysis.py index 87d8b2c..4feeb09 100644 --- a/tests/test_analysis.py +++ b/tests/test_analysis.py @@ -247,6 +247,22 @@ def test_unused_local_is_reported(): assert "unused" in {symbol.name for symbol in analysis.symbols.unused} +def test_unused_local_is_reported_in_javascript(): + source = "function go() {\n const used = 1;\n const unused = 2;\n return used;\n}\n" + analysis = analyze(source, Language.JAVASCRIPT) + assert {symbol.name for symbol in analysis.symbols.unused} == {"unused"} + + +def test_naive_recursion_is_exponential_in_java_too(): + analysis = analyze( + "class A {\n int fib(int n) {\n if (n < 2) return n;\n" + " return fib(n - 1) + fib(n - 2);\n }\n}\n", + Language.JAVA, + ) + assert function(analysis, "fib").complexity_class == "O(2^n)" + assert "exponential-recursion" in rules(analysis) + + def test_underscore_prefixed_names_are_left_alone(): analysis = analyze("def go():\n _ignored = 1\n return 2\n") assert "_ignored" not in {symbol.name for symbol in analysis.symbols.unused} From 804983d2a358858d1122866d09c3a1426b5a6e06 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 07:12:11 +0000 Subject: [PATCH 2/2] Move the tree-sitter analysis tests to their own section They sat at the same spot as the Python lowering tests in another open PR; at the end of the file the two merge cleanly in either order. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UigC7feaY8NkAy9oay3GDW --- tests/test_analysis.py | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/tests/test_analysis.py b/tests/test_analysis.py index 4feeb09..2adda22 100644 --- a/tests/test_analysis.py +++ b/tests/test_analysis.py @@ -247,22 +247,6 @@ def test_unused_local_is_reported(): assert "unused" in {symbol.name for symbol in analysis.symbols.unused} -def test_unused_local_is_reported_in_javascript(): - source = "function go() {\n const used = 1;\n const unused = 2;\n return used;\n}\n" - analysis = analyze(source, Language.JAVASCRIPT) - assert {symbol.name for symbol in analysis.symbols.unused} == {"unused"} - - -def test_naive_recursion_is_exponential_in_java_too(): - analysis = analyze( - "class A {\n int fib(int n) {\n if (n < 2) return n;\n" - " return fib(n - 1) + fib(n - 2);\n }\n}\n", - Language.JAVA, - ) - assert function(analysis, "fib").complexity_class == "O(2^n)" - assert "exponential-recursion" in rules(analysis) - - def test_underscore_prefixed_names_are_left_alone(): analysis = analyze("def go():\n _ignored = 1\n return 2\n") assert "_ignored" not in {symbol.name for symbol in analysis.symbols.unused} @@ -308,3 +292,22 @@ def test_analysis_scales_without_blowing_up(size): source = "\n".join(f"def f{i}(x):\n return x + {i}\n" for i in range(size)) analysis = analyze(source) assert len(analysis.functions) == size + + +# -- tree-sitter languages ----------------------------------------------------------- + + +def test_unused_local_is_reported_in_javascript(): + source = "function go() {\n const used = 1;\n const unused = 2;\n return used;\n}\n" + analysis = analyze(source, Language.JAVASCRIPT) + assert {symbol.name for symbol in analysis.symbols.unused} == {"unused"} + + +def test_naive_recursion_is_exponential_in_java_too(): + analysis = analyze( + "class A {\n int fib(int n) {\n if (n < 2) return n;\n" + " return fib(n - 1) + fib(n - 2);\n }\n}\n", + Language.JAVA, + ) + assert function(analysis, "fib").complexity_class == "O(2^n)" + assert "exponential-recursion" in rules(analysis)