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.

refactor(ingestion): flatten deep nesting in heritage extractors (#526)

Raghav Chamadiya977b6b087e84
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/java.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/java.py
index f30b70c1b..a47392588 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/java.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/java.py
@@ -8,30 +8,32 @@ from ...models import HeritageRelation
from ..helpers import node_text
-def _extract_java_heritage(
+def _superclass(
def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
) -> None:
- """Java: class Foo extends Bar implements IFoo, IBar."""
+ """``class Foo extends Bar``."""
superclass = def_node.child_by_field_name("superclass")
- if superclass:
- parent = node_text(superclass, src).strip()
- parent = parent.removeprefix("extends").strip()
- if parent:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent.split(".")[-1],
- kind="extends",
- line=line,
- )
+ if not superclass:
+ return
+ parent = node_text(superclass, src).strip().removeprefix("extends").strip()
+ if parent:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=parent.split(".")[-1],
+ kind="extends",
+ line=line,
)
+ )
+
- # `sealed class Foo permits A, B {}` — emit a permits edge in BOTH
- # directions so the analyzer treats the sealed hierarchy as a closed
- # set. Parent → child = "extends" (the permits clause is the
- # inverse of the children's own ``extends Foo``), letting the parent
- # file reach every permitted subclass even when no other code references
- # those subclasses directly.
+def _permits(def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]) -> None:
+ """``sealed class Foo permits A, B``: emit a parent -> child ``extends`` edge.
+
+ The permits clause is the inverse of each child's own ``extends Foo``, so
+ emitting it lets the parent file reach every permitted subclass even when
+ no other code references those subclasses directly.
+ """
for child in def_node.children:
if child.type != "permits":
continue
@@ -42,54 +44,62 @@ def _extract_java_heritage(
if type_node.type in (",", "permits"):
continue
permit_name = node_text(type_node, src).strip().split(".")[-1]
- if not permit_name:
- continue
- out.append(
- HeritageRelation(
- child_name=permit_name,
- parent_name=name,
- kind="extends",
- line=line,
+ if permit_name:
+ out.append(
+ HeritageRelation(
+ child_name=permit_name,
+ parent_name=name,
+ kind="extends",
+ line=line,
+ )
)
- )
+
+def _interfaces_node(def_node: Node) -> Node | None:
+ """The interface list: ``interfaces`` field, or ``extends_interfaces`` for interfaces."""
interfaces = def_node.child_by_field_name("interfaces")
- # Java interface declarations use `extends_interfaces` for the parent list.
+ if interfaces is not None:
+ return interfaces
+ for child in def_node.children:
+ if child.type == "extends_interfaces":
+ return child
+ return None
+
+
+def _interfaces(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """``class Foo implements IFoo, IBar`` / ``interface Foo extends IBar``."""
+ interfaces = _interfaces_node(def_node)
if interfaces is None:
- for child in def_node.children:
- if child.type == "extends_interfaces":
- interfaces = child
- break
- if interfaces:
- for child in interfaces.children:
- if child.type in ("implements", "extends", ",", "type_list"):
- if child.type == "type_list":
- for type_node in child.children:
- if type_node.type != ",":
- parent = node_text(type_node, src).strip().split(".")[-1]
- if parent:
- kind = (
- "implements"
- if def_node.type == "class_declaration"
- else "extends"
- )
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind=kind,
- line=line,
- )
- )
- continue
- parent = node_text(child, src).strip().split(".")[-1]
- if parent and parent not in ("implements", "extends"):
- kind = "implements" if def_node.type == "class_declaration" else "extends"
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind=kind,
- line=line,
- )
- )
+ return
+ kind = "implements" if def_node.type == "class_declaration" else "extends"
+ for child in interfaces.children:
+ if child.type in ("implements", "extends", ",", "type_list"):
+ if child.type == "type_list":
+ for type_node in child.children:
+ if type_node.type == ",":
+ continue
+ parent = node_text(type_node, src).strip().split(".")[-1]
+ if parent:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=parent,
+ kind=kind,
+ line=line,
+ )
+ )
+ continue
+ parent = node_text(child, src).strip().split(".")[-1]
+ if parent and parent not in ("implements", "extends"):
+ out.append(HeritageRelation(child_name=name, parent_name=parent, kind=kind, line=line))
+
+
+def _extract_java_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Java: class Foo extends Bar implements IFoo, IBar."""
+ _superclass(def_node, name, line, src, out)
+ _permits(def_node, name, line, src, out)
+ _interfaces(def_node, name, line, src, out)
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/php.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/php.py
index c3f612ba0..a891bd428 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/php.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/php.py
@@ -8,50 +8,57 @@ from ...models import HeritageRelation
from ..helpers import node_text
+def _named_children_text(node: Node, src: str, name: str) -> list[tuple[str, Node]]:
+ """Return ``(text, child)`` for each ``name`` child whose text differs from *name*."""
+ out: list[tuple[str, Node]] = []
+ for sub in node.children:
+ if sub.type == "name":
+ parent = node_text(sub, src).strip()
+ if parent and parent != name:
+ out.append((parent, sub))
+ return out
+
+
+def _base_clause(clause: Node, name: str, line: int, src: str, out: list[HeritageRelation]) -> None:
+ """``class Foo extends Bar``."""
+ for parent, _ in _named_children_text(clause, src, name):
+ out.append(HeritageRelation(child_name=name, parent_name=parent, kind="extends", line=line))
+
+
+def _interface_clause(
+ clause: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """``class Foo implements IFoo, IBar``."""
+ for parent, _ in _named_children_text(clause, src, name):
+ out.append(
+ HeritageRelation(child_name=name, parent_name=parent, kind="implements", line=line)
+ )
+
+
+def _trait_uses(body: Node, name: str, src: str, out: list[HeritageRelation]) -> None:
+ """``use TraitName;`` statements inside the class body."""
+ for stmt in body.children:
+ if stmt.type != "use_declaration":
+ continue
+ for trait_name, _ in _named_children_text(stmt, src, name):
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=trait_name,
+ kind="mixin",
+ line=stmt.start_point[0] + 1,
+ )
+ )
+
+
def _extract_php_heritage(
def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
) -> None:
"""PHP: ``class Foo extends Bar implements IFoo, IBar; use TraitName;``."""
for child in def_node.children:
if child.type == "base_clause":
- for sub in child.children:
- if sub.type == "name":
- parent = node_text(sub, src).strip()
- if parent and parent != name:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind="extends",
- line=line,
- )
- )
+ _base_clause(child, name, line, src, out)
elif child.type == "class_interface_clause":
- for sub in child.children:
- if sub.type == "name":
- parent = node_text(sub, src).strip()
- if parent and parent != name:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind="implements",
- line=line,
- )
- )
+ _interface_clause(child, name, line, src, out)
elif child.type == "declaration_list":
- # use TraitName; inside class body
- for stmt in child.children:
- if stmt.type == "use_declaration":
- for sub in stmt.children:
- if sub.type == "name":
- trait_name = node_text(sub, src).strip()
- if trait_name and trait_name != name:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=trait_name,
- kind="mixin",
- line=stmt.start_point[0] + 1,
- )
- )
+ _trait_uses(child, name, src, out)
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/rust.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/rust.py
index 2a17f5a49..48ebaa8d0 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/rust.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/rust.py
@@ -7,94 +7,141 @@ from tree_sitter import Node
from ...models import HeritageRelation
from ..helpers import node_text
+# Auto-derived/auto-implemented marker traits carry no useful heritage signal.
+_SKIP_BOUNDS = ("Sized", "Send", "Sync", "Unpin")
-def _extract_rust_heritage(
+
+def _strip_generics(text: str) -> str:
+ """``Sides<T>`` -> ``Sides``; also strips a leading path (``a::B`` -> ``B``)."""
+ name = text.strip().rsplit("::", 1)[-1]
+ if "<" in name:
+ name = name[: name.index("<")]
+ return name
+
+
+def _impl_relation(def_node: Node, line: int, src: str, out: list[HeritageRelation]) -> None:
+ """``impl Trait for Type`` -> ``Type`` trait_impl ``Trait``."""
+ trait_node = def_node.child_by_field_name("trait")
+ type_node = def_node.child_by_field_name("type")
+ if not (trait_node and type_node):
+ return
+ trait_name = _strip_generics(node_text(trait_node, src))
+ type_name = _strip_generics(node_text(type_node, src))
+ if trait_name and type_name:
+ out.append(
+ HeritageRelation(
+ child_name=type_name,
+ parent_name=trait_name,
+ kind="trait_impl",
+ line=line,
+ )
+ )
+
+
+def _trait_supertraits(
def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
) -> None:
- """Rust: impl Trait for Type, trait Foo: Bar + Baz, #[derive(Trait)]."""
- if def_node.type == "impl_item":
- trait_node = def_node.child_by_field_name("trait")
- type_node = def_node.child_by_field_name("type")
- if trait_node and type_node:
- trait_name = node_text(trait_node, src).strip().rsplit("::", 1)[-1]
- if "<" in trait_name:
- trait_name = trait_name[:trait_name.index("<")]
- type_name = node_text(type_node, src).strip()
- # Strip generic parameters: "Sides<T>" → "Sides"
- if "<" in type_name:
- type_name = type_name[:type_name.index("<")]
- if trait_name and type_name:
- out.append(
- HeritageRelation(
- child_name=type_name,
- parent_name=trait_name,
- kind="trait_impl",
- line=line,
- )
+ """``trait Foo: Bar + Baz`` -> ``Foo`` extends ``Bar``, ``Baz``."""
+ bounds = def_node.child_by_field_name("bounds")
+ if not bounds:
+ return
+ for child in bounds.children:
+ if child.type in ("+", ":"):
+ continue
+ parent = node_text(child, src).strip().rsplit("::", 1)[-1]
+ if parent:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=parent,
+ kind="extends",
+ line=line,
)
+ )
- elif def_node.type == "trait_item":
- bounds = def_node.child_by_field_name("bounds")
- if bounds:
- for child in bounds.children:
- if child.type in ("+", ":"):
+
+def _where_clause_bounds(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """``impl<T> Foo for T where T: Debug + Clone`` -> Foo trait_bound Debug, Clone."""
+ for child in def_node.children:
+ if child.type != "where_clause":
+ continue
+ for predicate in child.children:
+ if predicate.type != "where_predicate":
+ continue
+ bounds = predicate.child_by_field_name("bounds")
+ if not bounds:
+ continue
+ for bound_child in bounds.children:
+ if bound_child.type in ("+", ":"):
continue
- parent = node_text(child, src).strip().rsplit("::", 1)[-1]
- if parent:
+ bound_name = _strip_generics(node_text(bound_child, src))
+ if bound_name and bound_name not in _SKIP_BOUNDS:
out.append(
HeritageRelation(
child_name=name,
- parent_name=parent,
- kind="extends",
+ parent_name=bound_name,
+ kind="trait_bound",
line=line,
)
)
- # Extract trait bounds from where clauses on any item type.
- # `impl<T> Foo for T where T: Debug + Clone` → Foo depends on Debug, Clone
- if def_node.type in ("impl_item", "function_item", "struct_item", "enum_item", "trait_item"):
- for child in def_node.children:
- if child.type == "where_clause":
- for predicate in child.children:
- if predicate.type == "where_predicate":
- bounds = predicate.child_by_field_name("bounds")
- if bounds:
- for bound_child in bounds.children:
- if bound_child.type in ("+", ":"):
- continue
- bound_name = node_text(bound_child, src).strip().rsplit("::", 1)[-1]
- if "<" in bound_name:
- bound_name = bound_name[:bound_name.index("<")]
- if bound_name and bound_name not in ("Sized", "Send", "Sync", "Unpin"):
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=bound_name,
- kind="trait_bound",
- line=line,
- )
- )
+
+def _derive_traits(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """``#[derive(Trait1, Trait2)]`` on the preceding attribute siblings."""
+ prev = def_node.prev_named_sibling
+ while prev is not None and prev.type == "attribute_item":
+ if "derive(" in node_text(prev, src):
+ for trait_name in _derive_idents(prev, src):
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=trait_name,
+ kind="derive",
+ line=line,
+ )
+ )
+ prev = prev.prev_named_sibling
+
+
+def _derive_idents(attr_node: Node, src: str) -> list[str]:
+ """Yield the trait identifiers inside a ``#[derive(...)]`` attribute."""
+ idents: list[str] = []
+ for child in attr_node.children:
+ if child.type != "attribute":
+ continue
+ for sub in child.children:
+ if sub.type != "token_tree":
+ continue
+ for tok in sub.children:
+ if tok.type == "identifier":
+ trait_name = node_text(tok, src).strip()
+ if trait_name:
+ idents.append(trait_name)
+ return idents
+
+
+def _extract_rust_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Rust: impl Trait for Type, trait Foo: Bar + Baz, #[derive(Trait)]."""
+ if def_node.type == "impl_item":
+ _impl_relation(def_node, line, src, out)
+ elif def_node.type == "trait_item":
+ _trait_supertraits(def_node, name, line, src, out)
+
+ # Trait bounds from where clauses can appear on any item type.
+ if def_node.type in (
+ "impl_item",
+ "function_item",
+ "struct_item",
+ "enum_item",
+ "trait_item",
+ ):
+ _where_clause_bounds(def_node, name, line, src, out)
if def_node.type in ("struct_item", "enum_item"):
- # Walk preceding siblings for #[derive(Trait1, Trait2)]
- prev = def_node.prev_named_sibling
- while prev is not None and prev.type == "attribute_item":
- attr_text = node_text(prev, src).strip()
- if "derive(" in attr_text:
- for child in prev.children:
- if child.type == "attribute":
- for sub in child.children:
- if sub.type == "token_tree":
- for tok in sub.children:
- if tok.type == "identifier":
- trait_name = node_text(tok, src).strip()
- if trait_name:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=trait_name,
- kind="derive",
- line=line,
- )
- )
- prev = prev.prev_named_sibling
+ _derive_traits(def_node, name, line, src, out)
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/swift.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/swift.py
index 3ae4d8dd1..a5843bfcb 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/swift.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/swift.py
@@ -8,23 +8,34 @@ from ...models import HeritageRelation
from ..helpers import node_text
+def _user_type_identifiers(spec: Node, src: str) -> list[str]:
+ """Yield ``type_identifier`` texts nested under a ``user_type`` in *spec*."""
+ names: list[str] = []
+ for type_child in spec.children:
+ if type_child.type != "user_type":
+ continue
+ for id_node in type_child.children:
+ if id_node.type == "type_identifier":
+ parent = node_text(id_node, src).strip()
+ if parent:
+ names.append(parent)
+ return names
+
+
def _extract_swift_heritage(
def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
) -> None:
"""Swift: ``class Foo: Bar, Protocol1`` — inheritance via ``:`` separator."""
for child in def_node.children:
- if child.type == "inheritance_specifier":
- for type_child in child.children:
- if type_child.type == "user_type":
- for id_node in type_child.children:
- if id_node.type == "type_identifier":
- parent = node_text(id_node, src).strip()
- if parent and parent != name:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind="extends",
- line=line,
- )
- )
+ if child.type != "inheritance_specifier":
+ continue
+ for parent in _user_type_identifiers(child, src):
+ if parent != name:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=parent,
+ kind="extends",
+ line=line,
+ )
+ )
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/ts_js.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/ts_js.py
index 13de8292c..b8fa8b16d 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/ts_js.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/ts_js.py
@@ -8,53 +8,42 @@ from ...models import HeritageRelation
from ..helpers import node_text
+def _type_clause(
+ clause: Node,
+ name: str,
+ line: int,
+ src: str,
+ kind: str,
+ keyword: str,
+ out: list[HeritageRelation],
+) -> None:
+ """Emit a *kind* relation for each type listed in an extends/implements clause."""
+ for type_node in clause.children:
+ if type_node.type in (keyword, ","):
+ continue
+ parent = node_text(type_node, src).strip()
+ if parent:
+ out.append(HeritageRelation(child_name=name, parent_name=parent, kind=kind, line=line))
+
+
+def _class_heritage(
+ heritage: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """``class Foo extends Bar implements IFoo, IBar``."""
+ for clause in heritage.children:
+ if clause.type == "extends_clause":
+ _type_clause(clause, name, line, src, "extends", "extends", out)
+ elif clause.type == "implements_clause":
+ _type_clause(clause, name, line, src, "implements", "implements", out)
+
+
def _extract_ts_js_heritage(
def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
) -> None:
"""TypeScript/JavaScript: class Foo extends Bar implements IFoo, IBar."""
for child in def_node.children:
if child.type == "class_heritage":
- for clause in child.children:
- if clause.type == "extends_clause":
- for type_node in clause.children:
- if type_node.type in ("extends", ","):
- continue
- parent = node_text(type_node, src).strip()
- if parent:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind="extends",
- line=line,
- )
- )
- elif clause.type == "implements_clause":
- for type_node in clause.children:
- if type_node.type in ("implements", ","):
- continue
- parent = node_text(type_node, src).strip()
- if parent:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind="implements",
- line=line,
- )
- )
+ _class_heritage(child, name, line, src, out)
# interface extends: interface Foo extends Bar
- if child.type == "extends_type_clause":
- for type_node in child.children:
- if type_node.type in ("extends", ","):
- continue
- parent = node_text(type_node, src).strip()
- if parent:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind="extends",
- line=line,
- )
- )
+ elif child.type == "extends_type_clause":
+ _type_clause(child, name, line, src, "extends", "extends", out)