Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(graph): keep a Lombok @SuperBuilder chain going through inherited builder methods (#4837)
Swati Ahujaec3e49a64333
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing/java.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing/java.pyindex 185ad73d1..98d4be44e 100644--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing/java.py+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing/java.py@@ -5,7 +5,8 @@ from __future__ import annotationsimport posixpathimport re-from ..models import CallSite+from ..models import CallSite, Symbol+from ..return_types import declared_return_typefrom ..symbol_identity import outer_scope, symbol_id_pathfrom ..type_names import bare_type_name, strip_type_arguments, type_qualifierfrom ._shared import _FUNCTION_KINDS, _TYPE_KINDS@@ -34,6 +35,12 @@ def _header_type_parameters(header: str) -> set[str]:return names+def _self_bounded(header: str, parameter: str, owner: str) -> bool:+ """Is *parameter* declared in *header* as ``parameter extends owner<...>``?"""+ bound = rf"[<,]\s*{re.escape(parameter)}\s+extends\s+{re.escape(owner)}\s*<"+ return re.search(bound, header) is not None++class JavaTypeVisibility:"""Which type a Java spelling names from a given scope."""@@ -230,3 +237,28 @@ class JavaTypeVisibility:header = "\n".join(lines[start - 1 : end]).partition("{")[0]names.update(_header_type_parameters(header))return names++ def _returns_java_self_type(self, callee_id: str) -> bool:+ """Does *callee_id* return its class's self-bounded type parameter?++ ``B`` of ``class Builder<B extends Builder<B>>`` is the receiver's own+ type, a subclass included, which is how a fluent builder hierarchy+ keeps chaining through a method it inherits. Ceiling: a method's own+ ``<B>`` shadowing the class's is not read.+ """+ symbol = self._symbols_by_id.get(callee_id)+ if symbol is None or not symbol.parent_name:+ return False+ returned = declared_return_type(symbol.signature or "") or ""+ path = symbol_id_path(callee_id)+ owner = self._symbols_by_id.get(self._only_type_in(path, symbol.parent_name) or "")+ if owner is None or not returned.isidentifier():+ return False+ return _self_bounded(self._java_type_header(path, owner), returned, symbol.parent_name)++ def _java_type_header(self, file_path: str, symbol: Symbol) -> str:+ """A type's declaration up to its body, or the signature a synthesised one carries."""+ if "<" in (symbol.signature or ""):+ return symbol.signature or ""+ start, end = self._spans_for(file_path).get(symbol.id, (1, 0))+ return "\n".join(self._text_of(file_path).splitlines()[start - 1 : end]).partition("{")[0]diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex fde40f6aa..55439529d 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -472,6 +472,11 @@ class CallResolver(# the chain links being typed right now, which a cycle would revisit.self._chained_sites: dict[str, dict[tuple[int, str | None, str], CallReceiver]] = {}self._chain_links_in_flight: set[tuple[str, int, str | None, str]] = set()+ # Each chain link's resolved inner call, for the file being resolved: a+ # self-typed hop walks back down its chain, which would otherwise+ # re-resolve every lower link once per hop above it.+ self._chain_inner_resolved: dict[tuple[Any, ...], ResolvedCall | None] = {}+ self._chain_cycle_hits = 0self._unindexed_extensions: frozenset[str] | None = None# Barrel re-export origins: {barrel_file: {name: origin_file}}@@ -959,6 +964,7 @@ class CallResolver(def resolve_file(self, file_path: str, calls: list[CallSite]) -> list[ResolvedCall]:"""Resolve all calls in a single file to symbol-level edges."""results: list[ResolvedCall] = []+ self._chain_inner_resolved.clear()for call in calls:if not call.caller_symbol_id:@@ -1234,7 +1240,7 @@ class CallResolver(type_name = (tabledif tabled is not None- else self._callee_chain_return_type(inner_callee, inner, language)+ else self._callee_chain_return_type(file_path, call, inner, inner_callee, caller_id, language))if type_name is None:return False, None@@ -1386,21 +1392,14 @@ class CallResolver(# types is not admitted for this language.return Nonelink = (file_path, call.line, inner.receiver_name, inner.target_name)- if link in self._chain_links_in_flight:+ memo_key = (*link, inner.argument_count, caller_id)+ if memo_key in self._chain_inner_resolved:+ resolved_inner = self._chain_inner_resolved[memo_key]+ elif link in self._chain_links_in_flight:+ self._chain_cycle_hits += 1return None- inner_call = CallSite(- target_name=inner.target_name,- receiver_name=inner.receiver_name,- caller_symbol_id=caller_id,- line=call.line,- argument_count=inner.argument_count,- receiver_call=self._nested_receiver_call(file_path, call.line, inner, language),- )- self._chain_links_in_flight.add(link)- try:- resolved_inner = self._resolve_one(file_path, inner_call)- finally:- self._chain_links_in_flight.discard(link)+ else:+ resolved_inner = self._resolve_chain_link(file_path, call, inner, caller_id, language)if resolved_inner is None:return None# The overload the inner call's arguments select is the one whose type it returns.@@ -1421,11 +1420,55 @@ class CallResolver(callee_id = targetreturn callee_id+ def _resolve_chain_link(+ self,+ file_path: str,+ call: CallSite,+ inner: CallReceiver,+ caller_id: str,+ language: str,+ ) -> ResolvedCall | None:+ """Resolve a chain's inner call, remembered unless a cycle cut it short."""+ link = (file_path, call.line, inner.receiver_name, inner.target_name)+ inner_call = CallSite(+ target_name=inner.target_name,+ receiver_name=inner.receiver_name,+ caller_symbol_id=caller_id,+ line=call.line,+ argument_count=inner.argument_count,+ receiver_call=self._nested_receiver_call(file_path, call.line, inner, language),+ )+ cycles = self._chain_cycle_hits+ self._chain_links_in_flight.add(link)+ try:+ resolved = self._resolve_one(file_path, inner_call)+ finally:+ self._chain_links_in_flight.discard(link)+ if self._chain_cycle_hits == cycles:+ self._chain_inner_resolved[(*link, inner.argument_count, caller_id)] = resolved+ return resolved+def _callee_chain_return_type(- self, callee_id: str | None, inner: CallReceiver, language: str+ self,+ file_path: str,+ call: CallSite,+ inner: CallReceiver,+ callee_id: str | None,+ caller_id: str,+ language: str,) -> str | None:if callee_id is None:return None+ if language == "java" and self._returns_java_self_type(callee_id):+ # A self-bounded ``B`` is the type of whatever the call was made on.+ # Ceiling: only a chained receiver is typed; ``b.name(x).w(1)`` stops.+ nested = self._nested_receiver_call(file_path, call.line, inner, language)+ if nested is None:+ return None+ nested_callee = self._chain_inner_callee(file_path, call, nested, caller_id, language)+ return self._callee_chain_return_type(+ file_path, call, nested, nested_callee, caller_id, language+ )return self._callee_return_type(callee_id, inner.argument_count, language)def _nested_receiver_call(diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/java.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/java.pyindex 8a147d519..2e8ce29d8 100644--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/java.py+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/java.py@@ -7,6 +7,7 @@ from tree_sitter import Nodefrom ...models import HeritageRelationfrom ...type_names import bare_type_namefrom ..helpers import node_text+from ..synthetic_symbols.lombok import superbuilder_parentdef _superclass(@@ -17,13 +18,14 @@ def _superclass(if not superclass:returnparent = bare_type_name(node_text(superclass, src).strip().removeprefix("extends"))- if parent:+ if not parent:+ return+ out.append(HeritageRelation(child_name=name, parent_name=parent, kind="extends", line=line))+ builder_parent = superbuilder_parent(def_node, src, parent)+ if builder_parent is not None:out.append(HeritageRelation(- child_name=name,- parent_name=parent,- kind="extends",- line=line,+ child_name=f"{name}Builder", parent_name=builder_parent, kind="extends", line=line))diff --git a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/lombok.py b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/lombok.pyindex ed6bf72d9..5499ccf5c 100644--- a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/lombok.py+++ b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/lombok.py@@ -104,6 +104,9 @@ def _line(node: Node) -> int:return node.start_point[0] + 1+_TYPE_DECLARATIONS = frozenset(+ {"class_declaration", "interface_declaration", "enum_declaration", "record_declaration"}+)_NONE = re.compile(r"\bAccessLevel\.NONE\b|\(\s*NONE\s*\)")_XARGS = frozenset({"NoArgsConstructor", "RequiredArgsConstructor", "AllArgsConstructor"})@@ -321,16 +324,29 @@ def _emit_setter(def _emit_builder(fields: list[_Field], line: int, file_info: FileInfo, class_name: str,- out: list[Symbol],+ out: list[Symbol], *, scope: str, self_typed: bool = False,) -> None:- """``Foo.builder()``, the inner ``FooBuilder`` and one method per field."""+ """``Foo.builder()``, the inner ``FooBuilder`` and one method per field.++ A ``@SuperBuilder`` builder is generic in the builder it returns, as+ Lombok writes it, so a subclass builder's chain keeps its own type+ through a method it inherits.+ """builder_class = f"{class_name}Builder"- out.append(build_synthetic_symbol(+ header = builder_class+ returns = builder_class+ if self_typed:+ header = f"{builder_class}<C extends {class_name}, B extends {builder_class}<C, B>>"+ returns = "B"+ builder = build_synthetic_symbol(name=builder_class, kind="class",- signature=f"class {builder_class}",+ signature=f"class {header}",start_line=line, end_line=line,file_info=file_info, parent_name=class_name,- ))+ )+ # A member type's id names every enclosing type, as a written one's does.+ builder.id = f"{file_info.path}::{scope}::{builder_class}"+ out.append(builder)_add(out, file_info, name="builder", kind="method",parent=class_name, line=line,signature=f"builder() -> {builder_class}")@@ -339,7 +355,7 @@ def _emit_builder(continue_add(out, file_info, name=field.name, kind="method",parent=builder_class, line=field.name_line,- signature=f"{field.name}({field.type_text or 'Object'} {field.name}) -> {builder_class}")+ signature=f"{field.name}({field.type_text or 'Object'} {field.name}) -> {returns}")_add(out, file_info, name="build", kind="method",parent=builder_class, line=line,signature=f"build() -> {class_name}")@@ -348,6 +364,19 @@ def _emit_builder(signature="toString() -> String")+def _type_scope(class_node: Node, src: str) -> str:+ """``Outer::Inner`` for *class_node* and every type declared around it."""+ names: list[str] = []+ node: Node | None = class_node+ while node is not None:+ if node.type in _TYPE_DECLARATIONS:+ name_node = node.child_by_field_name("name")+ if name_node is not None:+ names.append(node_text(name_node, src).strip())+ node = node.parent+ return "::".join(reversed(names))++def _emit_for_class(class_node: Node, src: str, file_info: FileInfo, out: list[Symbol]) -> None:@@ -371,7 +400,8 @@ def _emit_for_class(_emit_constructors(class_node, annotations, fields, file_info, class_name, line, out)if "Builder" in annotations or "SuperBuilder" in annotations:_emit_builder(fields, _ann_line(annotations, ("Builder", "SuperBuilder"), line),- file_info, class_name, out)+ file_info, class_name, out, scope=_type_scope(class_node, src),+ self_typed="SuperBuilder" in annotations)# Logger field: only one logger annotation per class is valid.for ann, logger_type in _TYPE_LOGGER_ANNOTATIONS.items():if ann in annotations:@@ -442,3 +472,17 @@ def lombok_synthetic_symbols(_emit_for_class(node, src, file_info, out)stack.extend(node.children)return out+++def superbuilder_parent(class_node: Node, src: str, parent: str) -> str | None:+ """The builder ``@SuperBuilder`` on *class_node* extends: its superclass *parent*'s.++ Lombok requires the superclass to carry ``@SuperBuilder`` too, so its+ builder exists wherever the class compiles.+ """+ if "lombok" not in src:+ return None+ modifiers = _modifiers(class_node)+ if modifiers is None or "SuperBuilder" not in _annotation_nodes(modifiers, src):+ return None+ return f"{parent}Builder"diff --git a/tests/unit/ingestion/test_lombok_synthesis.py b/tests/unit/ingestion/test_lombok_synthesis.pyindex 9c5f84030..1cd16caea 100644--- a/tests/unit/ingestion/test_lombok_synthesis.py+++ b/tests/unit/ingestion/test_lombok_synthesis.py@@ -361,3 +361,151 @@ class TestLombokCallEdges:assert "src/Child.java::Child::name" in calleesassert "src/Dto.java::DtoBuilder::label" in calleesassert "src/Dto.java::DtoBuilder::build" in callees+++def _resolve_with_heritage(tmp_path: Path, files: dict[str, str], caller_file: str) -> list[str]:+ """Callees of *caller_file*, with heritage resolved as the graph builder does."""+ from repowise.core.ingestion.call_resolver import CallResolver+ from repowise.core.ingestion.heritage_resolver import HeritageResolver++ parsed = {}+ for rel, src in files.items():+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)+ parsed[rel] = _parse_full(tmp_path, rel, src)+ imports: dict[str, set[str]] = {p: set() for p in parsed}+ parents: dict[str, set[str]] = {}+ for rel, pf in parsed.items():+ for rh in HeritageResolver(parsed, imports).resolve_file(rel, pf.heritage):+ parents.setdefault(rh.child_id, set()).add(rh.parent_id)+ resolver = CallResolver(parsed, imports, repo_path=str(tmp_path), heritage_parents=parents)+ return sorted(rc.callee_id for rc in resolver.resolve_file(caller_file, parsed[caller_file].calls))+++class TestSuperBuilder:+ """A ``@SuperBuilder`` subclass builder extends its superclass's, generic in itself."""++ _BASE = (+ "package p;\nimport lombok.experimental.SuperBuilder;\n"+ "@SuperBuilder\npublic class Base {\n private String name;\n}\n"+ )+ _SUB = (+ "package p;\nimport lombok.experimental.SuperBuilder;\n"+ "@SuperBuilder\npublic class Sub extends Base {\n private int w;\n}\n"+ )++ def test_the_subclass_builder_extends_the_superclass_builder(self, tmp_path: Path) -> None:+ pf = _parse_full(tmp_path, "Sub.java", self._SUB)+ assert [(h.child_name, h.parent_name) for h in pf.heritage] == [+ ("Sub", "Base"),+ ("SubBuilder", "BaseBuilder"),+ ]++ def test_a_plain_builder_adds_no_builder_heritage(self, tmp_path: Path) -> None:+ src = self._SUB.replace("SuperBuilder", "Builder").replace(".experimental", "")+ pf = _parse_full(tmp_path, "Sub.java", src)+ assert [(h.child_name, h.parent_name) for h in pf.heritage] == [("Sub", "Base")]++ def test_a_chain_keeps_the_subclass_builder_through_an_inherited_method(+ self, tmp_path: Path+ ) -> None:+ use = (+ "package p;\nclass Use {\n Sub u() {\n"+ " return Sub.builder().name(\"a\").w(1).build();\n }\n}\n"+ )+ files = {"p/Base.java": self._BASE, "p/Sub.java": self._SUB, "p/Use.java": use}+ assert _resolve_with_heritage(tmp_path, files, "p/Use.java") == [+ "p/Base.java::BaseBuilder::name",+ "p/Sub.java::Sub::builder",+ "p/Sub.java::SubBuilder::build",+ "p/Sub.java::SubBuilder::w",+ ]++ def test_a_nested_builder_is_a_member_type_of_its_host(self, tmp_path: Path) -> None:+ """Two outer types nest a ``Create``; each chain stays on its own host's builders."""+ outer = (+ "package p;\nimport lombok.experimental.SuperBuilder;\n"+ "public interface {o} {{\n"+ " @SuperBuilder\n final class Create extends UpdateCreate {{\n"+ " private String key;\n }}\n"+ " @SuperBuilder\n class UpdateCreate {{\n private String colour;\n }}\n"+ " static Object u() {{\n"+ " return Create.builder().colour(\"c\").key(\"k\").build();\n }}\n}}\n"+ )+ files = {"p/AMgmt.java": outer.format(o="AMgmt"), "p/BMgmt.java": outer.format(o="BMgmt")}+ pf = _parse_full(tmp_path, "AMgmt.java", files["p/AMgmt.java"])+ assert "AMgmt.java::AMgmt::Create::CreateBuilder" in {s.id for s in pf.symbols}+ callees = _resolve_with_heritage(tmp_path, files, "p/AMgmt.java")+ assert "p/AMgmt.java::UpdateCreateBuilder::colour" in callees+ assert "p/AMgmt.java::CreateBuilder::key" in callees+ assert "p/AMgmt.java::CreateBuilder::build" in callees+ assert not any(c.startswith("p/BMgmt.java") for c in callees), callees+++class TestSelfBoundedReturn:+ """``B`` of ``Base<B extends Base<B>>`` is the receiver's own type in a chain."""++ def test_a_self_bounded_return_keeps_the_receivers_type(self, tmp_path: Path) -> None:+ outer = (+ "package p;\npublic class Outer {\n"+ " public abstract static class Base<B extends Base<B>> {\n"+ " public B name(String n) { return null; }\n }\n"+ " public static class Sub extends Base<Sub> {\n"+ " public Sub extra(int x) { return this; }\n }\n"+ " public static Sub sub() { return new Sub(); }\n}\n"+ )+ use = "package p;\nclass Use {\n void go() {\n Outer.sub().name(\"a\").extra(1);\n }\n}\n"+ files = {"p/Outer.java": outer, "p/Use.java": use}+ assert _resolve_with_heritage(tmp_path, files, "p/Use.java") == [+ "p/Outer.java::Base::name",+ "p/Outer.java::Outer::sub",+ "p/Outer.java::Sub::extra",+ ]++ def test_a_type_parameter_bounded_by_another_type_is_not_the_receiver(+ self, tmp_path: Path+ ) -> None:+ """``T extends Other<T>`` is not ``Base``'s self type, so the chain stops."""+ outer = (+ "package p;\npublic class Outer {\n"+ " public static class Other<T> {}\n"+ " public abstract static class Base<B extends Other<B>> {\n"+ " public B name(String n) { return null; }\n }\n"+ " public static class Sub extends Base<Sub> {\n"+ " public Sub extra(int x) { return this; }\n }\n"+ " public static Sub sub() { return new Sub(); }\n}\n"+ )+ use = "package p;\nclass Use {\n void go() {\n Outer.sub().name(\"a\").extra(1);\n }\n}\n"+ files = {"p/Outer.java": outer, "p/Use.java": use}+ assert "p/Outer.java::Sub::extra" not in _resolve_with_heritage(tmp_path, files, "p/Use.java")+++def test_a_long_superbuilder_chain_resolves_each_link_once(tmp_path: Path, monkeypatch) -> None:+ """Each self-typed hop walks back down its chain; a remembered link keeps that linear."""+ from repowise.core.ingestion.call_resolver import CallResolver++ fields = [f"f{i}" for i in range(24)]+ base = (+ "package p;\nimport lombok.experimental.SuperBuilder;\n@SuperBuilder\npublic class Base {\n"+ + "".join(f" private int {f};\n" for f in fields)+ + "}\n"+ )+ sub = (+ "package p;\nimport lombok.experimental.SuperBuilder;\n"+ "@SuperBuilder\npublic class Sub extends Base {\n private int w;\n}\n"+ )+ chain = "".join(f".{f}({i})" for i, f in enumerate(fields))+ use = f"package p;\nclass Use {{\n Sub u() {{\n return Sub.builder(){chain}.w(1).build();\n }}\n}}\n"+ calls = 0+ resolve_one = CallResolver._resolve_one++ def counted(self, *args):+ nonlocal calls+ calls += 1+ return resolve_one(self, *args)++ monkeypatch.setattr(CallResolver, "_resolve_one", counted)+ files = {"p/Base.java": base, "p/Sub.java": sub, "p/Use.java": use}+ callees = _resolve_with_heritage(tmp_path, files, "p/Use.java")+ assert {f"p/Base.java::BaseBuilder::{f}" for f in fields} <= set(callees)+ assert "p/Sub.java::SubBuilder::build" in callees+ assert calls < 20 * len(fields)