Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
218 changes: 194 additions & 24 deletions cldk/analysis/java/backend.py

Large diffs are not rendered by default.

95 changes: 39 additions & 56 deletions cldk/analysis/java/codeanalyzer/codeanalyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,8 @@
CallingLines,
CRUDRow,
JavaAnalysisBackend,
duplicate_type_name,
index_types,
java_body_node_id,
unhomed_endpoint,
)
from cldk.models.java import JGraphEdges
from cldk.models.java.models import (
Expand Down Expand Up @@ -351,40 +350,17 @@ def _index(self) -> None:
"""Flatten the containment tree once: every type (top-level, nested, local/anonymous) by
its source-spelled qualified name, its file, and every callable by its ``can://`` id — the
join that turns a wire call-graph endpoint into the ``"<type fqn>.<signature>"`` node key."""
self._types: Dict[str, JType] = {}
self._file_of: Dict[str, str] = {}
self._callables: Dict[str, Tuple[JType, JCallable]] = {}
for path, unit in self.application.symbol_table.items():
for t in unit.types.values():
self._add_type(t, path)

def _add_type(self, t: JType, path: str) -> None:
name = t.qualified_name
if name in self._types:
raise CodeanalyzerExecutionException(duplicate_type_name(name))
self._types[name] = t
self._file_of[name] = path
for c in t.callables.values():
self._callables[c.id] = (t, c)
for lt in c.types.values():
self._add_type(lt, path)
for nt in t.types.values():
self._add_type(nt, path)
# A name declared in several files loads; only a query keyed by it refuses (#420).
self._types, self._file_of, self._callables, self._callable_file = index_types(self.application.symbol_table)

@staticmethod
def _detail(klass: str, c: JCallable) -> JMethodDetail:
return JMethodDetail(method_declaration=c.declaration, klass=klass, method=c)

def _node_of(self, node_id: str) -> Tuple[str, JMethodDetail]:
"""The (node key, method detail) a call-graph endpoint id resolves to. Every endpoint the
analyzer emits is homed on the tree; one that is not is the analyzer's defect, surfaced
rather than skipped — named by the signature and module key its id spells, never by the id
(E6), in the same words the Neo4j backend uses."""
try:
t, c = self._callables[node_id]
except KeyError:
raise CodeanalyzerExecutionException(unhomed_endpoint(node_id)) from None
return f"{t.qualified_name}.{c.signature}", self._detail(t.qualified_name, c)
"""The (node key, method detail) a call-graph endpoint id resolves to: see
:meth:`JavaAnalysisBackend._node_key`, which both backends share."""
return self._node_key(node_id)

def _is_external(self, node_id: str) -> bool:
"""An ``@external/…`` endpoint (a call target outside the project). 3a keeps the 1.x
Expand Down Expand Up @@ -730,8 +706,9 @@ def get_call_graph_json(self) -> str:
return json.dumps(rows)

def get_all_callers(self, target_class_name: str, target_method_signature: str, using_symbol_table: bool) -> Dict:
cg = self._symbol_table_call_graph(target_class_name, target_method_signature, is_target=True) if using_symbol_table else self.get_call_graph()
key = f"{target_class_name}.{target_method_signature}"
self._refuse_contested_key(key) # a signature may name one copy as "<signature>@<file>" (#420)
cg = self._symbol_table_call_graph(target_class_name, target_method_signature, is_target=True) if using_symbol_table else self.get_call_graph()
if key not in cg:
return {}
return {
Expand All @@ -740,8 +717,9 @@ def get_all_callers(self, target_class_name: str, target_method_signature: str,
}

def get_all_callees(self, source_class_name: str, source_method_signature: str, using_symbol_table: bool) -> Dict:
cg = self._symbol_table_call_graph(source_class_name, source_method_signature) if using_symbol_table else self.get_call_graph()
key = f"{source_class_name}.{source_method_signature}"
self._refuse_contested_key(key) # a signature may name one copy as "<signature>@<file>" (#420)
cg = self._symbol_table_call_graph(source_class_name, source_method_signature) if using_symbol_table else self.get_call_graph()
if key not in cg:
return {}
return {
Expand All @@ -759,6 +737,10 @@ def _edges_out_of(cg: nx.DiGraph, qualified_class_name: str, method_signature: s
return [(cg.nodes[s]["method_detail"], cg.nodes[t]["method_detail"]) for s, t in cg.edges(seeds)]

def get_class_call_graph(self, qualified_class_name: str, method_name: str | None = None) -> List[Tuple[JMethodDetail, JMethodDetail]]:
# Seeded by class name, so a contested one would merge its copies' edges: refuse (#420).
self.get_class(qualified_class_name)
if method_name is not None:
self._refuse_contested_key(f"{qualified_class_name}.{method_name}")
return self._edges_out_of(self.get_call_graph(), qualified_class_name, method_name)

def get_class_call_graph_using_symbol_table(self, qualified_class_name: str, method_signature: str | None = None) -> List[Tuple[JMethodDetail, JMethodDetail]]:
Expand All @@ -772,8 +754,10 @@ def _symbol_table_call_graph(self, qualified_class_name: str, method_signature:
cg = nx.DiGraph()
lines = CallingLines()
edges = self._st_edges_into(qualified_class_name, method_signature) if is_target else self._st_edges_from(qualified_class_name, method_signature)
by_id = self._addressing.by_id
for source, target in edges:
src, dst = f"{source.klass}.{source.method.signature}", f"{target.klass}.{target.method.signature}"
# Keyed as the declared call graph is, so a copy of a contested key is its own node.
src, dst = by_id[source.method.id].key, by_id[target.method.id].key
cg.add_node(src, method_detail=source, kind="callable")
cg.add_node(dst, method_detail=target, kind="callable")
cg.add_edge(src, dst, type="CALL_DEP", weight=1, calling_lines=lines.of(source.method, target.method))
Expand All @@ -790,7 +774,7 @@ def _st_edges_from(self, qualified_class_name: str, method_signature: str | None
sources = [source] if source is not None else []
for source in sources:
for call_site in source.call_sites:
target, target_class = self._resolve_call_site(qualified_class_name, call_site)
target, target_class = self._resolve_call_site(klass, call_site)
if target is not None:
yield self._detail(qualified_class_name, source), self._detail(target_class, target)

Expand All @@ -800,32 +784,34 @@ def _st_edges_into(self, target_class_name: str, target_method_signature: str) -
return
for owner, source in self._callables.values():
for call_site in source.call_sites:
found, found_class = self._resolve_call_site(owner.qualified_name, call_site)
found, found_class = self._resolve_call_site(owner, call_site)
if found is not None and found_class == target_class_name and call_site.callee_signature == target_method_signature:
yield self._detail(owner.qualified_name, source), self._detail(target_class_name, target)

def _resolve_call_site(self, owner_class_name: str, call_site: JCallSite) -> Tuple[JCallable | None, str]:
def _resolve_call_site(self, owner: JType, call_site: JCallSite) -> Tuple[JCallable | None, str]:
"""The (declaration, declaring class) a call site names, or ``(None, "")``: an explicit
receiver type is followed only when it is a project class; an implicit receiver means the
owning class (and its ``extends`` chain)."""
owning class (and its ``extends`` chain). A receiver or supertype name declared in more than
one file is not followed, since the call site does not say which copy it means (#420)."""
if not call_site.callee_signature:
return None, ""
if call_site.receiver_type:
if self.get_class(call_site.receiver_type) is None:
receiver = self._unique_type(call_site.receiver_type)
if receiver is None:
return None, ""
return self._find_in_hierarchy(call_site.receiver_type, call_site.callee_signature)
return self._find_in_hierarchy(owner_class_name, call_site.callee_signature)
return self._find_in_hierarchy(receiver, call_site.callee_signature)
return self._find_in_hierarchy(owner, call_site.callee_signature)

def _find_in_hierarchy(self, qualified_class_name: str, method_signature: str) -> Tuple[JCallable | None, str]:
def _find_in_hierarchy(self, klass: JType, method_signature: str) -> Tuple[JCallable | None, str]:
"""The concrete declaration of ``method_signature`` on the class or up its ``extends``
chain; interface declarations are not call-graph targets and are skipped."""
klass = self.get_class(qualified_class_name)
method = self.get_method(qualified_class_name, method_signature)
if method is not None and klass is not None and not klass.is_interface:
return method, qualified_class_name
if klass is not None:
for parent in klass.extends_list:
found, found_class = self._find_in_hierarchy(parent, method_signature)
method = klass.callables.get(method_signature)
if method is not None and not klass.is_interface:
return method, klass.qualified_name
for parent in klass.extends_list:
parent_type = self._unique_type(parent)
if parent_type is not None:
found, found_class = self._find_in_hierarchy(parent_type, method_signature)
if found is not None:
return found, found_class
return None, ""
Expand Down Expand Up @@ -861,7 +847,7 @@ def get_method_parameters(self, qualified_class_name: str, qualified_method_name
return method.parameters if method is not None else []

def get_all_sub_classes(self, qualified_class_name: str) -> Dict[str, JType]:
return {name: t for name, t in self._types.items() if qualified_class_name in t.extends_list or qualified_class_name in t.implements_list}
return self._types.select(lambda t: qualified_class_name in t.extends_list or qualified_class_name in t.implements_list)

def get_all_fields(self, qualified_class_name: str) -> List[JField]:
klass = self.get_class(qualified_class_name)
Expand All @@ -881,15 +867,12 @@ def get_implemented_interfaces(self, qualified_class_name: str) -> List[str]:

# -----[ entry points ]-----
def get_all_entry_point_methods(self) -> Dict[str, Dict[str, JCallable]]:
result: Dict[str, Dict[str, JCallable]] = {}
for name, methods in self.get_all_methods_in_application().items():
entrypoints = {sig: c for sig, c in methods.items() if c.is_entrypoint}
if entrypoints:
result[name] = entrypoints
return result
# Filtered, so it refuses only when a contested class declares an entry point (#420).
marked = self._types.select(lambda t: any(c.is_entrypoint for c in t.callable_declarations.values()))
return {name: {sig: c for sig, c in t.callable_declarations.items() if c.is_entrypoint} for name, t in marked.items()}

def get_all_entry_point_classes(self) -> Dict[str, JType]:
return {name: t for name, t in self._types.items() if t.is_entrypoint_class}
return self._types.select(lambda t: t.is_entrypoint_class)

# -----[ CRUD (J-4) ]-----
def get_all_crud_operations(self) -> List[CRUDRow]:
Expand Down
30 changes: 23 additions & 7 deletions cldk/analysis/java/java_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,22 @@ def get_class(self, qualified_class_name: str) -> JType | None:

return self.backend.get_class(qualified_class_name)

def get_class_declarations(self, qualified_class_name: str) -> Dict[str, JType]:
"""Return every declaration of a qualified class name, by file.

Most names have one. Where copies of one library are vendored across source roots, a name
is declared in several files: :meth:`get_class` then raises, since the name alone does
not say which copy is meant, and this returns each copy.

Args:
qualified_class_name: The fully qualified name of the class.

Returns:
A dictionary mapping each repo-relative file path that declares the name to its
:class:`~cldk.models.java.JType`. Empty if no file declares it.
"""
return self.backend.get_class_declarations(qualified_class_name)

def get_method(self, qualified_class_name: str, qualified_method_name: str) -> JCallable | None:
"""Return a specific method by class and method signature.

Expand Down Expand Up @@ -1013,20 +1029,20 @@ def get_test_methods(self) -> Dict[str, str]:

Returns:
A dictionary mapping ``"<type fqn>.<signature>"`` — the call-graph node key of J-1,
unique application-wide — to the callable's ``code``. Note that ``code`` is the body
unique application-wide; ``"<type fqn>.<signature>@<file>"`` for each copy of a key
declared in more than one file — to the callable's ``code``. Note that ``code`` is the body
block off ``analysis.json`` and the whole declaration off the Neo4j projection
(:attr:`~cldk.models.java.models.JCallable.code`).

See Also:
:meth:`get_methods_with_annotations`: For finding methods with
any annotation.
"""
return {
f"{klass}.{signature}": callable_.code
for klass, methods in self.get_methods().items()
for signature, callable_ in methods.items()
if any(d.name.rsplit(".", 1)[-1] in _TEST_ANNOTATIONS for d in callable_.decorators)
}
# Per callable, not per class, so a class name declared in more than one file does not
# refuse it; each copy of a contested key is "<key>@<file>" (#420).
keys = [o.key for o in self.backend.get_callables_overview() if any(d.rsplit(".", 1)[-1] in _TEST_ANNOTATIONS for d in o.decorators)]
bodies = self.backend.get_method_bodies(keys)
return {key: bodies.get(key) for key in keys}

def get_calling_lines(self, target_method_name: str) -> List[int]:
"""Return line numbers where a method is called.
Expand Down
Loading