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): place Lombok accessors where javac does and type their returns (#4819)

Swati Ahujac2880dcbc014
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.py
index 1d1c0ceed..ed6bf72d9 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
@@ -28,15 +28,22 @@ Supported annotations:
@XSlf4j / @CommonsLog / @Flogger — ``log`` field
@UtilityClass — private ctor + ``log`` not added
@With — withX(T) per field
+ @Accessors(fluent, chain) - accessor names and setter returns
Field-level:
@Getter / @Setter / @With — same shape, per single field
-Field-level annotations override type-level ones (more restrictive wins).
+Field-level annotations override type-level ones, and ``AccessLevel.NONE``
+switches an accessor off. Each member sits on the line javac's Lombok gives
+it, so a call edge keys where a compiler-backed index puts it: a getter on
+its field (or on the field's ``@Getter``), a setter on the ``@Setter`` /
+``@Data`` that asked for it, a builder method on its field, and the rest
+on the class annotation that generates them. Constructors stay on the class.
"""
from __future__ import annotations
-from typing import TYPE_CHECKING
+import re
+from typing import TYPE_CHECKING, NamedTuple
from ...models import FileInfo, Symbol
from ..helpers import node_text
@@ -61,11 +68,6 @@ _TYPE_ANNOTATIONS_OF_INTEREST = frozenset(
}
)
-# Field-level annotations override the type-level set for that one field.
-_FIELD_ANNOTATIONS_OF_INTEREST = frozenset(
- {"Getter", "Setter", "With", "ToString.Exclude", "EqualsAndHashCode.Exclude"}
-)
-
_TYPE_LOGGER_ANNOTATIONS = {
"Slf4j": "Logger",
"XSlf4j": "XLogger",
@@ -77,85 +79,118 @@ _TYPE_LOGGER_ANNOTATIONS = {
}
-def _bare_annotation_names(modifiers_node: Node, src: str) -> set[str]:
- """Return the bare names of every annotation on a modifiers node.
+def _annotation_nodes(modifiers_node: Node, src: str) -> dict[str, Node]:
+ """Map the bare name of every annotation on a modifiers node to its node.
``@lombok.Data`` / ``@Data`` / ``@Data(staticConstructor="of")`` all
- fold to ``"Data"``.
+ fold to ``"Data"``. The first annotation of a name wins.
"""
- names: set[str] = set()
+ found: dict[str, Node] = {}
for child in modifiers_node.children:
if child.type not in ("marker_annotation", "annotation"):
continue
for sub in child.children:
if sub.type in ("identifier", "scoped_identifier"):
- text = node_text(sub, src).strip()
- names.add(text.split(".")[-1])
+ found.setdefault(node_text(sub, src).strip().split(".")[-1], child)
break
- return names
+ return found
-def _field_info(field_node: Node, src: str) -> tuple[str, str, bool, set[str]] | None:
- """Return (field_name, type_text, is_final, field_annotations) or None.
+def _modifiers(decl_node: Node) -> Node | None:
+ return next((c for c in decl_node.children if c.type == "modifiers"), None)
- A single ``field_declaration`` can declare multiple variables
- (``int x, y;``) — we return the first; callers iterate by walking
- the AST themselves where it matters.
- """
- type_text = ""
- is_final = False
- field_annotations: set[str] = set()
- name: str | None = None
- for child in field_node.children:
- if child.type == "modifiers":
- for sub in child.children:
- if sub.type == "final":
- is_final = True
- elif sub.type in ("marker_annotation", "annotation"):
- for leaf in sub.children:
- if leaf.type in ("identifier", "scoped_identifier"):
- field_annotations.add(
- node_text(leaf, src).strip().split(".")[-1]
- )
- break
- elif child.type == "variable_declarator":
- for leaf in child.children:
- if leaf.type == "identifier" and name is None:
- name = node_text(leaf, src).strip()
- break
- # Whatever this node is, it sits where the type goes —
- # type_identifier / generic_type / scoped_type_identifier /
- # array_type / annotated_type / integral_type / void_type /
- # boolean_type / floating_point_type. Capture its text.
- elif child.type not in (";", ",") and not type_text:
- type_text = node_text(child, src).strip()
+def _line(node: Node) -> int:
+ return node.start_point[0] + 1
- if not name:
+
+_NONE = re.compile(r"\bAccessLevel\.NONE\b|\(\s*NONE\s*\)")
+_XARGS = frozenset({"NoArgsConstructor", "RequiredArgsConstructor", "AllArgsConstructor"})
+
+
+def _access_none(annotation: Node | None, src: str) -> bool:
+ """``@Getter(AccessLevel.NONE)`` switches the accessor off."""
+ return annotation is not None and _NONE.search(node_text(annotation, src)) is not None
+
+
+def _accessors_flag(annotations: dict[str, Node], src: str, flag: str) -> bool | None:
+ """An ``@Accessors`` flag as written, or None when it is not written."""
+ accessors = annotations.get("Accessors")
+ if accessors is None:
return None
- return name, type_text, is_final, field_annotations
+ found = re.search(flag + r"\s*=\s*(true|false)", node_text(accessors, src))
+ return None if found is None else found.group(1) == "true"
+
+
+def _accessors_style(
+ field_ann: dict[str, Node], class_ann: dict[str, Node], src: str
+) -> tuple[bool, bool]:
+ """(fluent, chain): a field's ``@Accessors`` wins, and chain follows fluent unless written."""
+ owner = field_ann if "Accessors" in field_ann else class_ann
+ fluent = bool(_accessors_flag(owner, src, "fluent"))
+ chain = _accessors_flag(owner, src, "chain")
+ return fluent, fluent if chain is None else chain
+
+
+class _Field(NamedTuple):
+ name: str
+ type_text: str
+ is_final: bool
+ is_static: bool
+ # Bare annotation name -> annotation node, for this field only.
+ annotations: dict[str, Node]
+ # Line of the declarator's name, where class-level getters sit.
+ name_line: int
+ # A final field with an initializer takes no constructor or builder slot.
+ initialized: bool
+
+
+def _field_infos(field_node: Node, src: str) -> list[_Field]:
+ """One entry per declarator, so ``int x, y;`` yields both fields."""
+ modifiers = _modifiers(field_node)
+ kinds = {c.type for c in modifiers.children} if modifiers is not None else set()
+ annotations = _annotation_nodes(modifiers, src) if modifiers is not None else {}
+ type_node = field_node.child_by_field_name("type")
+ type_text = node_text(type_node, src).strip() if type_node is not None else ""
+ out: list[_Field] = []
+ for child in field_node.children:
+ if child.type != "variable_declarator":
+ continue
+ name_node = child.child_by_field_name("name")
+ if name_node is None:
+ continue
+ out.append(_Field(
+ node_text(name_node, src).strip(), type_text, "final" in kinds,
+ "static" in kinds, annotations, _line(name_node),
+ child.child_by_field_name("value") is not None,
+ ))
+ return out
-def _class_fields(class_node: Node, src: str) -> list[tuple[str, str, bool, set[str]]]:
- """Return a list of (name, type_text, is_final, annotations) per declared field."""
- fields: list[tuple[str, str, bool, set[str]]] = []
+def _class_fields(class_node: Node, src: str) -> list[_Field]:
+ """Every field declared directly in a class or enum body."""
body = class_node.child_by_field_name("body")
if body is None:
- for child in class_node.children:
- if child.type in ("class_body", "interface_body", "record_body"):
- body = child
- break
- if body is None:
- return fields
+ return []
+ members = list(body.children)
+ # An enum's fields sit after its constants, in one declarations node.
for child in body.children:
- if child.type != "field_declaration":
- continue
- info = _field_info(child, src)
- if info is not None:
- fields.append(info)
+ if child.type == "enum_body_declarations":
+ members.extend(child.children)
+ fields: list[_Field] = []
+ for child in members:
+ if child.type == "field_declaration":
+ fields.extend(f for f in _field_infos(child, src) if not f.name.startswith("$"))
return fields
+def _declares_constructor(class_node: Node) -> bool:
+ body = class_node.child_by_field_name("body")
+ return body is not None and any(
+ c.type == "constructor_declaration" for c in body.children
+ )
+
+
def _pascal_case(name: str) -> str:
stripped = name.lstrip("_")
if not stripped:
@@ -163,22 +198,27 @@ def _pascal_case(name: str) -> str:
return stripped[0].upper() + stripped[1:]
-def _getter_name(field_name: str, field_type: str) -> str:
- """``boolean active`` → ``isActive``; otherwise ``getX``.
+def _boolean_is_name(field: _Field) -> bool:
+ """A primitive ``boolean isActive`` keeps its name as the getter."""
+ return field.type_text == "boolean" and re.match(r"is[A-Z]", field.name) is not None
- Lombok's actual rule is fancier (handles ``is`` prefixes, ``Boolean``
- boxed) but this approximation captures the high-value cases.
- """
- pascal = _pascal_case(field_name)
+
+def _getter_name(field: _Field, fluent: bool) -> str:
+ """``boolean active`` → ``isActive``; otherwise ``getX``."""
+ if fluent or _boolean_is_name(field):
+ return field.name
+ pascal = _pascal_case(field.name)
if not pascal:
return ""
- if field_type == "boolean":
- return f"is{pascal}"
- return f"get{pascal}"
+ return f"is{pascal}" if field.type_text == "boolean" else f"get{pascal}"
-def _setter_name(field_name: str) -> str:
- return f"set{_pascal_case(field_name)}"
+def _setter_name(field: _Field, fluent: bool) -> str:
+ if fluent:
+ return field.name
+ if _boolean_is_name(field):
+ return f"set{field.name[2:]}"
+ return f"set{_pascal_case(field.name)}"
def _with_name(field_name: str) -> str:
@@ -200,6 +240,114 @@ def _add(out: list[Symbol], file_info: FileInfo, *, name: str, kind: str,
))
+def _ann_line(annotations: dict[str, Node], names: tuple[str, ...], default: int) -> int:
+ """Line of the first of *names* present, else *default*."""
+ for name in names:
+ if name in annotations:
+ return _line(annotations[name])
+ return default
+
+
+def _accessor_line(field: _Field, own: Node | None, class_line: int, fluent: bool) -> int:
+ """On the field name for a fluent accessor (spelled like the field),
+ else on the field annotation that asked for it, else on the class-level
+ default."""
+ if fluent:
+ return field.name_line
+ if own is not None:
+ return _line(own)
+ return class_line
+
+
+def _class_level(
+ annotations: dict[str, Node], explicit: str, implied_by: tuple[str, ...], src: str
+) -> bool:
+ """An explicit class ``@Getter`` / ``@Setter`` overrides what @Data or @Value imply."""
+ if explicit in annotations:
+ return not _access_none(annotations[explicit], src)
+ return any(name in annotations for name in implied_by)
+
+
+def _wanted(own: Node | None, class_level: bool, field: _Field, src: str) -> bool:
+ """A field annotation decides alone; a class one skips static fields."""
+ if own is not None:
+ return not _access_none(own, src)
+ return class_level and not field.is_static
+
+
+def _emit_accessors(
+ fields: list[_Field], annotations: dict[str, Node], src: str,
+ file_info: FileInfo, class_name: str, line: int, out: list[Symbol],
+) -> None:
+ """Per-field getters, setters and withers."""
+ is_value = "Value" in annotations
+
+ class_get = _class_level(annotations, "Getter", ("Data", "Value"), src)
+ class_set = _class_level(annotations, "Setter", ("Data",), src) and not is_value
+ class_with = _class_level(annotations, "With", (), src)
+ set_line = _ann_line(annotations, ("Setter", "Data"), line)
+ with_line = _ann_line(annotations, ("With",), line)
+ for field in fields:
+ fluent, chain = _accessors_style(field.annotations, annotations, src)
+ own = field.annotations.get("Getter")
+ if _wanted(own, class_get, field, src):
+ name = _getter_name(field, fluent)
+ _add(out, file_info, name=name, kind="method", parent=class_name,
+ line=_accessor_line(field, own, field.name_line, fluent),
+ signature=f"{name}() -> {field.type_text or 'Object'}")
+ own = field.annotations.get("Setter")
+ if not field.is_final and not is_value and _wanted(own, class_set, field, src):
+ _emit_setter(field, own, set_line, (fluent, chain), file_info, class_name, out)
+ own = field.annotations.get("With")
+ if _wanted(own, class_with, field, src):
+ name = _with_name(field.name)
+ _add(out, file_info, name=name, kind="method", parent=class_name,
+ line=_accessor_line(field, own, with_line, False),
+ signature=f"{name}({field.type_text or 'Object'} {field.name}) -> {class_name}")
+
+
+def _emit_setter(
+ field: _Field, own: Node | None, class_line: int, style: tuple[bool, bool],
+ file_info: FileInfo, class_name: str, out: list[Symbol],
+) -> None:
+ fluent, chain = style
+ name = _setter_name(field, fluent)
+ # A chained setter returns its object, so a call chain can go on.
+ returns = class_name if chain else "void"
+ _add(out, file_info, name=name, kind="method", parent=class_name,
+ line=_accessor_line(field, own, class_line, fluent),
+ signature=f"{name}({field.type_text or 'Object'} {field.name}) -> {returns}")
+
+
+def _emit_builder(
+ fields: list[_Field], line: int, file_info: FileInfo, class_name: str,
+ out: list[Symbol],
+) -> None:
+ """``Foo.builder()``, the inner ``FooBuilder`` and one method per field."""
+ builder_class = f"{class_name}Builder"
+ out.append(build_synthetic_symbol(
+ name=builder_class, kind="class",
+ signature=f"class {builder_class}",
+ start_line=line, end_line=line,
+ file_info=file_info, parent_name=class_name,
+ ))
+ _add(out, file_info, name="builder", kind="method",
+ parent=class_name, line=line,
+ signature=f"builder() -> {builder_class}")
+ for field in fields:
+ if field.is_static or (field.is_final and field.initialized):
+ 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}")
+ _add(out, file_info, name="build", kind="method",
+ parent=builder_class, line=line,
+ signature=f"build() -> {class_name}")
+ _add(out, file_info, name="toString", kind="method",
+ parent=builder_class, line=line,
+ signature="toString() -> String")
+
+
def _emit_for_class(
class_node: Node, src: str, file_info: FileInfo, out: list[Symbol]
) -> None:
@@ -209,141 +357,88 @@ def _emit_for_class(
class_name = node_text(name_node, src).strip()
if not class_name:
return
- line = class_node.start_point[0] + 1
-
- annotations: set[str] = set()
- for child in class_node.children:
- if child.type == "modifiers":
- annotations |= _bare_annotation_names(child, src)
- if not annotations & _TYPE_ANNOTATIONS_OF_INTEREST and not any(
- a in _TYPE_LOGGER_ANNOTATIONS for a in annotations
- ):
- return
-
- is_data = "Data" in annotations
- is_value = "Value" in annotations
- has_getter = "Getter" in annotations or is_data or is_value
- has_setter = "Setter" in annotations or is_data # @Value is immutable — no setters
- has_to_string = "ToString" in annotations or is_data or is_value
- has_eq = "EqualsAndHashCode" in annotations or is_data or is_value
- has_rac = "RequiredArgsConstructor" in annotations or is_data
- has_aac = "AllArgsConstructor" in annotations or is_value
- has_noac = "NoArgsConstructor" in annotations
- has_builder = "Builder" in annotations or "SuperBuilder" in annotations
- has_with = "With" in annotations
- is_utility = "UtilityClass" in annotations
+ line = _line(class_node)
+ modifiers = _modifiers(class_node)
+ annotations = _annotation_nodes(modifiers, src) if modifiers is not None else {}
fields = _class_fields(class_node, src)
+ # Field-level accessors need no class annotation.
+ _emit_accessors(fields, annotations, src, file_info, class_name, line, out)
+ if not annotations.keys() & _TYPE_ANNOTATIONS_OF_INTEREST:
+ return
- # Per-field getters/setters/withers.
- for field_name, field_type, _is_final, field_annotations in fields:
- field_get = "Getter" in field_annotations or has_getter
- field_set = "Setter" in field_annotations or has_setter
- field_with = "With" in field_annotations or has_with
- if field_get:
- _add(out, file_info, name=_getter_name(field_name, field_type),
- kind="method", parent=class_name, line=line,
- signature=f"public {field_type or 'Object'} {_getter_name(field_name, field_type)}()")
- if field_set and not is_value:
- _add(out, file_info, name=_setter_name(field_name),
- kind="method", parent=class_name, line=line,
- signature=f"public void {_setter_name(field_name)}({field_type or 'Object'})")
- if field_with:
- _add(out, file_info, name=_with_name(field_name),
- kind="method", parent=class_name, line=line,
- signature=f"public {class_name} {_with_name(field_name)}({field_type or 'Object'})")
-
- if has_to_string:
- _add(out, file_info, name="toString", kind="method",
- parent=class_name, line=line,
- signature="public String toString()")
- if has_eq:
- _add(out, file_info, name="equals", kind="method",
- parent=class_name, line=line,
- signature="public boolean equals(Object)")
- _add(out, file_info, name="hashCode", kind="method",
- parent=class_name, line=line,
- signature="public int hashCode()")
- _add(out, file_info, name="canEqual", kind="method",
- parent=class_name, line=line,
- signature="protected boolean canEqual(Object)")
-
- if has_rac:
- # @RequiredArgsConstructor: final + @NonNull fields. We don't know
- # @NonNull from the source without parsing all annotations, so use
- # `is_final` as the proxy — covers the dominant Spring DI case
- # of ``private final Service service``.
- required = [
- (n, t) for (n, t, fin, _) in fields if fin
- ]
- _add(out, file_info, name=class_name, kind="function",
- parent=class_name, line=line,
- signature=f"public {class_name}({', '.join(f'{t} {n}' for n, t in required)})")
- if has_aac:
- all_params = [(n, t) for (n, t, _, _) in fields]
- _add(out, file_info, name=class_name, kind="function",
- parent=class_name, line=line,
- signature=f"public {class_name}({', '.join(f'{t} {n}' for n, t in all_params)})")
- if has_noac:
- _add(out, file_info, name=class_name, kind="function",
- parent=class_name, line=line,
- signature=f"public {class_name}()")
-
- if has_builder:
- builder_class = f"{class_name}Builder"
- # The builder class itself
- out.append(build_synthetic_symbol(
- name=builder_class, kind="class",
- signature=f"public static class {builder_class}",
- start_line=line, end_line=line,
- file_info=file_info, parent_name=class_name,
- ))
- # Static factory on the host class
- _add(out, file_info, name="builder", kind="method",
- parent=class_name, line=line,
- signature=f"public static {builder_class} builder()")
- # Builder-per-field methods + build()
- for field_name, field_type, _is_final, _ann in fields:
- _add(out, file_info, name=field_name, kind="method",
- parent=builder_class, line=line,
- signature=f"public {builder_class} {field_name}({field_type or 'Object'})")
- _add(out, file_info, name="build", kind="method",
- parent=builder_class, line=line,
- signature=f"public {class_name} build()")
- _add(out, file_info, name="toString", kind="method",
- parent=builder_class, line=line,
- signature="public String toString()")
-
- if is_utility:
- # Lombok turns the class into a final utility — emit a private
- # default constructor so the class is "constructed" somewhere.
- _add(out, file_info, name=class_name, kind="function",
- parent=class_name, line=line,
- signature=f"private {class_name}()")
-
- # Logger field — only one logger annotation per class is valid.
+ _emit_object_methods(annotations, file_info, class_name, line, out)
+ _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)
+ # Logger field: only one logger annotation per class is valid.
for ann, logger_type in _TYPE_LOGGER_ANNOTATIONS.items():
if ann in annotations:
_add(out, file_info, name="log", kind="variable",
- parent=class_name, line=line,
+ parent=class_name, line=_line(annotations[ann]),
signature=f"private static final {logger_type} log")
break
+def _emit_object_methods(
+ annotations: dict[str, Node], file_info: FileInfo, class_name: str, line: int,
+ out: list[Symbol],
+) -> None:
+ """toString, equals, hashCode and canEqual, on the annotation that asks for them."""
+ implied = "Data" in annotations or "Value" in annotations
+ if "ToString" in annotations or implied:
+ _add(out, file_info, name="toString", kind="method", parent=class_name,
+ line=_ann_line(annotations, ("ToString", "Data", "Value"), line),
+ signature="toString() -> String")
+ if "EqualsAndHashCode" in annotations or implied:
+ eq_line = _ann_line(annotations, ("EqualsAndHashCode", "Data", "Value"), line)
+ for name, signature in (
+ ("equals", "equals(Object o) -> boolean"),
+ ("hashCode", "hashCode() -> int"),
+ ("canEqual", "canEqual(Object other) -> boolean"),
+ ):
+ _add(out, file_info, name=name, kind="method", parent=class_name,
+ line=eq_line, signature=signature)
+
+
+def _emit_constructors(
+ class_node: Node, annotations: dict[str, Node], fields: list[_Field],
+ file_info: FileInfo, class_name: str, line: int, out: list[Symbol],
+) -> None:
+ """Generated constructors, on the class line where an index keys them."""
+ slots = [f for f in fields if not f.is_static and not (f.is_final and f.initialized)]
+ # @Data and @Value add theirs only when nothing else declares one.
+ implied = not _declares_constructor(class_node) and not annotations.keys() & _XARGS
+ params: list[list[_Field]] = []
+ if "RequiredArgsConstructor" in annotations or ("Data" in annotations and implied):
+ # @NonNull is not read, so final stands in for "required": the
+ # dominant Spring DI shape is ``private final Service service``.
+ params.append([f for f in slots if f.is_final])
+ if "AllArgsConstructor" in annotations or ("Value" in annotations and implied):
+ params.append(slots)
+ if "NoArgsConstructor" in annotations or "UtilityClass" in annotations:
+ # A @UtilityClass gets a private one, so the class is constructed somewhere.
+ params.append([])
+ for group in params:
+ _add(out, file_info, name=class_name, kind="function", parent=class_name, line=line,
+ signature=f"{class_name}({', '.join(f'{f.type_text} {f.name}' for f in group)})")
+
+
def lombok_synthetic_symbols(
root: Node, src: str, file_info: FileInfo
) -> list[Symbol]:
- """Emit synthetic symbols for Lombok-annotated Java classes."""
- # Cheap reject path: if the source doesn't even mention `@`, there
- # can't be any annotations.
- if "@" not in src:
+ """Emit synthetic symbols for Lombok-annotated Java classes and enums."""
+ # Lombok annotations need a ``lombok`` import or a qualified name, so a
+ # same-named annotation from another library generates nothing.
+ if "lombok" not in src:
return []
out: list[Symbol] = []
stack: list[Node] = [root]
while stack:
node = stack.pop()
- if node.type == "class_declaration":
+ if node.type in ("class_declaration", "enum_declaration"):
_emit_for_class(node, src, file_info, out)
stack.extend(node.children)
return out
diff --git a/tests/unit/ingestion/test_lombok_synthesis.py b/tests/unit/ingestion/test_lombok_synthesis.py
index b9c94cc89..9c5f84030 100644
--- a/tests/unit/ingestion/test_lombok_synthesis.py
+++ b/tests/unit/ingestion/test_lombok_synthesis.py
@@ -5,6 +5,8 @@ from __future__ import annotations
from datetime import datetime
from pathlib import Path
+import pytest
+
from repowise.core.ingestion.models import FileInfo
from repowise.core.ingestion.parser import parse_file
@@ -69,6 +71,23 @@ class TestLombok:
)
assert "log" in names, names
+ @pytest.mark.parametrize(
+ ("ann", "logger_type"),
+ [("Slf4j", "Logger"), ("XSlf4j", "XLogger"), ("Log4j2", "Logger"),
+ ("Log", "Logger"), ("JBossLog", "Logger"), ("CommonsLog", "Log"),
+ ("Flogger", "FluentLogger")],
+ )
+ def test_logger_only_class_keeps_its_log_field(
+ self, tmp_path: Path, ann: str, logger_type: str
+ ) -> None:
+ pf = _parse_full(
+ tmp_path, "Svc.java", f"import lombok.extern.*;\n@{ann}\npublic class Svc {{}}\n"
+ )
+ logs = [s for s in pf.symbols if s.name == "log" and s.parent_name == "Svc"]
+ assert len(logs) == 1, [s.id for s in pf.symbols]
+ assert logs[0].signature == f"private static final {logger_type} log"
+ assert logs[0].start_line == 2
+
def test_data_emits_getters_setters_toString_equals(self, tmp_path: Path) -> None:
names = _parse(
tmp_path, "Pt.java",
@@ -118,3 +137,227 @@ class TestLombok:
)
assert "getX" not in names, names
assert "log" not in names, names
+
+
+def _by_name(pf) -> dict[str, list]:
+ out: dict[str, list] = {}
+ for s in pf.symbols:
+ out.setdefault(s.name, []).append(s)
+ return out
+
+
+class TestLombokPlacement:
+ """Each generated member sits where javac's Lombok puts it, so a call
+ edge keys at the same line a compiler-backed index does."""
+
+ _ENTITY = (
+ "import lombok.*;\n" # 1
+ "@NoArgsConstructor\n" # 2
+ "public class Entity {\n" # 3
+ " @Setter\n" # 4
+ " @Getter\n" # 5
+ " @Column(name = \"status\")\n" # 6
+ " private String status;\n" # 7
+ " @Getter(AccessLevel.NONE)\n" # 8
+ " private String hidden;\n" # 9
+ " @Getter private boolean isActive;\n" # 10
+ " @Setter private boolean active2;\n" # 11
+ " private String plain;\n" # 12
+ "}\n"
+ )
+
+ def test_field_annotation_accessors_need_no_class_annotation(self, tmp_path: Path) -> None:
+ by = _by_name(_parse_full(tmp_path, "Entity.java", self._ENTITY))
+ assert by["getStatus"][0].start_line == 5
+ assert by["setStatus"][0].start_line == 4
+ assert "getHidden" not in by
+ assert "getPlain" not in by and "setPlain" not in by
+
+ def test_boolean_is_prefix(self, tmp_path: Path) -> None:
+ by = _by_name(_parse_full(tmp_path, "Entity.java", self._ENTITY))
+ assert "isActive" in by and "isIsActive" not in by
+ assert "setActive2" in by
+
+ _DATA = (
+ "import lombok.*;\n" # 1
+ "@Data\n" # 2
+ "@Builder\n" # 3
+ "@EqualsAndHashCode(callSuper = false)\n" # 4
+ "public class Dto {\n" # 5
+ " private static int counter;\n" # 6
+ " private final Long id;\n" # 7
+ " @Size(max = 3)\n" # 8
+ " private Child child;\n" # 9
+ "}\n"
+ )
+
+ def test_class_annotation_members(self, tmp_path: Path) -> None:
+ by = _by_name(_parse_full(tmp_path, "Dto.java", self._DATA))
+ # A class-level getter sits on its field's name; a setter on @Data.
+ assert by["getChild"][0].start_line == 9
+ assert by["setChild"][0].start_line == 2
+ assert by["equals"][0].start_line == 4
+ assert by["toString"][0].start_line == 2
+ assert by["builder"][0].start_line == 3
+ assert by["child"][0].start_line == 9 and by["child"][0].parent_name == "DtoBuilder"
+ # Static fields get no accessors; final fields no setter.
+ assert "getCounter" not in by and "counter" not in by
+ assert "getId" in by and "setId" not in by
+
+ def test_data_adds_no_constructor_beside_a_declared_one(self, tmp_path: Path) -> None:
+ pf = _parse_full(
+ tmp_path, "D.java",
+ "import lombok.Data;\n"
+ "@Data public class D {\n"
+ " private final Long id;\n"
+ " public D(Long id, String x) { this.id = id; }\n"
+ "}\n",
+ )
+ ctors = [s for s in pf.symbols if s.name == "D" and s.parent_name == "D"]
+ assert len(ctors) == 1 and "String x" in ctors[0].signature
+
+ def test_enum_getter(self, tmp_path: Path) -> None:
+ names = _parse(
+ tmp_path, "E.java",
+ "import lombok.Getter;\n"
+ "@Getter public enum E { A(\"a\"); private final String code; E(String c) { code = c; } }\n",
+ )
+ assert "getCode" in names, names
+
+ def test_fluent_accessors_sit_on_the_field(self, tmp_path: Path) -> None:
+ by = _by_name(_parse_full(
+ tmp_path, "B.java",
+ "import lombok.*;\n"
+ "@Accessors(fluent = true)\n"
+ "public class B {\n"
+ " @Setter\n"
+ " private Integer weight;\n"
+ "}\n",
+ ))
+ assert [s.start_line for s in by["weight"]] == [5]
+ assert by["weight"][0].signature.endswith("-> B")
+
+ def test_signatures_declare_return_types(self, tmp_path: Path) -> None:
+ by = _by_name(_parse_full(tmp_path, "Dto.java", self._DATA))
+ assert by["getChild"][0].signature == "getChild() -> Child"
+ assert by["builder"][0].signature == "builder() -> DtoBuilder"
+ assert by["child"][0].signature.endswith("-> DtoBuilder")
+ assert by["build"][0].signature == "build() -> Dto"
+
+
+class TestLombokSemantics:
+ def test_data_beside_explicit_constructor_annotations(self, tmp_path: Path) -> None:
+ pf = _parse_full(
+ tmp_path, "D.java",
+ "import lombok.*;\n"
+ "@Data @NoArgsConstructor @AllArgsConstructor\n"
+ "public class D { private final Long id; private String name; }\n",
+ )
+ sigs = sorted(s.signature for s in pf.symbols if s.name == "D" and s.parent_name == "D")
+ assert sigs == ["D()", "D(Long id, String name)"], sigs
+
+ def test_boolean_is_field_getter_sits_on_its_annotation(self, tmp_path: Path) -> None:
+ by = _by_name(_parse_full(
+ tmp_path, "A.java",
+ "import lombok.Getter;\n"
+ "public class A {\n"
+ " @Getter\n"
+ " private boolean isOpen;\n"
+ "}\n",
+ ))
+ assert [s.start_line for s in by["isOpen"] if s.kind == "method"] == [3]
+
+ def test_every_declarator_gets_accessors(self, tmp_path: Path) -> None:
+ names = _parse(
+ tmp_path, "M.java",
+ "import lombok.Getter;\n@Getter public class M { private int x, y; }\n",
+ )
+ assert "getX" in names and "getY" in names, names
+
+ def test_explicit_class_getter_none_beats_data(self, tmp_path: Path) -> None:
+ names = _parse(
+ tmp_path, "N.java",
+ "import lombok.*;\n"
+ "@Data @Getter(AccessLevel.NONE) public class N { private int x; }\n",
+ )
+ assert "getX" not in names and "setX" in names, names
+
+ def test_setter_returns_follow_chain_and_fluent(self, tmp_path: Path) -> None:
+ by = _by_name(_parse_full(
+ tmp_path, "C.java",
+ "import lombok.*;\n"
+ "import lombok.experimental.Accessors;\n"
+ "@Setter @Accessors(chain = true)\n"
+ "public class C {\n"
+ " private int a;\n"
+ " @Accessors(fluent = true, chain = false) private int b;\n"
+ "}\n",
+ ))
+ assert by["setA"][0].signature.endswith("-> C")
+ assert [s.signature for s in by["b"] if s.kind == "method"] == ["b(int b) -> void"]
+
+ def test_initialized_final_field_takes_no_builder_or_constructor_slot(
+ self, tmp_path: Path
+ ) -> None:
+ pf = _parse_full(
+ tmp_path, "F.java",
+ "import lombok.*;\n"
+ "@Builder @AllArgsConstructor\n"
+ "public class F { private final int k = 1; private int v; }\n",
+ )
+ names = [s.name for s in pf.symbols if s.parent_name == "FBuilder"]
+ assert "v" in names and "k" not in names, names
+ ctor = [s for s in pf.symbols if s.name == "F" and s.parent_name == "F"]
+ assert [c.signature for c in ctor] == ["F(int v)"]
+
+ def test_a_non_lombok_getter_annotation_generates_nothing(self, tmp_path: Path) -> None:
+ names = _parse(
+ tmp_path, "G.java",
+ "import other.Getter;\npublic class G { @Getter private int x; }\n",
+ )
+ assert "getX" not in names, names
+
+
+class TestLombokCallEdges:
+ """A call through a generated member lands on it, chained hops included."""
+
+ def test_getter_and_builder_chains_resolve(self, tmp_path: Path) -> None:
+ from repowise.core.ingestion.call_resolver import CallResolver
+
+ files = {
+ "src/Child.java": (
+ "package p;\n"
+ "public class Child {\n"
+ " public String name() { return \"\"; }\n"
+ "}\n"
+ ),
+ "src/Dto.java": (
+ "package p;\n"
+ "import lombok.*;\n"
+ "@Getter\n"
+ "@Builder\n"
+ "public class Dto {\n"
+ " private Child child;\n"
+ " private String label;\n"
+ "}\n"
+ ),
+ "src/Use.java": (
+ "package p;\n"
+ "public class Use {\n"
+ " String run(Dto dto) {\n"
+ " Dto made = Dto.builder().label(\"x\").build();\n"
+ " return dto.getChild().name();\n"
+ " }\n"
+ "}\n"
+ ),
+ }
+ 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)
+ resolver = CallResolver(parsed, {p: set() for p in parsed}, repo_path=str(tmp_path))
+ callees = {rc.callee_id for rc in resolver.resolve_file("src/Use.java", parsed["src/Use.java"].calls)}
+ assert "src/Dto.java::Dto::getChild" in callees
+ assert "src/Child.java::Child::name" in callees
+ assert "src/Dto.java::DtoBuilder::label" in callees
+ assert "src/Dto.java::DtoBuilder::build" in callees