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 c8f4f59..ec8e14d 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 5c8447f..2588d98 100644 --- a/tests/test_analysis.py +++ b/tests/test_analysis.py @@ -445,3 +445,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)