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(graph): give every language one answer for a type's bare name (#1634)

Raghav Chamadiyac9cd46c14536
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py
index fc2534597..95b5143bc 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py
@@ -21,6 +21,7 @@ from __future__ import annotations
import re
from pathlib import Path
+from ..type_names import bare_type_name
from .base import DynamicEdge, DynamicHintExtractor
_SKIP_DIRS = {"bin", "obj", ".vs", "node_modules", ".git", "packages"}
@@ -127,11 +128,8 @@ class DotNetDynamicHints(DynamicHintExtractor):
if rel not in bucket:
bucket.append(rel)
- def _short(name: str) -> str:
- return name.rsplit(".", 1)[-1]
-
def _files_for(name: str) -> list[str]:
- return type_to_files.get(_short(name), [])
+ return type_to_files.get(bare_type_name(name), [])
for cs, text in cs_files:
try:
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/go.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/go.py
index 64a5bd94a..8fc1eb064 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/go.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/go.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import re
from pathlib import Path
+from ..type_names import bare_type_name
from .base import DynamicEdge, DynamicHintExtractor
_SKIP_DIRS = {"vendor", "node_modules", ".git", "bin"}
@@ -64,7 +65,7 @@ class GoDynamicHints(DynamicHintExtractor):
# Drop any package qualifier (``pkg.Foo`` → ``Foo``); reflect
# arguments are values/types whose defining file we look up by
# bare name.
- bare = match.group(1).split(".")[-1]
+ bare = bare_type_name(match.group(1))
target = type_to_file.get(bare) or func_to_file.get(bare)
if target and target != rel:
edges.append(DynamicEdge(
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/jvm.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/jvm.py
index e05084a34..c504747c5 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/jvm.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/jvm.py
@@ -26,6 +26,7 @@ from __future__ import annotations
import re
from pathlib import Path
+from ..type_names import bare_type_name
from .base import DynamicEdge, DynamicHintExtractor
_SKIP_DIRS = {"build", "target", "out", "node_modules", ".git", ".gradle", ".idea"}
@@ -119,7 +120,7 @@ class JvmDynamicHints(DynamicHintExtractor):
for match in _CLASS_FORNAME_RE.finditer(text):
fqn = match.group(1)
- target = fqn_to_file.get(fqn) or type_to_file.get(fqn.rsplit(".", 1)[-1])
+ target = fqn_to_file.get(fqn) or type_to_file.get(bare_type_name(fqn))
_emit(rel, target, "class_forname")
for match in _MOCKITO_RE.finditer(text):
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/scala.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/scala.py
index 4ca7544c7..8576716ff 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/scala.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/scala.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import re
from pathlib import Path
+from ..type_names import bare_type_name
from .base import DynamicEdge, DynamicHintExtractor
_SKIP_DIRS = {"target", "project", ".bloop", ".metals", "node_modules", ".git"}
@@ -46,9 +47,6 @@ class ScalaDynamicHints(DynamicHintExtractor):
for match in _TYPE_DECL_RE.finditer(text):
type_to_file.setdefault(match.group(1), rel)
- def _short(name: str) -> str:
- return name.rsplit(".", 1)[-1]
-
for src, text in sources:
try:
rel = src.resolve().relative_to(repo_root.resolve()).as_posix()
@@ -56,7 +54,7 @@ class ScalaDynamicHints(DynamicHintExtractor):
continue
for match in _CLASS_FORNAME_RE.finditer(text):
- target = type_to_file.get(_short(match.group(1)))
+ target = type_to_file.get(bare_type_name(match.group(1)))
if target and target != rel:
edges.append(DynamicEdge(
source=rel, target=target,
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/_types.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/_types.py
new file mode 100644
index 000000000..57845e757
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/_types.py
@@ -0,0 +1,60 @@
+"""Reading a heritage clause's parent types out of the AST.
+
+Grammars disagree about whether a qualified or generic parent is one node or
+several siblings: Dart spells ``extends ns.Qual`` as three flat children of the
+``superclass`` node, Scala wraps the same thing in one ``stable_type_identifier``.
+Picking identifier children individually therefore emits one edge per segment
+in the flat grammars, and picking whole-node text emits the qualifier in the
+wrapped ones.
+
+Joining the children between delimiters and normalising the run once handles
+both, and leaves the bare-name question with its one owner.
+"""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...type_names import bare_type_name
+from ..helpers import node_text
+
+
+def type_runs(
+ node: Node,
+ src: str,
+ separators: frozenset[str],
+ skip: frozenset[str] = frozenset(),
+) -> list[tuple[str, str]]:
+ """Return ``(separator, bare_name)`` for each type listed under *node*.
+
+ Children are joined into runs delimited by *separators* and by ``,``, and
+ each run is reduced to a bare name. The separator is the keyword that
+ introduced the run (``extends``, ``with``, ``implements``), so a caller can
+ classify the relation without re-walking. Nodes in *skip* are dropped from
+ the run — a Scala superclass constructor's ``arguments`` is not part of its
+ name.
+ """
+ runs: list[tuple[str, str]] = []
+ parts: list[str] = []
+ separator = ""
+
+ def flush() -> None:
+ if parts:
+ bare = bare_type_name("".join(parts))
+ if bare:
+ runs.append((separator, bare))
+ parts.clear()
+
+ for child in node.children:
+ if child.type in separators:
+ flush()
+ separator = child.type
+ continue
+ if child.type == ",":
+ flush()
+ continue
+ if child.type in skip:
+ continue
+ parts.append(node_text(child, src))
+ flush()
+ return runs
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/cpp.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/cpp.py
index 8d399ad5c..acceb34d0 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/cpp.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/cpp.py
@@ -17,6 +17,7 @@ import re
from tree_sitter import Node
from ...models import HeritageRelation
+from ...type_names import bare_type_name
from ..helpers import node_text
# ``IFoo`` / ``IShellExtInit`` — COM / Microsoft interface naming
@@ -54,7 +55,7 @@ def _extract_cpp_heritage(
# ``: boost::noncopyable`` and similar mixins — keep the
# bare name; downstream callers don't currently distinguish
# mixin bases from real ones.
- bare = text.split("::")[-1].strip()
+ bare = bare_type_name(text)
if not bare:
continue
out.append(
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/csharp.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/csharp.py
index f75eef4cc..0b245f28a 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/csharp.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/csharp.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from tree_sitter import Node
from ...models import HeritageRelation
+from ...type_names import bare_type_name, strip_call_arguments
from ..helpers import node_text
@@ -42,8 +43,7 @@ def _extract_csharp_heritage(
if base.type == "argument_list":
continue
text = node_text(base, src).strip()
- bare = text.split("<")[0].split("(")[0].strip()
- bare = bare.rsplit(".", 1)[-1].strip()
+ bare = bare_type_name(strip_call_arguments(text))
if not bare or bare == name:
continue
looks_interface = bare.startswith("I") and len(bare) > 1 and bare[1].isupper()
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/dart.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/dart.py
index 9881988ee..c0ca0373a 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/dart.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/dart.py
@@ -12,7 +12,15 @@ from __future__ import annotations
from tree_sitter import Node
from ...models import HeritageRelation
-from ..helpers import node_text
+from ._types import type_runs
+
+_SUPERCLASS_SEPARATORS = frozenset({"extends"})
+_MIXIN_SEPARATORS = frozenset({"with"})
+_INTERFACE_SEPARATORS = frozenset({"implements"})
+# The mixin list is a child of ``superclass`` and is read separately.
+_SUPERCLASS_SKIP = frozenset({"mixins"})
+_ON_SEPARATORS = frozenset({"on"})
+_MIXIN_DECL_SKIP = frozenset({"class_body"})
def _append(out: list[HeritageRelation], name: str, parent: str, kind: str, line: int) -> None:
@@ -33,20 +41,23 @@ def _extract_dart_heritage(
if def_node.type == "class_definition":
for child in def_node.children:
if child.type == "superclass":
+ for _, parent in type_runs(
+ child, src, _SUPERCLASS_SEPARATORS, _SUPERCLASS_SKIP
+ ):
+ _append(out, name, parent, "extends", line)
for sub in child.children:
- if sub.type == "type_identifier":
- _append(out, name, node_text(sub, src).strip(), "extends", line)
- elif sub.type == "mixins":
- for mixin in sub.children:
- if mixin.type == "type_identifier":
- _append(out, name, node_text(mixin, src).strip(), "mixin", line)
+ if sub.type == "mixins":
+ for _, mixin in type_runs(sub, src, _MIXIN_SEPARATORS):
+ _append(out, name, mixin, "mixin", line)
elif child.type == "interfaces":
- for sub in child.children:
- if sub.type == "type_identifier":
- _append(out, name, node_text(sub, src).strip(), "implements", line)
+ for _, parent in type_runs(child, src, _INTERFACE_SEPARATORS):
+ _append(out, name, parent, "implements", line)
elif def_node.type == "mixin_declaration":
- # ``mixin M on Base`` — the ``on`` constraint types are direct
- # type_identifier children of the declaration.
- for child in def_node.children:
- if child.type == "type_identifier":
- _append(out, name, node_text(child, src).strip(), "extends", line)
+ # ``mixin M on Base`` — the constraints are flat siblings of the
+ # declaration, sharing it with the mixin's own name and body, so only
+ # the runs the ``on`` keyword introduces are constraints.
+ for separator, parent in type_runs(
+ def_node, src, _ON_SEPARATORS, _MIXIN_DECL_SKIP
+ ):
+ if separator == "on":
+ _append(out, name, parent, "extends", line)
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/go.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/go.py
index 98b2e2b6a..9eb9459da 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/go.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/go.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from tree_sitter import Node
from ...models import HeritageRelation
+from ...type_names import bare_type_name
from ..helpers import node_text
@@ -32,7 +33,7 @@ def _extract_go_heritage(
type_child = field_decl.child_by_field_name("type")
if name_node is None and type_child is not None:
parent = node_text(type_child, src).strip().lstrip("*")
- bare = parent.split(".")[-1]
+ bare = bare_type_name(parent)
if bare:
out.append(
HeritageRelation(
@@ -48,8 +49,7 @@ def _extract_go_heritage(
if child.type in ("{", "}", "\n"):
continue
if child.type in ("type_identifier", "qualified_type"):
- parent = node_text(child, src).strip()
- bare = parent.split(".")[-1]
+ bare = bare_type_name(node_text(child, src))
if bare:
out.append(
HeritageRelation(
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 a47392588..8a147d519 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/java.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/java.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from tree_sitter import Node
from ...models import HeritageRelation
+from ...type_names import bare_type_name
from ..helpers import node_text
@@ -15,12 +16,12 @@ def _superclass(
superclass = def_node.child_by_field_name("superclass")
if not superclass:
return
- parent = node_text(superclass, src).strip().removeprefix("extends").strip()
+ parent = bare_type_name(node_text(superclass, src).strip().removeprefix("extends"))
if parent:
out.append(
HeritageRelation(
child_name=name,
- parent_name=parent.split(".")[-1],
+ parent_name=parent,
kind="extends",
line=line,
)
@@ -43,7 +44,7 @@ def _permits(def_node: Node, name: str, line: int, src: str, out: list[HeritageR
for type_node in sub.children:
if type_node.type in (",", "permits"):
continue
- permit_name = node_text(type_node, src).strip().split(".")[-1]
+ permit_name = bare_type_name(node_text(type_node, src))
if permit_name:
out.append(
HeritageRelation(
@@ -80,7 +81,7 @@ def _interfaces(
for type_node in child.children:
if type_node.type == ",":
continue
- parent = node_text(type_node, src).strip().split(".")[-1]
+ parent = bare_type_name(node_text(type_node, src))
if parent:
out.append(
HeritageRelation(
@@ -91,7 +92,7 @@ def _interfaces(
)
)
continue
- parent = node_text(child, src).strip().split(".")[-1]
+ parent = bare_type_name(node_text(child, src))
if parent and parent not in ("implements", "extends"):
out.append(HeritageRelation(child_name=name, parent_name=parent, kind=kind, line=line))
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/kotlin.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/kotlin.py
index 05ac5b140..8ee28f549 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/kotlin.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/kotlin.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from tree_sitter import Node
from ...models import HeritageRelation
+from ...type_names import bare_type_name, strip_call_arguments
from ..helpers import node_text
@@ -16,7 +17,7 @@ def _extract_kotlin_heritage(
if child.type == "delegation_specifier":
for delegate in child.children:
text = node_text(delegate, src).strip()
- bare = text.split("(")[0].split(".")[-1].strip()
+ bare = bare_type_name(strip_call_arguments(text))
if bare and bare != name:
out.append(
HeritageRelation(
@@ -31,7 +32,7 @@ def _extract_kotlin_heritage(
if delegate.type in (":", ","):
continue
text = node_text(delegate, src).strip()
- bare = text.split("(")[0].split(".")[-1].strip()
+ bare = bare_type_name(strip_call_arguments(text))
if bare and bare != name:
out.append(
HeritageRelation(
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/pascal.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/pascal.py
index b8d137e58..df1489056 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/pascal.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/pascal.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from tree_sitter import Node
from ...models import HeritageRelation
+from ...type_names import bare_type_name
from ..helpers import node_text
_CLASS_LIKE_KINDS = {"declClass", "declIntf", "declHelper"}
@@ -37,7 +38,7 @@ def _extract_pascal_heritage(
return
parent_nodes = type_node.children_by_field_name("parent")
- parents = [node_text(p, src).strip() for p in parent_nodes if p.type == "typeref"]
+ parents = [bare_type_name(node_text(p, src)) for p in parent_nodes if p.type == "typeref"]
parents = [p for p in parents if p and p != name]
for i, parent in enumerate(parents):
@@ -59,7 +60,7 @@ def _extract_pascal_heritage(
parent_typeref_ids = {p.id for p in parent_nodes}
for child in type_node.named_children:
if child.type == "typeref" and child.id not in parent_typeref_ids:
- extended = node_text(child, src).strip()
+ extended = bare_type_name(node_text(child, src))
if extended and extended != name:
out.append(
HeritageRelation(
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 a891bd428..1b4e22517 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/php.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/php.py
@@ -5,15 +5,21 @@ from __future__ import annotations
from tree_sitter import Node
from ...models import HeritageRelation
+from ...type_names import bare_type_name
from ..helpers import node_text
+# A namespaced reference (``\Ns\Qual``) is a ``qualified_name``, not a ``name``,
+# so accepting only the latter dropped every namespaced parent, interface and
+# trait outright.
+_NAME_NODES = frozenset({"name", "qualified_name"})
+
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*."""
+ """Return ``(bare name, child)`` for each named child differing from *name*."""
out: list[tuple[str, Node]] = []
for sub in node.children:
- if sub.type == "name":
- parent = node_text(sub, src).strip()
+ if sub.type in _NAME_NODES:
+ parent = bare_type_name(node_text(sub, src))
if parent and parent != name:
out.append((parent, sub))
return out
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/python.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/python.py
index 43f3caf0a..68d3c8b65 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/python.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/python.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from tree_sitter import Node
from ...models import HeritageRelation
+from ...type_names import bare_type_name
from ..helpers import node_text
@@ -26,9 +27,8 @@ def _extract_python_heritage(
continue
if child.type == "keyword_argument":
continue
- parent = node_text(child, src).strip()
- if parent:
- bare = parent.split(".")[-1]
+ bare = bare_type_name(node_text(child, src))
+ if bare:
out.append(
HeritageRelation(child_name=name, parent_name=bare, kind="extends", line=line)
)
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/ruby.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/ruby.py
index 709ff680c..8e239812f 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/ruby.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/ruby.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from tree_sitter import Node
from ...models import HeritageRelation
+from ...type_names import bare_type_name
from ..helpers import node_text
_MIXIN_METHODS = {"include", "extend", "prepend"}
@@ -18,7 +19,7 @@ def _extract_ruby_heritage(
if superclass:
parent = node_text(superclass, src).strip()
parent = parent.removeprefix("<").strip()
- bare = parent.split("::")[-1]
+ bare = bare_type_name(parent)
if bare:
out.append(
HeritageRelation(
@@ -55,7 +56,7 @@ def _extract_ruby_heritage(
continue
for arg in args.children:
if arg.type == "constant":
- mixin_name = node_text(arg, src).strip().split("::")[-1]
+ mixin_name = bare_type_name(node_text(arg, src))
if mixin_name:
out.append(
HeritageRelation(
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 48ebaa8d0..1512ba3b7 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/rust.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/rust.py
@@ -5,28 +5,21 @@ from __future__ import annotations
from tree_sitter import Node
from ...models import HeritageRelation
+from ...type_names import bare_type_name
from ..helpers import node_text
# Auto-derived/auto-implemented marker traits carry no useful heritage signal.
_SKIP_BOUNDS = ("Sized", "Send", "Sync", "Unpin")
-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))
+ trait_name = bare_type_name(node_text(trait_node, src))
+ type_name = bare_type_name(node_text(type_node, src))
if trait_name and type_name:
out.append(
HeritageRelation(
@@ -48,7 +41,7 @@ def _trait_supertraits(
for child in bounds.children:
if child.type in ("+", ":"):
continue
- parent = node_text(child, src).strip().rsplit("::", 1)[-1]
+ parent = bare_type_name(node_text(child, src))
if parent:
out.append(
HeritageRelation(
@@ -76,7 +69,7 @@ def _where_clause_bounds(
for bound_child in bounds.children:
if bound_child.type in ("+", ":"):
continue
- bound_name = _strip_generics(node_text(bound_child, src))
+ bound_name = bare_type_name(node_text(bound_child, src))
if bound_name and bound_name not in _SKIP_BOUNDS:
out.append(
HeritageRelation(
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/scala.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/scala.py
index febd22647..c7faadca3 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/scala.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/scala.py
@@ -5,7 +5,12 @@ from __future__ import annotations
from tree_sitter import Node
from ...models import HeritageRelation
-from ..helpers import node_text
+from ._types import type_runs
+
+# A superclass constructor call sits inside the extends clause but is not part
+# of the parent's name.
+_SKIP = frozenset({"arguments"})
+_SEPARATORS = frozenset({"extends", "with"})
def _extract_scala_heritage(
@@ -13,23 +18,16 @@ def _extract_scala_heritage(
) -> None:
"""Scala: ``class Foo extends Bar with Trait1 with Trait2``."""
for child in def_node.children:
- if child.type == "extends_clause":
- saw_with = False
- for sub in child.children:
- if sub.type == "extends":
- continue
- if sub.type == "with":
- saw_with = True
- continue
- if sub.type == "type_identifier":
- parent = node_text(sub, src).strip()
- if parent and parent != name:
- kind = "implements" if saw_with else "extends"
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind=kind,
- line=line,
- )
- )
+ if child.type != "extends_clause":
+ continue
+ for separator, parent in type_runs(child, src, _SEPARATORS, _SKIP):
+ if parent == name:
+ continue
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=parent,
+ kind="implements" if separator == "with" else "extends",
+ line=line,
+ )
+ )
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 a5843bfcb..26ce52616 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/swift.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/swift.py
@@ -5,20 +5,24 @@ from __future__ import annotations
from tree_sitter import Node
from ...models import HeritageRelation
+from ...type_names import bare_type_name
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*."""
+ """Yield the bare name of each ``user_type`` in *spec*.
+
+ A qualified conformance is several ``type_identifier`` children of one
+ ``user_type``, so the node's whole text is normalised once — picking the
+ children individually names the qualifier as a parent in its own right.
+ """
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)
+ parent = bare_type_name(node_text(type_child, src))
+ if parent:
+ names.append(parent)
return names
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 b8fa8b16d..20f48ef67 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
@@ -5,6 +5,7 @@ from __future__ import annotations
from tree_sitter import Node
from ...models import HeritageRelation
+from ...type_names import bare_type_name
from ..helpers import node_text
@@ -21,7 +22,7 @@ def _type_clause(
for type_node in clause.children:
if type_node.type in (keyword, ","):
continue
- parent = node_text(type_node, src).strip()
+ parent = bare_type_name(node_text(type_node, src))
if parent:
out.append(HeritageRelation(child_name=name, parent_name=parent, kind=kind, line=line))
diff --git a/packages/core/src/repowise/core/ingestion/language_data.py b/packages/core/src/repowise/core/ingestion/language_data.py
index 986994412..f8f3958a6 100644
--- a/packages/core/src/repowise/core/ingestion/language_data.py
+++ b/packages/core/src/repowise/core/ingestion/language_data.py
@@ -47,3 +47,9 @@ def get_builtin_parents(language: str) -> frozenset[str]:
"""Return the builtin parent type names for a language."""
spec = REGISTRY.get(language)
return spec.builtin_parents if spec else frozenset()
+
+
+def get_builtin_types(language: str) -> frozenset[str]:
+ """Return the type names that never resolve to a repo-declared symbol."""
+ spec = REGISTRY.get(language)
+ return spec.builtin_types if spec else frozenset()
diff --git a/packages/core/src/repowise/core/ingestion/languages/csharp_member_reads.py b/packages/core/src/repowise/core/ingestion/languages/csharp_member_reads.py
index 177f3f31b..3744e6bde 100644
--- a/packages/core/src/repowise/core/ingestion/languages/csharp_member_reads.py
+++ b/packages/core/src/repowise/core/ingestion/languages/csharp_member_reads.py
@@ -41,6 +41,8 @@ import re
from pathlib import Path
from typing import TYPE_CHECKING, Any
+from ..type_names import bare_type_name
+
if TYPE_CHECKING:
import networkx as nx
@@ -74,12 +76,6 @@ _PRIMARY_TYPE_RE = re.compile(
_READS_CONFIDENCE = 0.6
-def _head_type(raw: str) -> str:
- """Strip generic parameters / namespace prefix to a bare identifier."""
- head = raw.split("<", 1)[0]
- return head.rsplit(".", 1)[-1]
-
-
def resolve_csharp_member_reads(
graph: nx.DiGraph,
cs_texts: dict[str, str],
@@ -108,7 +104,7 @@ def resolve_csharp_member_reads(
type_name = m.group("type2") or m.group("type1")
if not type_name:
continue
- local_type[m.group("name")] = _head_type(type_name)
+ local_type[m.group("name")] = bare_type_name(type_name)
primary_match = _PRIMARY_TYPE_RE.search(text)
primary_type = primary_match.group("name") if primary_match else None
diff --git a/packages/core/src/repowise/core/ingestion/languages/spec.py b/packages/core/src/repowise/core/ingestion/languages/spec.py
index 06c28fafe..29fce0596 100644
--- a/packages/core/src/repowise/core/ingestion/languages/spec.py
+++ b/packages/core/src/repowise/core/ingestion/languages/spec.py
@@ -141,6 +141,12 @@ class LanguageSpec:
# -- Builtins --------------------------------------------------------
builtin_calls: frozenset[str] = field(default_factory=frozenset)
builtin_parents: frozenset[str] = field(default_factory=frozenset)
+ # Type names that never resolve to a symbol this repo declares, so a
+ # type-use lookup for one is waste. Distinct from ``builtin_parents``,
+ # which answers the narrower question of what may sit in an extends
+ # clause; a type may be ubiquitous in parameter position without ever
+ # being inherited from.
+ builtin_types: frozenset[str] = field(default_factory=frozenset)
# -- Display ---------------------------------------------------------
color_hex: str = "#8b5cf6" # fallback purple ("other")
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/c.py b/packages/core/src/repowise/core/ingestion/languages/specs/c.py
index 6b3bef9a7..bd1329c69 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/c.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/c.py
@@ -2,6 +2,27 @@
from ..spec import LanguageSpec
+#: Predeclared / standard-library scalar types that never resolve to a
+#: user-defined struct, so they're dropped before the resolver lookup.
+#: ``primitive_type`` / ``sized_type_specifier`` nodes are filtered
+#: structurally in the extractor; this set catches the ``<stdint.h>`` /
+#: ``<stddef.h>`` typedefs that the grammar surfaces as plain
+#: ``type_identifier`` nodes.
+#:
+#: Exported because cpp shares the C extractor and grammar, so it needs the
+#: same set.
+BUILTIN_TYPES: frozenset[str] = frozenset(
+ {
+ "void", "char", "short", "int", "long", "float", "double",
+ "signed", "unsigned", "bool", "_Bool", "_Complex",
+ "size_t", "ssize_t", "rsize_t", "ptrdiff_t", "intptr_t", "uintptr_t",
+ "int8_t", "int16_t", "int32_t", "int64_t",
+ "uint8_t", "uint16_t", "uint32_t", "uint64_t",
+ "intmax_t", "uintmax_t", "wchar_t", "wint_t", "char16_t", "char32_t",
+ "va_list", "FILE",
+ }
+)
+
SPEC = LanguageSpec(
tag="c",
display_name="C",
@@ -46,5 +67,6 @@ SPEC = LanguageSpec(
"exit",
}
),
+ builtin_types=BUILTIN_TYPES,
color_hex="#555555",
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/cpp.py b/packages/core/src/repowise/core/ingestion/languages/specs/cpp.py
index fae625c47..8992fe39a 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/cpp.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/cpp.py
@@ -1,6 +1,7 @@
"""LanguageSpec for cpp (extracted from the registry data table)."""
from ..spec import LanguageSpec
+from .c import BUILTIN_TYPES as _C_BUILTIN_TYPES
#: Include fragments: C++ source that is ``#include``d into a translation unit
#: rather than compiled as one of its own. The convention carries inline and
@@ -79,5 +80,7 @@ SPEC = LanguageSpec(
"weak_ptr",
}
),
+ # Same C extractor and grammar as c.py, so the same builtin set applies.
+ builtin_types=_C_BUILTIN_TYPES,
color_hex="#F34B7D",
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/csharp.py b/packages/core/src/repowise/core/ingestion/languages/specs/csharp.py
index 02d47030a..ec8e402e4 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/csharp.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/csharp.py
@@ -96,5 +96,48 @@ SPEC = LanguageSpec(
"IEquatable",
}
),
+ # Type expressions that never resolve to a user-defined .NET type. Skipping
+ # these avoids polluting the resolver with hopeless lookups. Generic args
+ # inside `IList<T>` are stripped before this check is applied.
+ builtin_types=frozenset(
+ {
+ "void",
+ "bool",
+ "byte",
+ "sbyte",
+ "char",
+ "short",
+ "ushort",
+ "int",
+ "uint",
+ "long",
+ "ulong",
+ "float",
+ "double",
+ "decimal",
+ "string",
+ "object",
+ "nint",
+ "nuint",
+ "dynamic",
+ "var",
+ # Frequently appearing BCL types that are always external — listing
+ # them here is purely a performance optimisation (one dict miss
+ # avoided per occurrence).
+ "Task",
+ "ValueTask",
+ "CancellationToken",
+ "Action",
+ "Func",
+ "Type",
+ "Exception",
+ "DateTime",
+ "DateTimeOffset",
+ "TimeSpan",
+ "Guid",
+ "Uri",
+ "Stream",
+ }
+ ),
color_hex="#178600",
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/go.py b/packages/core/src/repowise/core/ingestion/languages/specs/go.py
index 684627afa..ffe658db2 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/go.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/go.py
@@ -39,5 +39,17 @@ SPEC = LanguageSpec(
}
),
builtin_parents=frozenset({"error"}),
+ # Predeclared Go type names — never resolve to a user-defined type, so
+ # they are dropped before the resolver lookup. ``error``/``any``/
+ # ``comparable`` are predeclared identifiers, not keywords, but behave
+ # as builtins here.
+ builtin_types=frozenset(
+ {
+ "string", "bool", "byte", "rune", "error", "any", "comparable",
+ "int", "int8", "int16", "int32", "int64",
+ "uint", "uint8", "uint16", "uint32", "uint64", "uintptr",
+ "float32", "float64", "complex64", "complex128",
+ }
+ ),
color_hex="#00ADD8",
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/java.py b/packages/core/src/repowise/core/ingestion/languages/specs/java.py
index 062177b8d..69a4260ad 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/java.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/java.py
@@ -66,5 +66,55 @@ SPEC = LanguageSpec(
"Closeable",
}
),
+ # Primitives + ubiquitous JDK types that never resolve to a user-defined
+ # Java/Kotlin class in the workspace. Stripping them at extraction time
+ # avoids polluting the resolver with hopeless lookups. The list errs on
+ # the side of inclusion: a user class colliding with one of these names
+ # still surfaces through the value-import path, just not through the
+ # type-ref path.
+ builtin_types=frozenset(
+ {
+ # Java primitives + builtin type nodes
+ "boolean", "byte", "short", "int", "long", "float", "double",
+ "char", "void", "var",
+ # java.lang (auto-imported)
+ "Object", "String", "Class", "Enum", "Record",
+ "Integer", "Long", "Double", "Float", "Boolean", "Character",
+ "Byte", "Short", "Number", "Void",
+ "Thread", "Runnable", "Runtime", "Process", "ProcessBuilder",
+ "Throwable", "Exception", "RuntimeException", "Error",
+ "IllegalArgumentException", "IllegalStateException",
+ "NullPointerException", "UnsupportedOperationException",
+ "IndexOutOfBoundsException", "ClassCastException",
+ "ArithmeticException", "SecurityException", "ClassNotFoundException",
+ "InterruptedException", "CloneNotSupportedException",
+ "StringBuilder", "StringBuffer",
+ "Comparable", "Iterable", "AutoCloseable", "Cloneable",
+ "Override", "Deprecated", "SuppressWarnings",
+ "FunctionalInterface", "SafeVarargs",
+ "Math", "System",
+ # java.util ubiquitous containers (almost always external when used
+ # as a type position; the actual element type is captured separately
+ # by the same query via the type_arguments inner capture).
+ "List", "ArrayList", "LinkedList",
+ "Map", "HashMap", "LinkedHashMap", "TreeMap", "ConcurrentHashMap",
+ "Set", "HashSet", "LinkedHashSet", "TreeSet",
+ "Collection", "Collections", "Iterator", "Optional",
+ "Queue", "Deque", "ArrayDeque", "Stack",
+ # java.util.function
+ "Function", "BiFunction", "Consumer", "BiConsumer", "Supplier",
+ "Predicate", "BiPredicate", "UnaryOperator", "BinaryOperator",
+ # java.util.concurrent ubiquitous
+ "Future", "CompletableFuture", "Executor", "ExecutorService",
+ "CountDownLatch", "Semaphore", "AtomicBoolean", "AtomicInteger",
+ "AtomicLong", "AtomicReference",
+ # java.time
+ "Instant", "Duration", "LocalDate", "LocalTime", "LocalDateTime",
+ "ZonedDateTime", "OffsetDateTime", "Period", "ZoneId",
+ # java.io
+ "File", "InputStream", "OutputStream", "Reader", "Writer",
+ "IOException", "Serializable",
+ }
+ ),
color_hex="#B07219",
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/javascript.py b/packages/core/src/repowise/core/ingestion/languages/specs/javascript.py
index 8f5e50bb3..9a3e119a0 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/javascript.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/javascript.py
@@ -1,6 +1,7 @@
"""LanguageSpec for javascript (extracted from the registry data table)."""
from ..spec import LanguageSpec
+from .typescript import BUILTIN_TYPES as _TS_BUILTIN_TYPES
SPEC = LanguageSpec(
tag="javascript",
@@ -71,5 +72,8 @@ SPEC = LanguageSpec(
}
),
builtin_parents=frozenset({"Error", "Object"}),
+ # Same TS extractor and type grammar as typescript.py, so the same
+ # builtin set applies.
+ builtin_types=_TS_BUILTIN_TYPES,
color_hex="#F1E05A",
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/kotlin.py b/packages/core/src/repowise/core/ingestion/languages/specs/kotlin.py
index 96109afbc..4968b107e 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/kotlin.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/kotlin.py
@@ -56,5 +56,31 @@ SPEC = LanguageSpec(
"Serializable",
}
),
+ builtin_types=frozenset(
+ {
+ # Kotlin primitives (kotlin package, auto-imported)
+ "Boolean", "Byte", "Short", "Int", "Long", "Float", "Double", "Char",
+ "String", "Unit", "Nothing", "Any", "Number",
+ "Array", "IntArray", "LongArray", "ByteArray", "ShortArray",
+ "FloatArray", "DoubleArray", "CharArray", "BooleanArray",
+ "List", "MutableList", "ArrayList",
+ "Map", "MutableMap", "HashMap", "LinkedHashMap",
+ "Set", "MutableSet", "HashSet", "LinkedHashSet",
+ "Collection", "MutableCollection",
+ "Iterable", "MutableIterable", "Iterator", "MutableIterator",
+ "Sequence", "Pair", "Triple", "Result",
+ "Comparable", "Comparator",
+ "Throwable", "Exception", "RuntimeException", "Error",
+ "IllegalArgumentException", "IllegalStateException",
+ "NullPointerException", "UnsupportedOperationException",
+ "IndexOutOfBoundsException", "ClassCastException",
+ "Lazy", "Regex", "Range", "IntRange", "LongRange", "CharRange",
+ "Enum", "Annotation",
+ # kotlin.io / kotlin.text / kotlin.collections ubiquitous
+ "Reader", "Writer", "BufferedReader", "BufferedWriter",
+ # Coroutines + JVM common
+ "Object", "Function", "Runnable", "Class", "Void",
+ }
+ ),
color_hex="#A97BFF",
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/typescript.py b/packages/core/src/repowise/core/ingestion/languages/specs/typescript.py
index 503341e65..bb6ff97f2 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/typescript.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/typescript.py
@@ -2,6 +2,56 @@
from ..spec import LanguageSpec
+#: Predeclared / lib.dom / lib.es type names that never resolve to a user-
+#: defined symbol in the workspace. Filtering them before the resolver
+#: lookup avoids polluting the graph with edges for ubiquitous globals
+#: (``string``, ``Promise``, ``Pick``) the dead-code analyzer does not
+#: care about. The list intentionally errs on the side of inclusion: a
+#: user type colliding with one of these names will fail to resolve via
+#: the type-ref path, but cross-file usage still surfaces through the
+#: value-import + call path.
+#:
+#: Exported because javascript shares the TS extractor and needs the same set.
+BUILTIN_TYPES: frozenset[str] = frozenset(
+ {
+ # Primitives + structural
+ "string", "number", "boolean", "bigint", "symbol",
+ "void", "null", "undefined", "never", "unknown", "any",
+ "object", "this", "Object",
+ # Built-in containers / wrappers. ``Map`` / ``Set`` / ``WeakMap``
+ # / ``WeakSet`` are intentionally **not** listed: they're routinely
+ # shadowed by user-defined types (Hono ``interface Set<E>`` /
+ # ``interface Get<E>`` is the canonical case) and filtering them
+ # at extraction time hides the same-file rescue.
+ "Array", "ReadonlyArray", "Promise", "Awaited", "WeakRef",
+ "Date", "RegExp", "Error", "TypeError", "RangeError",
+ "SyntaxError", "ReferenceError", "EvalError",
+ "Function", "CallableFunction", "NewableFunction",
+ "ArrayBuffer", "SharedArrayBuffer", "DataView",
+ "Int8Array", "Uint8Array", "Uint8ClampedArray",
+ "Int16Array", "Uint16Array", "Int32Array", "Uint32Array",
+ "Float32Array", "Float64Array", "BigInt64Array", "BigUint64Array",
+ "Iterable", "AsyncIterable", "Iterator", "AsyncIterator",
+ "IterableIterator", "AsyncIterableIterator",
+ "Generator", "AsyncGenerator", "GeneratorFunction",
+ "Proxy", "Reflect", "JSON", "Math",
+ # Utility types
+ "Record", "Partial", "Required", "Readonly",
+ "Pick", "Omit", "Exclude", "Extract", "NonNullable",
+ "Parameters", "ConstructorParameters", "ReturnType",
+ "InstanceType", "ThisType", "ThisParameterType", "OmitThisParameter",
+ "Uppercase", "Lowercase", "Capitalize", "Uncapitalize",
+ # Common DOM / Node globals that show up everywhere as parameter
+ # types — listing here is a perf optimisation, not correctness.
+ "URL", "URLSearchParams", "Request", "Response", "Headers",
+ "Blob", "File", "FormData", "FileReader",
+ "AbortController", "AbortSignal", "AbortError",
+ "EventTarget", "Event", "CustomEvent", "MessageEvent",
+ "Element", "HTMLElement", "Node", "Document", "Window",
+ "Buffer", "NodeJS",
+ }
+)
+
SPEC = LanguageSpec(
tag="typescript",
display_name="TypeScript",
@@ -73,5 +123,6 @@ SPEC = LanguageSpec(
}
),
builtin_parents=frozenset({"Error", "Object"}),
+ builtin_types=BUILTIN_TYPES,
color_hex="#3178C6",
)
diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.py
index 994297c45..62f7a1ab8 100644
--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py
+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py
@@ -18,6 +18,7 @@ import structlog
from tree_sitter import Node
from .extractors import node_text
+from .type_names import is_resolvable_type_name
if TYPE_CHECKING:
from .models import Symbol
@@ -320,50 +321,6 @@ def _pascal_dedupe_key(parent_name: str | None, signature: str) -> tuple[str | N
# Type reference helpers (used by _extract_type_refs)
# ---------------------------------------------------------------------------
-# Type expressions that never resolve to a user-defined .NET type. Skipping
-# these here avoids polluting the resolver with hopeless lookups. Generic
-# args inside `IList<T>` are stripped before this check is applied.
-_BUILTIN_CSHARP_TYPES: frozenset[str] = frozenset(
- {
- "void",
- "bool",
- "byte",
- "sbyte",
- "char",
- "short",
- "ushort",
- "int",
- "uint",
- "long",
- "ulong",
- "float",
- "double",
- "decimal",
- "string",
- "object",
- "nint",
- "nuint",
- "dynamic",
- "var",
- # Frequently appearing BCL types that are always external — listing
- # them here is purely a performance optimisation (one dict miss
- # avoided per occurrence).
- "Task",
- "ValueTask",
- "CancellationToken",
- "Action",
- "Func",
- "Type",
- "Exception",
- "DateTime",
- "DateTimeOffset",
- "TimeSpan",
- "Guid",
- "Uri",
- "Stream",
- }
-)
-
_PARAM_ORIGIN_BY_ANCESTOR: dict[str, str] = {
"type_argument_list": "generic_argument",
"typeof_expression": "typeof",
@@ -478,16 +435,7 @@ def _head_type_identifier(type_node: Node, src: str) -> str | None:
ident = _first_descendant(head_node, "identifier")
text = _node_text(ident, src) if ident else ""
- if not text or (not text[0].isalpha() and text[0] != "_"):
- return None
- if text in _BUILTIN_CSHARP_TYPES:
- return None
- # Single-uppercase-letter heads are overwhelmingly generic params (T, K, V).
- # Skipping them avoids spurious lookups against a type-name index that
- # would never contain them.
- if len(text) == 1 and text.isupper():
- return None
- return text
+ return text if is_resolvable_type_name(text, "csharp") else None
def _first_descendant(node: Node, type_name: str) -> Node | None:
@@ -523,19 +471,6 @@ def _classify_param_origin(type_node: Node) -> str:
# Go type-reference head extraction
# ---------------------------------------------------------------------------
-# Predeclared Go type names — never resolve to a user-defined type, so they
-# are dropped before the resolver lookup. ``error``/``any``/``comparable``
-# are predeclared identifiers, not keywords, but behave as builtins here.
-_GO_BUILTIN_TYPES: frozenset[str] = frozenset(
- {
- "string", "bool", "byte", "rune", "error", "any", "comparable",
- "int", "int8", "int16", "int32", "int64",
- "uint", "uint8", "uint16", "uint32", "uint64", "uintptr",
- "float32", "float64", "complex64", "complex128",
- }
-)
-
-
def _go_head_type_identifier(type_node: Node, src: str) -> str | None:
"""Return the head type name of a Go type expression, or None.
@@ -598,38 +533,13 @@ def _go_head_type_identifier(type_node: Node, src: str) -> str | None:
else:
return None
- if not text or (not text[0].isalpha() and text[0] != "_"):
- return None
- if text in _GO_BUILTIN_TYPES:
- return None
- # Single-uppercase-letter heads are overwhelmingly generic type params.
- if len(text) == 1 and text.isupper():
- return None
- return text
+ return text if is_resolvable_type_name(text, "go") else None
# ---------------------------------------------------------------------------
# C / C++ type-reference head extraction
# ---------------------------------------------------------------------------
-# Predeclared / standard-library scalar types that never resolve to a
-# user-defined struct, so they're dropped before the resolver lookup.
-# ``primitive_type`` / ``sized_type_specifier`` nodes are filtered
-# structurally below; this set catches the ``<stdint.h>`` / ``<stddef.h>``
-# typedefs that the grammar surfaces as plain ``type_identifier`` nodes.
-_C_BUILTIN_TYPES: frozenset[str] = frozenset(
- {
- "void", "char", "short", "int", "long", "float", "double",
- "signed", "unsigned", "bool", "_Bool", "_Complex",
- "size_t", "ssize_t", "rsize_t", "ptrdiff_t", "intptr_t", "uintptr_t",
- "int8_t", "int16_t", "int32_t", "int64_t",
- "uint8_t", "uint16_t", "uint32_t", "uint64_t",
- "intmax_t", "uintmax_t", "wchar_t", "wint_t", "char16_t", "char32_t",
- "va_list", "FILE",
- }
-)
-
-
def _c_head_type_identifier(type_node: Node, src: str) -> str | None:
"""Return the head type name of a C / C++ type expression, or None.
@@ -677,68 +587,14 @@ def _c_head_type_identifier(type_node: Node, src: str) -> str | None:
else:
return None
- if not text or (not text[0].isalpha() and text[0] != "_"):
- return None
- if text in _C_BUILTIN_TYPES:
- return None
- if len(text) == 1 and text.isupper():
- return None
- return text
+ # cpp shares this extractor; the builtin set is identical for both.
+ return text if is_resolvable_type_name(text, "c") else None
# ---------------------------------------------------------------------------
# TypeScript / JavaScript type-reference head extraction
# ---------------------------------------------------------------------------
-# Predeclared / lib.dom / lib.es type names that never resolve to a user-
-# defined symbol in the workspace. Filtering them before the resolver
-# lookup avoids polluting the graph with edges for ubiquitous globals
-# (``string``, ``Promise``, ``Pick``) the dead-code analyzer does not
-# care about. The list intentionally errs on the side of inclusion: a
-# user type colliding with one of these names will fail to resolve via
-# the type-ref path, but cross-file usage still surfaces through the
-# value-import + call path.
-_TS_BUILTIN_TYPES: frozenset[str] = frozenset(
- {
- # Primitives + structural
- "string", "number", "boolean", "bigint", "symbol",
- "void", "null", "undefined", "never", "unknown", "any",
- "object", "this", "Object",
- # Built-in containers / wrappers. ``Map`` / ``Set`` / ``WeakMap``
- # / ``WeakSet`` are intentionally **not** listed: they're routinely
- # shadowed by user-defined types (Hono ``interface Set<E>`` /
- # ``interface Get<E>`` is the canonical case) and filtering them
- # at extraction time hides the same-file rescue.
- "Array", "ReadonlyArray", "Promise", "Awaited", "WeakRef",
- "Date", "RegExp", "Error", "TypeError", "RangeError",
- "SyntaxError", "ReferenceError", "EvalError",
- "Function", "CallableFunction", "NewableFunction",
- "ArrayBuffer", "SharedArrayBuffer", "DataView",
- "Int8Array", "Uint8Array", "Uint8ClampedArray",
- "Int16Array", "Uint16Array", "Int32Array", "Uint32Array",
- "Float32Array", "Float64Array", "BigInt64Array", "BigUint64Array",
- "Iterable", "AsyncIterable", "Iterator", "AsyncIterator",
- "IterableIterator", "AsyncIterableIterator",
- "Generator", "AsyncGenerator", "GeneratorFunction",
- "Proxy", "Reflect", "JSON", "Math",
- # Utility types
- "Record", "Partial", "Required", "Readonly",
- "Pick", "Omit", "Exclude", "Extract", "NonNullable",
- "Parameters", "ConstructorParameters", "ReturnType",
- "InstanceType", "ThisType", "ThisParameterType", "OmitThisParameter",
- "Uppercase", "Lowercase", "Capitalize", "Uncapitalize",
- # Common DOM / Node globals that show up everywhere as parameter
- # types — listing here is a perf optimisation, not correctness.
- "URL", "URLSearchParams", "Request", "Response", "Headers",
- "Blob", "File", "FormData", "FileReader",
- "AbortController", "AbortSignal", "AbortError",
- "EventTarget", "Event", "CustomEvent", "MessageEvent",
- "Element", "HTMLElement", "Node", "Document", "Window",
- "Buffer", "NodeJS",
- }
-)
-
-
def _ts_head_type_identifier(type_node: Node, src: str) -> str | None:
"""Return the head identifier of a TypeScript/JavaScript type, or None.
@@ -825,75 +681,13 @@ def _ts_head_type_identifier(type_node: Node, src: str) -> str | None:
else:
return None
- # JS/TS identifiers may start with `$` or `_` in addition to a
- # letter — Zod's ``$ZSF`` interface family is the canonical case.
- if not text or (not text[0].isalpha() and text[0] not in ("_", "$")):
- return None
- if text in _TS_BUILTIN_TYPES:
- return None
- # Single-uppercase-letter heads are overwhelmingly generic type params
- # (T, K, V, U). Skipping them avoids spurious lookups.
- if len(text) == 1 and text.isupper():
- return None
- return text
+ return text if is_resolvable_type_name(text, "typescript") else None
# ---------------------------------------------------------------------------
# Java type-reference head extraction
# ---------------------------------------------------------------------------
-# Primitives + ubiquitous JDK types that never resolve to a user-defined
-# Java/Kotlin class in the workspace. Stripping them at extraction time
-# avoids polluting the resolver with hopeless lookups. The list errs on
-# the side of inclusion: a user class colliding with one of these names
-# still surfaces through the value-import path, just not through the
-# type-ref path.
-_JAVA_BUILTIN_TYPES: frozenset[str] = frozenset(
- {
- # Java primitives + builtin type nodes
- "boolean", "byte", "short", "int", "long", "float", "double",
- "char", "void", "var",
- # java.lang (auto-imported)
- "Object", "String", "Class", "Enum", "Record",
- "Integer", "Long", "Double", "Float", "Boolean", "Character",
- "Byte", "Short", "Number", "Void",
- "Thread", "Runnable", "Runtime", "Process", "ProcessBuilder",
- "Throwable", "Exception", "RuntimeException", "Error",
- "IllegalArgumentException", "IllegalStateException",
- "NullPointerException", "UnsupportedOperationException",
- "IndexOutOfBoundsException", "ClassCastException",
- "ArithmeticException", "SecurityException", "ClassNotFoundException",
- "InterruptedException", "CloneNotSupportedException",
- "StringBuilder", "StringBuffer",
- "Comparable", "Iterable", "AutoCloseable", "Cloneable",
- "Override", "Deprecated", "SuppressWarnings",
- "FunctionalInterface", "SafeVarargs",
- "Math", "System",
- # java.util ubiquitous containers (almost always external when used
- # as a type position; the actual element type is captured separately
- # by the same query via the type_arguments inner capture).
- "List", "ArrayList", "LinkedList",
- "Map", "HashMap", "LinkedHashMap", "TreeMap", "ConcurrentHashMap",
- "Set", "HashSet", "LinkedHashSet", "TreeSet",
- "Collection", "Collections", "Iterator", "Optional",
- "Queue", "Deque", "ArrayDeque", "Stack",
- # java.util.function
- "Function", "BiFunction", "Consumer", "BiConsumer", "Supplier",
- "Predicate", "BiPredicate", "UnaryOperator", "BinaryOperator",
- # java.util.concurrent ubiquitous
- "Future", "CompletableFuture", "Executor", "ExecutorService",
- "CountDownLatch", "Semaphore", "AtomicBoolean", "AtomicInteger",
- "AtomicLong", "AtomicReference",
- # java.time
- "Instant", "Duration", "LocalDate", "LocalTime", "LocalDateTime",
- "ZonedDateTime", "OffsetDateTime", "Period", "ZoneId",
- # java.io
- "File", "InputStream", "OutputStream", "Reader", "Writer",
- "IOException", "Serializable",
- }
-)
-
-
def _java_head_type_identifier(type_node: Node, src: str) -> str | None:
"""Return the head type identifier of a Java type expression, or None.
@@ -955,48 +749,13 @@ def _java_head_type_identifier(type_node: Node, src: str) -> str | None:
else:
return None
- if not text or (not text[0].isalpha() and text[0] != "_"):
- return None
- if text in _JAVA_BUILTIN_TYPES:
- return None
- # Single-uppercase-letter heads are overwhelmingly generic type params.
- if len(text) == 1 and text.isupper():
- return None
- return text
+ return text if is_resolvable_type_name(text, "java") else None
# ---------------------------------------------------------------------------
# Kotlin type-reference head extraction
# ---------------------------------------------------------------------------
-_KOTLIN_BUILTIN_TYPES: frozenset[str] = frozenset(
- {
- # Kotlin primitives (kotlin package, auto-imported)
- "Boolean", "Byte", "Short", "Int", "Long", "Float", "Double", "Char",
- "String", "Unit", "Nothing", "Any", "Number",
- "Array", "IntArray", "LongArray", "ByteArray", "ShortArray",
- "FloatArray", "DoubleArray", "CharArray", "BooleanArray",
- "List", "MutableList", "ArrayList",
- "Map", "MutableMap", "HashMap", "LinkedHashMap",
- "Set", "MutableSet", "HashSet", "LinkedHashSet",
- "Collection", "MutableCollection",
- "Iterable", "MutableIterable", "Iterator", "MutableIterator",
- "Sequence", "Pair", "Triple", "Result",
- "Comparable", "Comparator",
- "Throwable", "Exception", "RuntimeException", "Error",
- "IllegalArgumentException", "IllegalStateException",
- "NullPointerException", "UnsupportedOperationException",
- "IndexOutOfBoundsException", "ClassCastException",
- "Lazy", "Regex", "Range", "IntRange", "LongRange", "CharRange",
- "Enum", "Annotation",
- # kotlin.io / kotlin.text / kotlin.collections ubiquitous
- "Reader", "Writer", "BufferedReader", "BufferedWriter",
- # Coroutines + JVM common
- "Object", "Function", "Runnable", "Class", "Void",
- }
-)
-
-
def _kotlin_head_type_identifier(type_node: Node, src: str) -> str | None:
"""Return the head identifier of a Kotlin type expression, or None.
@@ -1048,13 +807,7 @@ def _kotlin_head_type_identifier(type_node: Node, src: str) -> str | None:
else:
return None
- if not text or (not text[0].isalpha() and text[0] != "_"):
- return None
- if text in _KOTLIN_BUILTIN_TYPES:
- return None
- if len(text) == 1 and text.isupper():
- return None
- return text
+ return text if is_resolvable_type_name(text, "kotlin") else None
# Per-language head-identifier extractor for ``@param.type`` captures.
diff --git a/packages/core/src/repowise/core/ingestion/type_names.py b/packages/core/src/repowise/core/ingestion/type_names.py
new file mode 100644
index 000000000..6e853fa2f
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/type_names.py
@@ -0,0 +1,109 @@
+"""One answer to "what is this type's bare name".
+
+Two questions were being answered independently in twenty places, and they are
+not the same question:
+
+``bare_type_name``
+ Shape only. Given a type as written in source, return the name without its
+ type arguments or its qualifier. Language-independent, because every
+ language we parse spells a qualifier with ``.``, ``::`` or ``\\`` and opens
+ type arguments with ``<``, ``[`` or ``(``.
+
+``is_resolvable_type_name``
+ Policy, for the type-use path only. Given a bare name and a language, could
+ it name a symbol this repo declares? Builtins and single-letter generic
+ parameters cannot, so looking them up is waste.
+
+They are deliberately separate. Heritage filters builtin parents through its
+own per-language set and the dynamic-hint extractors filter nothing at all, so
+a shared shape helper that also applied one builtin policy would hand every
+caller a different consumer's rules.
+
+This module is a leaf: it reads the language registry and nothing else.
+"""
+
+from __future__ import annotations
+
+from .language_data import get_builtin_types
+
+# A qualifier separator in any language we parse. PHP's ``\`` is here rather
+# than handled per-language because no type name may contain one, so splitting
+# on all three can only ever be right.
+_QUALIFIER_SEPARATORS = (".", "::", "\\")
+
+# Bracket pairs that delimit type arguments. A constructor call's ``(...)``
+# is deliberately not here: it sits in the same position but means something
+# else, and a Python base written ``factory().__class__`` must keep its last
+# attribute rather than yield the callee.
+_TYPE_ARGUMENT_BRACKETS = (("<", ">"), ("[", "]"))
+
+# Languages where a leading ``$`` starts a real user type rather than a
+# compiler artefact. This is consumer policy, not language identity: ``$`` is a
+# legal identifier start in several languages here, but only in TS/JS is a
+# ``$``-prefixed type routinely one the repo declares.
+_DOLLAR_START_LANGUAGES = frozenset({"typescript", "javascript"})
+
+
+def strip_type_arguments(raw: str) -> str:
+ """Return *raw* with every balanced type-argument group removed.
+
+ Removed rather than truncated at the opener, because a qualifier can follow
+ the group: ``Impl<C>::type`` names ``type``, and cutting at ``<`` would
+ answer ``Impl``. Truncating is equally wrong the other way round —
+ ``Outer<a.b.C>`` must not have its qualifier taken from inside the group.
+ """
+ text = raw
+ for opener, closer in _TYPE_ARGUMENT_BRACKETS:
+ out: list[str] = []
+ depth = 0
+ for char in text:
+ if char == opener:
+ depth += 1
+ elif char == closer:
+ # An unbalanced closer means the text was already truncated
+ # upstream; dropping it is better than keeping a stray bracket.
+ depth = max(0, depth - 1)
+ elif depth == 0:
+ out.append(char)
+ text = "".join(out)
+ return text
+
+
+def strip_call_arguments(raw: str) -> str:
+ """Return *raw* without a trailing constructor-call argument list.
+
+ For the languages whose heritage clause names a base by calling it —
+ Kotlin's ``Bar()``, a C# record's ``Base(x)``.
+ """
+ head, sep, _ = raw.partition("(")
+ return head if sep else raw
+
+
+def bare_type_name(raw: str) -> str:
+ """Return *raw* without its type arguments or qualifier.
+
+ ``Gen<Arg>`` → ``Gen``; ``ns.Qual`` → ``Qual``; ``ns.Both<Arg>`` → ``Both``;
+ ``\\Ns\\Qual`` → ``Qual``; ``NS::Widget`` → ``Widget``;
+ ``Impl<C>::type`` → ``type``.
+ """
+ text = strip_type_arguments(raw.strip())
+ for separator in _QUALIFIER_SEPARATORS:
+ text = text.rsplit(separator, 1)[-1]
+ return text.strip()
+
+
+def is_resolvable_type_name(name: str, language: str) -> bool:
+ """True if *name* could name a symbol declared in this repo.
+
+ Rejects the empty string, names not starting with an identifier character,
+ the language's builtin types, and single uppercase letters, which are
+ overwhelmingly generic parameters (``T``, ``K``, ``V``).
+ """
+ if not name:
+ return False
+ starters = "_$" if language in _DOLLAR_START_LANGUAGES else "_"
+ if not name[0].isalpha() and name[0] not in starters:
+ return False
+ if name in get_builtin_types(language):
+ return False
+ return not (len(name) == 1 and name.isupper())
diff --git a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
index 4a43ae242..e2161aa82 100644
--- a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
+++ b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
@@ -254,10 +254,11 @@ def _resolve_go_type_refs(
return 0
from .cohesion import SAME_PACKAGE_HINT
- from .parser_helpers import _GO_BUILTIN_TYPES
+ from .language_data import get_builtin_types
from .resolvers.go_workspace import get_or_build_go_index
index = get_or_build_go_index(ctx)
+ go_builtin_types = get_builtin_types("go")
from_path = parsed.file_info.path
# Candidate defining files: same-package siblings (referenced with no
@@ -286,7 +287,7 @@ def _resolve_go_type_refs(
same_file_refs: set[str] = set()
for ref in parsed.type_refs:
name = ref.type_name
- if not name or name in _GO_BUILTIN_TYPES:
+ if not name or name in go_builtin_types:
continue
# Check cross-file candidates first.
target = _find_go_type_file(name, sorted_candidates, defined_names)
@@ -394,10 +395,11 @@ def _resolve_c_type_refs(
if not parsed.type_refs:
return 0
- from .parser_helpers import _C_BUILTIN_TYPES
+ from .language_data import get_builtin_types
from_path = parsed.file_info.path
is_cpp = parsed.file_info.language == "cpp"
+ c_builtin_types = get_builtin_types("c")
import_targets: set[str] = set()
for imp in parsed.imports:
@@ -422,7 +424,7 @@ def _resolve_c_type_refs(
seen_targets: set[tuple[str, str]] = set()
for ref in parsed.type_refs:
name = ref.type_name
- if not name or name in _C_BUILTIN_TYPES:
+ if not name or name in c_builtin_types:
continue
if is_cpp and name in _CPP_STL_HEAD_NAMES:
continue
diff --git a/tests/unit/ingestion/test_heritage_type_names.py b/tests/unit/ingestion/test_heritage_type_names.py
new file mode 100644
index 000000000..4c0aab7f8
--- /dev/null
+++ b/tests/unit/ingestion/test_heritage_type_names.py
@@ -0,0 +1,153 @@
+"""Characterisation: the parent name each language's heritage extractor emits.
+
+Every extractor answers one question — given a parent type written in source,
+what is the bare type name — and each answered it its own way. This table pins
+the answer per language for four spellings of the same parent: bare, with type
+arguments, qualified, and both.
+
+Every row now yields the bare name, because all fourteen extractors ask one
+module for it. The rows that moved to get here are what the table was committed
+to expose: type arguments survived into the parent name in six languages, a
+qualifier was emitted as a parent in its own right in three, and two dropped a
+qualified parent entirely.
+
+Two languages still produce no edge, and neither is a type-name defect. Pascal's
+grammar is not installed here. JavaScript's extractor looks for a clause node
+only TypeScript's grammar emits.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+import pytest
+
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+# (language, extension, source template with {p}, parent spelling, expected
+# (parent_name, kind) pairs). Templates declare one class so a failure names
+# one case.
+CASES: list[tuple[str, str, str, str, list[tuple[str, str]]]] = [
+ # --- python ------------------------------------------------------------
+ ("python", "py", "class Child({p}):\n pass\n", "Bare", [("Bare", "extends")]),
+ ("python", "py", "class Child({p}):\n pass\n", "Gen[Arg]", [("Gen", "extends")]),
+ ("python", "py", "class Child({p}):\n pass\n", "ns.Qual", [("Qual", "extends")]),
+ ("python", "py", "class Child({p}):\n pass\n", "ns.Both[Arg]", [("Both", "extends")]),
+ # --- java --------------------------------------------------------------
+ ("java", "java", "class Child extends {p} {{}}\n", "Bare", [("Bare", "extends")]),
+ ("java", "java", "class Child extends {p} {{}}\n", "Gen<Arg>", [("Gen", "extends")]),
+ ("java", "java", "class Child extends {p} {{}}\n", "ns.Qual", [("Qual", "extends")]),
+ ("java", "java", "class Child extends {p} {{}}\n", "ns.Both<Arg>", [("Both", "extends")]),
+ # --- kotlin ------------------------------------------------------------
+ ("kotlin", "kt", "class Child : {p}()\n", "Bare", [("Bare", "extends")]),
+ ("kotlin", "kt", "class Child : {p}()\n", "Gen<Arg>", [("Gen", "extends")]),
+ ("kotlin", "kt", "class Child : {p}()\n", "ns.Qual", [("Qual", "extends")]),
+ ("kotlin", "kt", "class Child : {p}()\n", "ns.Both<Arg>", [("Both", "extends")]),
+ # --- csharp ------------------------------------------------------------
+ ("csharp", "cs", "class Child : {p} {{}}\n", "Bare", [("Bare", "extends")]),
+ ("csharp", "cs", "class Child : {p} {{}}\n", "Gen<Arg>", [("Gen", "extends")]),
+ ("csharp", "cs", "class Child : {p} {{}}\n", "ns.Qual", [("Qual", "extends")]),
+ ("csharp", "cs", "class Child : {p} {{}}\n", "ns.Both<Arg>", [("Both", "extends")]),
+ # --- cpp ---------------------------------------------------------------
+ ("cpp", "cpp", "class Child : public {p} {{}};\n", "Bare", [("Bare", "extends")]),
+ ("cpp", "cpp", "class Child : public {p} {{}};\n", "Gen<Arg>", [("Gen", "extends")]),
+ ("cpp", "cpp", "class Child : public {p} {{}};\n", "ns::Qual", [("Qual", "extends")]),
+ ("cpp", "cpp", "class Child : public {p} {{}};\n", "ns::Both<Arg>", [("Both", "extends")]),
+ # --- go: struct embedding ----------------------------------------------
+ ("go", "go", "type Child struct {{\n\t{p}\n}}\n", "Bare", [("Bare", "mixin")]),
+ ("go", "go", "type Child struct {{\n\t{p}\n}}\n", "Gen[Arg]", [("Gen", "mixin")]),
+ ("go", "go", "type Child struct {{\n\t{p}\n}}\n", "ns.Qual", [("Qual", "mixin")]),
+ ("go", "go", "type Child struct {{\n\t{p}\n}}\n", "ns.Both[Arg]", [("Both", "mixin")]),
+ # --- rust --------------------------------------------------------------
+ ("rust", "rs", "struct Child;\nimpl {p} for Child {{}}\n", "Bare", [("Bare", "trait_impl")]),
+ (
+ "rust",
+ "rs",
+ "struct Child;\nimpl {p} for Child {{}}\n",
+ "Gen<Arg>",
+ [("Gen", "trait_impl")],
+ ),
+ (
+ "rust",
+ "rs",
+ "struct Child;\nimpl {p} for Child {{}}\n",
+ "ns::Qual",
+ [("Qual", "trait_impl")],
+ ),
+ (
+ "rust",
+ "rs",
+ "struct Child;\nimpl {p} for Child {{}}\n",
+ "ns::Both<Arg>",
+ [("Both", "trait_impl")],
+ ),
+ # --- ruby: no generic syntax to mishandle ------------------------------
+ ("ruby", "rb", "class Child < {p}\nend\n", "Bare", [("Bare", "extends")]),
+ ("ruby", "rb", "class Child < {p}\nend\n", "Ns::Qual", [("Qual", "extends")]),
+ # --- typescript --------------------------------------------------------
+ ("typescript", "ts", "class Child extends {p} {{}}\n", "Bare", [("Bare", "extends")]),
+ ("typescript", "ts", "class Child extends {p} {{}}\n", "Gen<Arg>", [("Gen", "extends")]),
+ ("typescript", "ts", "class Child extends {p} {{}}\n", "ns.Qual", [("Qual", "extends")]),
+ (
+ "typescript",
+ "ts",
+ "class Child extends {p} {{}}\n",
+ "ns.Both<Arg>",
+ [("Both", "extends")],
+ ),
+ # --- javascript: a grammar-shape gap, not a type-name one --------------
+ ("javascript", "js", "class Child extends {p} {{}}\n", "Bare", []),
+ ("javascript", "js", "class Child extends {p} {{}}\n", "ns.Qual", []),
+ # --- swift -------------------------------------------------------------
+ ("swift", "swift", "class Child: {p} {{}}\n", "Bare", [("Bare", "extends")]),
+ ("swift", "swift", "class Child: {p} {{}}\n", "Gen<Arg>", [("Gen", "extends")]),
+ ("swift", "swift", "class Child: {p} {{}}\n", "Ns.Qual", [("Qual", "extends")]),
+ ("swift", "swift", "class Child: {p} {{}}\n", "Ns.Both<Arg>", [("Both", "extends")]),
+ # --- dart --------------------------------------------------------------
+ ("dart", "dart", "class Child extends {p} {{}}\n", "Bare", [("Bare", "extends")]),
+ ("dart", "dart", "class Child extends {p} {{}}\n", "Gen<Arg>", [("Gen", "extends")]),
+ ("dart", "dart", "class Child extends {p} {{}}\n", "ns.Qual", [("Qual", "extends")]),
+ ("dart", "dart", "class Child extends {p} {{}}\n", "ns.Both<Arg>", [("Both", "extends")]),
+ # --- scala -------------------------------------------------------------
+ ("scala", "scala", "class Child extends {p}\n", "Bare", [("Bare", "extends")]),
+ ("scala", "scala", "class Child extends {p}\n", "Gen[Arg]", [("Gen", "extends")]),
+ ("scala", "scala", "class Child extends {p}\n", "ns.Qual", [("Qual", "extends")]),
+ ("scala", "scala", "class Child extends {p}\n", "ns.Both[Arg]", [("Both", "extends")]),
+ # --- php ---------------------------------------------------------------
+ ("php", "php", "<?php\nclass Child extends {p} {{}}\n", "Bare", [("Bare", "extends")]),
+ ("php", "php", "<?php\nclass Child extends {p} {{}}\n", "\\Ns\\Qual", [("Qual", "extends")]),
+]
+
+
+def _parse(language: str, ext: str, source: str):
+ info = FileInfo(
+ path=f"probe.{ext}",
+ abs_path=f"/tmp/probe.{ext}",
+ language=language,
+ size_bytes=len(source),
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ return ASTParser().parse_file(info, source.encode())
+
+
+ ("language", "ext", "template", "spelling", "expected"),
+ CASES,
+ ids=[f"{c[0]}-{c[3]}" for c in CASES],
+)
+def test_parent_name_for_spelling(
+ language: str,
+ ext: str,
+ template: str,
+ spelling: str,
+ expected: list[tuple[str, str]],
+) -> None:
+ parsed = _parse(language, ext, template.format(p=spelling))
+ got = [(h.parent_name, h.kind) for h in parsed.heritage]
+ assert sorted(got) == sorted(expected)
diff --git a/tests/unit/ingestion/test_type_head_identifiers.py b/tests/unit/ingestion/test_type_head_identifiers.py
new file mode 100644
index 000000000..6b3ddf521
--- /dev/null
+++ b/tests/unit/ingestion/test_type_head_identifiers.py
@@ -0,0 +1,295 @@
+"""Characterisation: what the six type-head extractors in ``parser_helpers.py``
+actually produce for a table of type spellings, per language.
+
+``TYPE_HEAD_EXTRACTORS`` dispatches ``@param.type`` captures (constructor /
+method parameters, fields, generics, heritage, ...) to a language-specific
+extractor: ``_head_type_identifier`` (C#, the dict default), ``_go_...``,
+``_c_...`` (shared by C and C++), ``_ts_...`` (shared by TypeScript and
+JavaScript), ``_java_...``, ``_kotlin_...``. Each answers "what is the head
+type name" its own way, with its own builtin-filter list and its own
+generic-argument recursion (or lack of it).
+
+Driven through the real parser (never hand-built tree-sitter nodes) so the
+pinned values are what production actually emits, not what the extractor's
+docstring claims. Committed against pre-existing behaviour: rows marked
+"defect" are bugs, pinned anyway, because this file's job is to make the next
+change to it show up as a legible diff rather than a silent regression.
+
+Rust and Pascal are excluded: Rust uses the default C# extractor (already
+covered by the C# rows) via no per-language entry, and Pascal's grammar
+(tree_sitter_pascal) is unavailable in this environment.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+import pytest
+
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+# (language, extension, case id, source, expected (type_name, origin) pairs).
+# Each source declares exactly one type-bearing construct so a failure names
+# one case. Grouped per language in the order TYPE_HEAD_EXTRACTORS lists them
+# (csharp is the dict's default fallback, listed first).
+CASES: list[tuple[str, str, str, str, list[tuple[str, str]]]] = [
+ # =========================================================================
+ # C# — _head_type_identifier (the TYPE_HEAD_EXTRACTORS default)
+ # =========================================================================
+ ("csharp", "cs", "plain", "class Probe {\n void M(Basket a) {}\n}\n", [("Basket", "method_param")]),
+ (
+ "csharp",
+ "cs",
+ "generic",
+ "class Probe {\n void M(IList<Basket> a) {}\n}\n",
+ # Generic args are captured separately via type_argument_list, so
+ # both the head and the arg show up as their own refs.
+ [("IList", "method_param"), ("Basket", "generic_argument")],
+ ),
+ (
+ "csharp",
+ "cs",
+ "qualified",
+ "class Probe {\n void M(Acme.Catalog.IRepository a) {}\n}\n",
+ [("IRepository", "method_param")],
+ ),
+ (
+ "csharp",
+ "cs",
+ "ref-readonly-generic-wrapper",
+ "class Probe {\n void M(ref readonly Span<byte> a) {}\n}\n",
+ [("Span", "method_param")],
+ ),
+ ("csharp", "cs", "nullable-wrapper", "class Probe {\n void M(Foo? a) {}\n}\n", [("Foo", "method_param")]),
+ ("csharp", "cs", "array-wrapper", "class Probe {\n void M(Foo[] a) {}\n}\n", [("Foo", "method_param")]),
+ ("csharp", "cs", "builtin-string", "class Probe {\n void M(string a) {}\n}\n", []),
+ ("csharp", "cs", "builtin-int", "class Probe {\n void M(int a) {}\n}\n", []),
+ ("csharp", "cs", "single-upper-generic-param", "class Probe {\n void M(T a) {}\n}\n", []),
+ # =========================================================================
+ # Go — _go_head_type_identifier
+ # =========================================================================
+ ("go", "go", "plain", "package main\n\nfunc F(a Options) {}\n", [("Options", "param_type")]),
+ (
+ "go",
+ "go",
+ "generic",
+ # Defect: unlike C#/Java/C++, Go's query has no separate capture for
+ # a generic type argument — ``Inner`` is silently dropped, not just
+ # filtered.
+ "package main\n\nfunc F(a List[Inner]) {}\n",
+ [("List", "param_type")],
+ ),
+ (
+ "go",
+ "go",
+ "qualified",
+ "package main\n\nfunc F(a dynacache.Cache) {}\n",
+ [("Cache", "param_type")],
+ ),
+ ("go", "go", "pointer-wrapper", "package main\n\nfunc F(a *Cache) {}\n", [("Cache", "param_type")]),
+ ("go", "go", "slice-wrapper", "package main\n\nfunc F(a []Partition) {}\n", [("Partition", "param_type")]),
+ (
+ "go",
+ "go",
+ "map-value-wrapper",
+ "package main\n\nfunc F(a map[string]Config) {}\n",
+ [("Config", "param_type")],
+ ),
+ ("go", "go", "builtin-string", "package main\n\nfunc F(a string) {}\n", []),
+ ("go", "go", "builtin-error", "package main\n\nfunc F(a error) {}\n", []),
+ ("go", "go", "single-upper-generic-param", "package main\n\nfunc F(a T) {}\n", []),
+ # =========================================================================
+ # C — _c_head_type_identifier (shared with C++)
+ # =========================================================================
+ ("c", "c", "plain", "void f(JSON_Value *v) {}\n", [("JSON_Value", "param_type")]),
+ ("c", "c", "named-struct-ref", "void f(struct JSON_Object *o) {}\n", [("JSON_Object", "param_type")]),
+ ("c", "c", "builtin-int", "void f(int x) {}\n", []),
+ ("c", "c", "builtin-unsigned-long", "void f(unsigned long x) {}\n", []),
+ ("c", "c", "stdlib-typedef-size_t", "void f(size_t x) {}\n", []),
+ # C has no ``::`` qualifier or template syntax to exercise those rows.
+ # =========================================================================
+ # C++ — _c_head_type_identifier
+ # =========================================================================
+ ("cpp", "cpp", "plain", "void f(Widget *w) {}\n", [("Widget", "param_type")]),
+ (
+ "cpp",
+ "cpp",
+ "generic",
+ # Unlike Go, C++'s template_argument_list pattern DOES capture the
+ # inner arg as its own ref.
+ "void f(std::vector<Widget> v) {}\n",
+ [("vector", "param_type"), ("Widget", "param_type")],
+ ),
+ ("cpp", "cpp", "qualified", "void f(NS::Widget *w) {}\n", [("Widget", "param_type")]),
+ ("cpp", "cpp", "builtin-int", "void f(int x) {}\n", []),
+ ("cpp", "cpp", "stdlib-typedef-size_t", "void f(size_t x) {}\n", []),
+ ("cpp", "cpp", "single-upper-generic-param", "void f(T x) {}\n", []),
+ # =========================================================================
+ # TypeScript — _ts_head_type_identifier (shared with JavaScript)
+ # =========================================================================
+ ("typescript", "ts", "plain", "function f(a: Foo) {}\n", [("Foo", "param_type")]),
+ (
+ "typescript",
+ "ts",
+ "generic-builtin-outer",
+ # Defect: the builtin outer (Promise) is correctly filtered, but the
+ # inner user type (Foo) is never captured separately — TS has no
+ # equivalent of C#'s type_argument_list rescue. Produces nothing.
+ "function f(a: Promise<Foo>) {}\n",
+ [],
+ ),
+ (
+ "typescript",
+ "ts",
+ "generic-user-outer",
+ # Defect: same loss when the outer is a non-builtin — only the
+ # outer head (Container) survives; the inner arg (Foo) is dropped.
+ "function f(a: Container<Foo>) {}\n",
+ [("Container", "param_type")],
+ ),
+ ("typescript", "ts", "qualified", "function f(a: ns.Foo) {}\n", [("Foo", "param_type")]),
+ ("typescript", "ts", "array-wrapper", "function f(a: Foo[]) {}\n", [("Foo", "param_type")]),
+ ("typescript", "ts", "builtin-string", "function f(a: string) {}\n", []),
+ ("typescript", "ts", "builtin-bare-Promise", "function f(a: Promise) {}\n", []),
+ ("typescript", "ts", "single-upper-generic-param", "function f(a: T) {}\n", []),
+ (
+ "typescript",
+ "ts",
+ "union-type",
+ "function f(a: Foo | null) {}\n",
+ [("Foo", "param_type")],
+ ),
+ # =========================================================================
+ # JavaScript — _ts_head_type_identifier (no type syntax to feed it)
+ # =========================================================================
+ ("javascript", "js", "no-type-annotations", "function f(a) {}\n", []),
+ # =========================================================================
+ # Java — _java_head_type_identifier
+ # =========================================================================
+ ("java", "java", "plain", "class Probe {\n void m(Bar a) {}\n}\n", [("Bar", "param_type")]),
+ (
+ "java",
+ "java",
+ "generic",
+ "class Probe {\n void m(List<Foo> a) {}\n}\n",
+ [("Foo", "param_type")],
+ ),
+ (
+ "java",
+ "java",
+ "qualified",
+ "class Probe {\n void m(com.x.y.Zeta a) {}\n}\n",
+ [("Zeta", "param_type")],
+ ),
+ (
+ "java",
+ "java",
+ "qualified-single-upper",
+ # Defect: the qualifier-stripped rightmost segment is a real class
+ # name (Z), but the single-uppercase-letter heuristic (meant for
+ # generic params like T/K/V) fires on it anyway and drops it.
+ "class Probe {\n void m(com.x.y.Z a) {}\n}\n",
+ [],
+ ),
+ ("java", "java", "array-wrapper", "class Probe {\n void m(Foo[] a) {}\n}\n", [("Foo", "param_type")]),
+ ("java", "java", "builtin-int", "class Probe {\n void m(int a) {}\n}\n", []),
+ ("java", "java", "builtin-String", "class Probe {\n void m(String a) {}\n}\n", []),
+ ("java", "java", "single-upper-generic-param", "class Probe {\n void m(T a) {}\n}\n", []),
+ # =========================================================================
+ # Kotlin — _kotlin_head_type_identifier
+ # =========================================================================
+ ("kotlin", "kt", "plain-ctor-param", "class Probe(val a: Bar)\n", [("Bar", "ctor_param")]),
+ (
+ "kotlin",
+ "kt",
+ "generic-ctor-param",
+ "class Probe(val a: List<Foo>)\n",
+ [("Foo", "ctor_param")],
+ ),
+ (
+ "kotlin",
+ "kt",
+ "qualified-ctor-param",
+ "class Probe(val a: com.x.Zeta)\n",
+ [("Zeta", "ctor_param")],
+ ),
+ (
+ "kotlin",
+ "kt",
+ "qualified-single-upper-ctor-param",
+ # Defect: same single-uppercase-letter false positive as Java, on
+ # the rightmost segment of a qualified name.
+ "class Probe(val a: com.x.Z)\n",
+ [],
+ ),
+ ("kotlin", "kt", "nullable-wrapper", "class Probe(val a: Foo?)\n", [("Foo", "ctor_param")]),
+ ("kotlin", "kt", "builtin-Int", "class Probe(val a: Int)\n", []),
+ ("kotlin", "kt", "builtin-Unit-return", "fun f(): Unit {}\n", []),
+ ("kotlin", "kt", "single-upper-generic-param", "class Probe(val a: T)\n", []),
+ (
+ "kotlin",
+ "kt",
+ "function-param-mislabeled-return-type",
+ # Not a value bug, but a visibly wrong origin tag: ``parameter`` is
+ # deliberately absent from _PARAM_ORIGIN_BY_ANCESTOR (it would
+ # collide with C#'s ctor-param walk), so a function parameter's
+ # origin falls through to the enclosing function_declaration and
+ # is tagged "return_type" even though it is a parameter.
+ "class Probe {\n fun m(a: Bar) {}\n}\n",
+ [("Bar", "return_type")],
+ ),
+ (
+ "kotlin",
+ "kt",
+ "heritage-plain-interface",
+ "interface Probe : Bar\n",
+ [("Bar", "extends")],
+ ),
+ (
+ "kotlin",
+ "kt",
+ "heritage-with-constructor-call",
+ # Defect: ``delegation_specifier (user_type)`` only matches a bare
+ # supertype name. ``Qux()`` wraps the user_type one level deeper in
+ # a constructor_invocation, so the pattern never fires — a
+ # superclass named with call syntax produces no type ref at all
+ # (heritage.extends still records it separately; this is only the
+ # file-level param.type edge).
+ "class Probe : Qux() {}\n",
+ [],
+ ),
+]
+
+
+def _parse(language: str, ext: str, source: str):
+ info = FileInfo(
+ path=f"probe.{ext}",
+ abs_path=f"/tmp/probe.{ext}",
+ language=language,
+ size_bytes=len(source),
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ return ASTParser().parse_file(info, source.encode())
+
+
+ ("language", "ext", "case_id", "source", "expected"),
+ CASES,
+ ids=[f"{c[0]}-{c[2]}" for c in CASES],
+)
+def test_type_head_identifier_for_spelling(
+ language: str,
+ ext: str,
+ case_id: str,
+ source: str,
+ expected: list[tuple[str, str]],
+) -> None:
+ parsed = _parse(language, ext, source)
+ got = [(t.type_name, t.origin) for t in parsed.type_refs]
+ assert sorted(got) == sorted(expected)