Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(typescript): give object-literal methods their own symbol (#2772)

Raghav Chamadiya2b288ce6bc3f
diff --git a/packages/core/src/repowise/core/ingestion/lang_helpers/ts_js.py b/packages/core/src/repowise/core/ingestion/lang_helpers/ts_js.py
new file mode 100644
index 000000000..af010a406
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/lang_helpers/ts_js.py
@@ -0,0 +1,92 @@
+"""TypeScript / JavaScript object-literal method helpers."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ..extractors import node_text
+
+# Functions that carry their own name.
+_TS_NAMED_FUNCTIONS = frozenset(
+ {"function_declaration", "generator_function_declaration", "method_definition"}
+)
+
+# Function values, named only by what they are bound to.
+_TS_FUNCTION_VALUES = frozenset(
+ {"arrow_function", "function_expression", "function", "generator_function"}
+)
+
+# What names a function value: ``const f = () => {}``, ``{ f: () => {} }``, a
+# class field, ``export default () => {}``.
+_TS_VALUE_BINDERS = frozenset(
+ {
+ "variable_declarator",
+ "pair",
+ "public_field_definition",
+ "field_definition",
+ "export_statement",
+ }
+)
+
+# Bindings that own an object literal, with the field holding their name: a
+# property key, a declarator, a TS class field, a JS class field.
+_TS_OBJECT_OWNER_FIELDS = {
+ "pair": "key",
+ "variable_declarator": "name",
+ "public_field_definition": "name",
+ "field_definition": "property",
+}
+
+_TS_OWNER_NAME_TYPES = frozenset(
+ {"identifier", "property_identifier", "private_property_identifier"}
+)
+
+_CALLABLE_KINDS = frozenset({"function", "method"})
+
+
+def _ts_is_named_function(node: Node) -> bool:
+ if node.type in _TS_NAMED_FUNCTIONS:
+ return True
+ return (
+ node.type in _TS_FUNCTION_VALUES
+ and node.parent is not None
+ and node.parent.type in _TS_VALUE_BINDERS
+ )
+
+
+def _ts_nested_object_method_owner(
+ def_node: Node, src: str, symbol_kinds: dict[str, str]
+) -> str | None:
+ """The owner of an object-literal method the callable filter would drop.
+
+ ``const Foo = make("Foo", (inst) => install(inst, { gt() {...} }))``: the
+ anonymous callback names nothing, so ``gt`` is the nearest name its calls
+ can be attributed to, as a type checker does, and ``Foo`` qualifies its id
+ so a same-named method of another object keeps a distinct one.
+
+ None when a named function encloses the method (it stays a local of that
+ function), when no callable encloses it (the filter keeps it already, under
+ its existing id), or when the nearest owner has no plain name (a string
+ key, a destructuring pattern), since an unqualified id could collide.
+ """
+ if def_node.type != "method_definition":
+ return None
+ parent = def_node.parent
+ if parent is None or parent.type != "object":
+ return None
+ owner: str | None = None
+ owner_seen = False
+ under_callable = False
+ ancestor = parent.parent
+ while ancestor is not None:
+ if _ts_is_named_function(ancestor):
+ return None
+ if not owner_seen and ancestor.type in _TS_OBJECT_OWNER_FIELDS:
+ owner_seen = True
+ name = ancestor.child_by_field_name(_TS_OBJECT_OWNER_FIELDS[ancestor.type])
+ if name is not None and name.type in _TS_OWNER_NAME_TYPES:
+ owner = node_text(name, src)
+ if symbol_kinds.get(ancestor.type) in _CALLABLE_KINDS:
+ under_callable = True
+ ancestor = ancestor.parent
+ return owner if under_callable else None
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 19e0ce3cd..5fd19f54d 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -113,6 +113,7 @@ from .parser_helpers import (
_qualified_pascal_parent,
_run_query,
_rust_shadowed_by_type_param,
+ _ts_nested_object_method_owner,
)
from .python_local_refs import extract_python_local_refs
from .sfc_source import component_call_sites, prepare_source
@@ -1448,7 +1449,21 @@ class ASTParser:
def_node, name_nodes, name, export_type, start_line = identity
node_type = def_node.type
- kind = self._symbol_kind(def_node, config, language, src, cpp_exports.parent_ids)
+ # A TS/JS object-literal method inside an anonymous callback is kept,
+ # qualified by the binding that owns its object.
+ object_owner = (
+ _ts_nested_object_method_owner(def_node, src, config.symbol_node_types)
+ if language in _TS_JS_LANGUAGES
+ else None
+ )
+ kind = self._symbol_kind(
+ def_node,
+ config,
+ language,
+ src,
+ cpp_exports.parent_ids,
+ keep_nested=object_owner is not None,
+ )
if kind is None:
return None
@@ -1471,7 +1486,7 @@ class ASTParser:
src,
)
- parent_name = self._resolve_parent_name(
+ parent_name = object_owner or self._resolve_parent_name(
def_node,
config,
capture_dict.get("symbol.receiver", []),
@@ -1532,6 +1547,8 @@ class ASTParser:
language: str,
src: str,
export_type_parent_ids: frozenset[int],
+ *,
+ keep_nested: bool = False,
) -> str | None:
"""The symbol kind for *def_node*, or None when it is not a symbol here."""
node_type = def_node.type
@@ -1541,9 +1558,12 @@ class ASTParser:
# Only module-level and class-body members are symbols; the query is
# recursive, so defs nested in a callable are dropped. Module-anchored
- # node types only match at module level and skip the check.
- if node_type not in _MODULE_ANCHORED_NODE_TYPES and _has_callable_ancestor(
- def_node, config.symbol_node_types, export_type_parent_ids
+ # node types only match at module level and skip the check, as does a
+ # def the caller has placed already (``keep_nested``).
+ if (
+ not keep_nested
+ and node_type not in _MODULE_ANCHORED_NODE_TYPES
+ and _has_callable_ancestor(def_node, config.symbol_node_types, export_type_parent_ids)
):
return None
diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.py
index dce4aa97b..ea0ae6642 100644
--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py
+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py
@@ -37,6 +37,7 @@ from .lang_helpers.objc import (
)
from .lang_helpers.pascal import _dedupe_pascal_interface_symbols, _qualified_pascal_parent
from .lang_helpers.source_prep import prepare_objectivec_source, prepare_pascal_source
+from .lang_helpers.ts_js import _ts_nested_object_method_owner
from .lang_helpers.type_heads import (
TYPE_HEAD_EXTRACTORS,
_classify_param_origin,
@@ -79,6 +80,7 @@ __all__ = [
"_run_query",
"_rust_head_type_identifier",
"_rust_shadowed_by_type_param",
+ "_ts_nested_object_method_owner",
"prepare_objectivec_source",
"prepare_pascal_source",
]
diff --git a/tests/unit/ingestion/parser/test_typescript.py b/tests/unit/ingestion/parser/test_typescript.py
index 878593459..66353ffdd 100644
--- a/tests/unit/ingestion/parser/test_typescript.py
+++ b/tests/unit/ingestion/parser/test_typescript.py
@@ -794,3 +794,106 @@ class Outer {
symbols = parser.parse_file(fi, src).symbols
assert [s.name for s in symbols] == ["Outer"]
assert "inner" not in {s.name for s in symbols}
+
+
+class TestObjectLiteralMethods:
+ """An object-literal method no named function encloses is a symbol.
+
+ Its calls are keyed to it, not to whatever binding encloses the whole
+ expression, and it is qualified by that binding so same-named methods of
+ two objects in one file keep distinct ids.
+ """
+
+ MIXIN = b"""\
+import * as checks from "./checks";
+export const ZodNumber = $constructor("ZodNumber", (inst, def) => {
+ install(inst, {
+ gt(v, p) { return checks.gtCheck(v, p); },
+ positive(p) { return checks.gtCheck(0, p); },
+ });
+});
+export const ZodBigInt = $constructor("ZodBigInt", (inst, def) => {
+ install(inst, {
+ gt(v, p) { return checks.gtCheck(v, p); },
+ });
+});
+export const api = {
+ get(url) { return fetchIt(url); },
+};
+"""
+
+ def _parse(self, parser: ASTParser, src: bytes, path: str, language: str = "typescript"):
+ return parser.parse_file(_make_file_info(path, language), src)
+
+ def test_mixin_methods_are_symbols_under_their_binding(self, parser: ASTParser) -> None:
+ result = self._parse(parser, self.MIXIN, "src/schemas.ts")
+ ids = {s.id: s for s in result.symbols}
+ for sid in (
+ "src/schemas.ts::ZodNumber::gt",
+ "src/schemas.ts::ZodNumber::positive",
+ "src/schemas.ts::ZodBigInt::gt",
+ "src/schemas.ts::api::get",
+ ):
+ assert sid in ids, sid
+ assert ids[sid].kind == "method"
+
+ def test_calls_inside_are_keyed_to_the_method(self, parser: ASTParser) -> None:
+ result = self._parse(parser, self.MIXIN, "src/schemas.ts")
+ callers = {(c.line, c.target_name): c.caller_symbol_id for c in result.calls}
+ assert callers[(4, "gtCheck")] == "src/schemas.ts::ZodNumber::gt"
+ assert callers[(5, "gtCheck")] == "src/schemas.ts::ZodNumber::positive"
+ assert callers[(10, "gtCheck")] == "src/schemas.ts::ZodBigInt::gt"
+ assert callers[(3, "install")] == "src/schemas.ts::ZodNumber"
+
+ def test_javascript_shares_the_rule(self, parser: ASTParser) -> None:
+ result = self._parse(parser, self.MIXIN, "src/schemas.js", "javascript")
+ ids = {s.id for s in result.symbols}
+ assert "src/schemas.js::ZodNumber::gt" in ids
+ assert "src/schemas.js::ZodBigInt::gt" in ids
+
+ def test_methods_inside_a_named_function_stay_local(self, parser: ASTParser) -> None:
+ src = b"""\
+export function outer() {
+ const helper = () => 1;
+ return { inner() { return helper(); } };
+}
+export const arrow = () => ({ viaArrow() { return 1; } });
+export const table = { handler: () => ({ viaPair() { return 1; } }) };
+export class K {
+ m() { return { deep() { return 1; } }; }
+}
+"""
+ names = {s.name for s in self._parse(parser, src, "src/local.ts").symbols}
+ for hidden in ("helper", "inner", "viaArrow", "viaPair", "deep"):
+ assert hidden not in names, hidden
+ assert {"outer", "arrow", "K", "m"} <= names
+
+ def test_nested_object_is_owned_by_its_property_key(self, parser: ASTParser) -> None:
+ src = b"""\
+export const useStore = defineStore("s", {
+ actions: { inc() { return 1; } },
+ getters: { inc() { return 2; } },
+});
+"""
+ ids = {s.id for s in self._parse(parser, src, "src/store.ts").symbols}
+ assert "src/store.ts::actions::inc" in ids
+ assert "src/store.ts::getters::inc" in ids
+ assert "src/store.ts::inc" not in ids
+
+ def test_no_symbol_without_a_plain_owner_name(self, parser: ASTParser) -> None:
+ src = b"""\
+export const a = f({ "odd-key": { m() { return 1; } } });
+export const { b } = f({ n() { return 2; } });
+"""
+ names = {s.name for s in self._parse(parser, src, "src/owners.ts").symbols}
+ assert "m" not in names
+ assert "n" not in names
+
+ def test_methods_kept_before_keep_their_ids(self, parser: ASTParser) -> None:
+ # No callable encloses these, so they were symbols already: unchanged.
+ src = b"""\
+export default { data() { return {}; }, methods: { inc() { return 1; } } };
+var legacy = { run() { return 1; } };
+"""
+ ids = {s.id for s in self._parse(parser, src, "src/options.ts").symbols}
+ assert {"src/options.ts::data", "src/options.ts::inc", "src/options.ts::run"} <= ids
diff --git a/tests/unit/ingestion/test_object_literal_method_graph.py b/tests/unit/ingestion/test_object_literal_method_graph.py
new file mode 100644
index 000000000..cb55672af
--- /dev/null
+++ b/tests/unit/ingestion/test_object_literal_method_graph.py
@@ -0,0 +1,117 @@
+"""Object-literal methods inside an anonymous callback, end to end.
+
+The parser keeps them as symbols qualified by their owning binding. These
+tests pin that the calls inside them resolve with the method as caller, that
+SFC projection keeps their lines on the original file, and that dead code
+never flags them.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+
+_FILES = {
+ "src/checks.ts": "export function gtCheck(v: number, p: number) { return v > p; }\n",
+ "src/helper.ts": "export function helper() { return 1; }\n",
+ "src/schemas.ts": """\
+import * as checks from "./checks";
+export const ZodNumber = $constructor("ZodNumber", (inst: any) => {
+ install(inst, {
+ gt(v: number, p: number) { return checks.gtCheck(v, p); },
+ });
+});
+export const ZodBigInt = $constructor("ZodBigInt", (inst: any) => {
+ install(inst, {
+ gt(v: number, p: number) { return checks.gtCheck(v, p); },
+ });
+});
+""",
+ "src/C.vue": """\
+<template>
+ <button @click="inc">{{ count }}</button>
+</template>
+
+<script>
+import { helper } from "./helper";
+export const useStore = defineStore("s", {
+ actions: {
+ inc() { return helper(); },
+ },
+});
+export default {
+ data() { return { count: 0 }; },
+ methods: {
+ inc() { return helper(); },
+ },
+};
+</script>
+""",
+ "src/Counter.svelte": """\
+<script lang="ts">
+ import { helper } from "./helper";
+ export const store = createStore({
+ actions: {
+ bump() { return helper(); },
+ },
+ });
+</script>
+
+<button on:click={() => store.actions.bump()}>x</button>
+""",
+}
+
+
+def _build(tmp_path: Path):
+ for rel, text in _FILES.items():
+ path = tmp_path / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+ builder = GraphBuilder(tmp_path)
+ parser = ASTParser()
+ source_map: dict[str, bytes] = {}
+ for fi in FileTraverser(tmp_path).traverse():
+ src = Path(fi.abs_path).read_bytes()
+ builder.add_file(parser.parse_file(fi, src))
+ source_map[fi.path] = src
+ builder.set_source_map(source_map)
+ builder.build()
+ graph = builder.graph()
+ report = DeadCodeAnalyzer(
+ graph, {}, parsed_files=builder._parsed_files, source_map=source_map, repo_root=tmp_path
+ ).analyze({"detect_unused_internals": True})
+ calls = {(u, v) for u, v, d in graph.edges(data=True) if d.get("edge_type") == "calls"}
+ return graph, calls, report
+
+
+def test_mixin_calls_resolve_from_each_method(tmp_path: Path) -> None:
+ graph, calls, _ = _build(tmp_path)
+ assert ("src/schemas.ts::ZodNumber::gt", "src/checks.ts::gtCheck") in calls
+ assert ("src/schemas.ts::ZodBigInt::gt", "src/checks.ts::gtCheck") in calls
+ assert graph.nodes["src/schemas.ts::ZodNumber::gt"]["start_line"] == 4
+ assert graph.nodes["src/schemas.ts::ZodBigInt::gt"]["start_line"] == 9
+
+
+def test_vue_script_keeps_options_ids_and_adds_the_store_action(tmp_path: Path) -> None:
+ graph, calls, _ = _build(tmp_path)
+ # Options API members were symbols already and keep their ids.
+ assert graph.nodes["src/C.vue::inc"]["start_line"] == 15
+ assert graph.nodes["src/C.vue::data"]["start_line"] == 13
+ # The store action is new, on its .vue line, and does not collide.
+ assert graph.nodes["src/C.vue::actions::inc"]["start_line"] == 9
+ assert ("src/C.vue::actions::inc", "src/helper.ts::helper") in calls
+ assert ("src/C.vue::inc", "src/helper.ts::helper") in calls
+
+
+def test_svelte_script_method_lands_on_its_line(tmp_path: Path) -> None:
+ graph, calls, _ = _build(tmp_path)
+ assert graph.nodes["src/Counter.svelte::actions::bump"]["start_line"] == 5
+ assert ("src/Counter.svelte::actions::bump", "src/helper.ts::helper") in calls
+
+
+def test_dead_code_never_flags_the_new_methods(tmp_path: Path) -> None:
+ _, _, report = _build(tmp_path)
+ flagged = {f.symbol_name for f in report.findings if f.symbol_name}
+ assert not flagged & {"gt", "inc", "bump"}