diff --git a/cldk/analysis/java/backend.py b/cldk/analysis/java/backend.py index 9b0ffd2..58891ba 100644 --- a/cldk/analysis/java/backend.py +++ b/cldk/analysis/java/backend.py @@ -50,7 +50,8 @@ import re from abc import abstractmethod from functools import cached_property -from typing import ClassVar, Collection, Dict, Iterable, List, Mapping, NamedTuple, Optional, Sequence, Set, Tuple, Union +import logging +from typing import Any, Callable, ClassVar, Collection, Dict, Iterable, Iterator, List, Mapping, NamedTuple, Optional, Sequence, Set, Tuple, TypeVar, Union import networkx as nx @@ -128,6 +129,8 @@ from cldk.models.java.projections import JCallableOverview, JClassOverview from cldk.utils.exceptions.exceptions import CodeanalyzerExecutionException, CodeanalyzerUsageException, SelectorNotInGraph +logger = logging.getLogger(__name__) + # A CRUD query row: the owning type + callable and the operations found within it. CRUDRow = Dict[str, Union[JType, JCallable, List[JCRUDOperation]]] @@ -519,18 +522,136 @@ class _Addressing(NamedTuple): """The application, indexed the four ways the addressing surface reads it — built once per backend, from the same :class:`JApplication` both backends hold.""" - by_key: Dict[str, _Addressed] + by_key: "NameIndex[_Addressed]" by_id: Dict[str, _Addressed] by_path: Dict[str, List[_Addressed]] candidates: List[CallableCandidate] + rows: List[_Addressed] + + +def duplicate_type_name(qualified_name: str, files: Sequence[str] = ()) -> str: + """The message for a query keyed by a qualified name that more than one file declares — which + would make a ``get_call_graph()`` node key and a ``get_class()`` key ambiguous, so it is + surfaced rather than letting one copy silently shadow the others. The duplication is in the + source tree (vendored copies of one library, say), not the analyzer's doing (#420). Both + backends raise this text, identically, and it names the qualified name and the files: a + ``can://`` id must not appear in a message (E6).""" + where = f" ({', '.join(sorted(files))})" if files else "" + return (f"type qualified name {qualified_name!r} is declared in more than one file{where}: " + "the name is ambiguous, so a query keyed by it cannot be answered") + + +def duplicate_callable_key(key: str, files: Sequence[str] = ()) -> str: + """The message for a ``"."`` key that callables in more than one file + spell (#420): each copy answers to ``"@"`` instead, the spelling + :meth:`~JavaAnalysisBackend.get_callables_overview` and ``get_call_graph()`` use for it.""" + where = f" ({', '.join(sorted(files))})" if files else "" + return (f"callable {key!r} is declared in more than one file{where}: the key is ambiguous; " + f"name one copy as '@'") + + +V = TypeVar("V") -def duplicate_type_name(qualified_name: str) -> str: - """The defect message for two declarations that spell one qualified name — which would make a - ``get_call_graph()`` node key and a ``get_class()`` key ambiguous, so it is surfaced rather than - letting the second silently shadow the first. Both backends raise this text, identically, and - it names only the qualified name: a ``can://`` id must not appear in a message (E6).""" - return f"type qualified name {qualified_name!r} is declared twice: codeanalyzer-java emitted two declarations that spell one name" +class NameIndex(Mapping[str, V]): + """Values by qualified name, where one name may be declared in several files (#420). + + The application always loads: every declaration is kept, under its name, with its file. A name + with one declaration answers as a plain mapping would. Looking up a contested one raises + ``refuse(name, files)`` (by default :func:`duplicate_type_name`) — directly, through ``.get()`` + (which returns ``None`` only for an absent name), or by iterating values (``dict(index)``, + ``.items()``). Membership, ``len`` (a count of names) and iteration over names never raise; + :meth:`entries` and :meth:`declarations` read every copy, and :meth:`select` answers a filter + that refuses only when a contested name passes it. + """ + + def __init__(self, refuse: Callable[[str, Sequence[str]], str] = duplicate_type_name) -> None: + self._entries: Dict[str, List[Tuple[V, str]]] = {} + self._refuse = refuse + + def add(self, name: str, value: V, path: str) -> None: + self._entries.setdefault(name, []).append((value, path)) + + def __getitem__(self, name: str) -> V: + entries = self._entries[name] + if len(entries) > 1: + raise CodeanalyzerExecutionException(self._refuse(name, [p for _, p in entries])) + return entries[0][0] + + def __setitem__(self, name: str, value: V) -> None: + """Replace every declaration of ``name`` with this one, in the file of the first, or + ``""`` for a name that had none.""" + old = self._entries.get(name) + self._entries[name] = [(value, old[0][1] if old else "")] + + def __delitem__(self, name: str) -> None: + del self._entries[name] + + def __contains__(self, name: object) -> bool: + return name in self._entries + + def __iter__(self) -> Iterator[str]: + return iter(self._entries) + + def __len__(self) -> int: + return len(self._entries) + + def contested(self) -> Dict[str, List[str]]: + """Every name declared in more than one file, with its files.""" + return {name: sorted(p for _, p in entries) + for name, entries in self._entries.items() if len(entries) > 1} + + def declarations(self, name: str) -> Dict[str, V]: + """Every declaration of ``name``, by file; empty when nothing declares it.""" + return {path: value for value, path in self._entries.get(name, ())} + + def entries(self) -> Iterator[Tuple[str, V, str]]: + """``(name, value, file)`` for every declaration, contested names included.""" + for name, entries in self._entries.items(): + for value, path in entries: + yield name, value, path + + def select(self, keep: Callable[[V], bool]) -> Dict[str, V]: + """The declarations ``keep`` accepts, by name. Refuses only when a contested name has a + declaration ``keep`` accepts, since that name could not be one key of the answer.""" + out: Dict[str, V] = {} + for name, entries in self._entries.items(): + if any(keep(value) for value, _ in entries): + out[name] = self[name] + return out + + +def index_types(symbol_table: Mapping[str, Any]) -> Tuple["NameIndex[Any]", "NameIndex[str]", Dict[str, Tuple[Any, Any]], Dict[str, str]]: + """The containment tree flattened once, for both backends: every type (top-level, nested, + local/anonymous) and its file by source-spelled qualified name, every callable by its + ``can://`` id, which is unique per copy, and each callable's file by that id. A callable's file + is never looked up by its owner's name, which two copies share. Contested names are logged + here, once, and refuse only the queries keyed by them (#420).""" + types: NameIndex[Any] = NameIndex() + file_of: NameIndex[str] = NameIndex() + callables: Dict[str, Tuple[Any, Any]] = {} + callable_file: Dict[str, str] = {} + + def add(t: Any, path: str) -> None: + types.add(t.qualified_name, t, path) + file_of.add(t.qualified_name, path, path) + for c in t.callables.values(): + callables[c.id] = (t, c) + callable_file[c.id] = path + for local in c.types.values(): + add(local, path) + for nested in t.types.values(): + add(nested, path) + + for path, unit in symbol_table.items(): + for t in unit.types.values(): + add(t, path) + contested = types.contested() + if contested: + name, files = next(iter(sorted(contested.items()))) + logger.warning(f"{len(contested)} type qualified name(s) are declared in more than one file " + f"(e.g. {name!r} in {', '.join(files)}); queries keyed by those names raise") + return types, file_of, callables, callable_file def unhomed_endpoint(node_id: str) -> str: @@ -592,8 +713,8 @@ def _addressing(self) -> _Addressing: """Every callable of the application, indexed for addressing — built once, lazily. Reads the flattened containment index each backend already builds for the call graph - (``_callables``: ``can://`` id → ``(owning type, callable)``; ``_file_of``: type qualified - name → module key), so there is no third walk of the tree and no way for the addressing + (``_callables``: ``can://`` id → ``(owning type, callable)``; ``_callable_file``: ``can://`` + id → module key), so there is no third walk of the tree and no way for the addressing domain to disagree with the one :meth:`get_call_graph` homes its endpoints on. The candidate domain is **every callable the analyzer emitted** (J-6): initializers, @@ -607,18 +728,56 @@ def _addressing(self) -> _Addressing: # callable: J-2's rule reads the *unit* (its declared package and the types it declares), # and daytrader8 has 1,216 callables across 138 of them. module_names = {path: java_module_dotted(unit.package, unit.types) for path, unit in symbol_table.items()} - by_key: Dict[str, _Addressed] = {} + # A key two copies spell (#420) names neither: each copy's row answers to + # ``"@"``, and the bare key stays in ``by_key`` only to refuse with both files + # (resolving it by name is an ambiguity between the two copies instead). + spelled: Dict[str, int] = {} + for owner, c in self._callables.values(): + key = f"{owner.qualified_name}.{c.signature}" + spelled[key] = spelled.get(key, 0) + 1 + by_key: NameIndex[_Addressed] = NameIndex(duplicate_callable_key) by_id: Dict[str, _Addressed] = {} by_path: Dict[str, List[_Addressed]] = {} candidates: List[CallableCandidate] = [] - for owner, c in self._callables.values(): - path = self._file_of[owner.qualified_name] - row = _Addressed(f"{owner.qualified_name}.{c.signature}", owner, c, path) - by_key[row.key] = row + rows: List[_Addressed] = [] + for callable_id, (owner, c) in self._callables.items(): + path = self._callable_file[callable_id] + key = f"{owner.qualified_name}.{c.signature}" + row = _Addressed(key if spelled[key] == 1 else f"{key}@{path}", owner, c, path) + by_key.add(row.key, row, path) + if row.key != key: + by_key.add(key, row, path) by_id[c.id] = row by_path.setdefault(path, []).append(row) - candidates.append(CallableCandidate(row.key, owner.qualified_name, path, java_callable_names(row.key), module_names.get(path, ()))) - return _Addressing(by_key, by_id, by_path, candidates) + rows.append(row) + # A contested copy is reported, and answers, as ``"@"`` too, so an ambiguity + # lists one spelling per copy and either that spelling or ``in_module=`` resolves it. + names = java_callable_names(key) + ((row.key,) if row.key != key else ()) + candidates.append(CallableCandidate(row.key, owner.qualified_name, path, names, module_names.get(path, ()))) + return _Addressing(by_key, by_id, by_path, candidates, rows) + + def _refuse_contested_key(self, key: str) -> None: + """Raise :func:`duplicate_callable_key` when callables in more than one file spell ``key`` + (#420): the question does not say which copy it is about. ``"@"`` names one + copy and passes, as does a key spelled once or not at all.""" + self._addressing.by_key.get(key) + + def _unique_type(self, qualified_name: str) -> JType | None: + """The one type declaring ``qualified_name``, or ``None`` when no type or several do. For + resolution that has no file to go on, where a contested name names no particular copy.""" + found = self._types.declarations(qualified_name) + return next(iter(found.values())) if len(found) == 1 else None + + def _node_key(self, node_id: str) -> Tuple[str, "JMethodDetail"]: + """The (call-graph node key, method detail) a call-graph endpoint id resolves to: the + callable's addressing key, so a copy of a contested key is its own node (#420). 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).""" + row = self._addressing.by_id.get(node_id) + if row is None: + raise CodeanalyzerExecutionException(unhomed_endpoint(node_id)) + return row.key, JMethodDetail(method_declaration=row.callable.declaration, klass=row.type.qualified_name, method=row.callable) # -----[ locate ]----- def locate(self, path: str, line: int) -> LocateResult: @@ -1016,7 +1175,7 @@ def get_callables_overview(self) -> List[JCallableOverview]: because all of them are addressable and a projection that quietly omits one is a name that resolves to nothing for a reason the caller cannot see. """ - return [JCallableOverview.of(row.key, row.type, row.callable, path=row.path) for row in self._addressing.by_key.values()] + return [JCallableOverview.of(row.key, row.type, row.callable, path=row.path) for row in self._addressing.rows] def get_method_bodies(self, signatures: List[str]) -> Dict[str, str]: """Source bodies for the given callables, keyed by the key that named them. @@ -1083,7 +1242,7 @@ def get_entrypoint_classes(self) -> List[JClassOverview]: ``Dict[str, JType]`` shape (J-4); the two never disagree about which types are marked, because both read the one flattened index. """ - return [JClassOverview.of(t, path=self._file_of[name], qualified_name=name) for name, t in self._types.items() if t.is_entrypoint_class] + return [JClassOverview.of(t, path=path, qualified_name=name) for name, t, path in self._types.entries() if t.is_entrypoint_class] def get_entrypoint_coverage(self) -> EntrypointCoverage: """The entrypoint pass's own coverage and failure record, identically on both backends. @@ -1407,7 +1566,7 @@ def get_enum_members(self, qualified_enum_name: str) -> List[JEnumConstant]: return list(found.enum_constants) def _of_kind(self, kind: str) -> Dict[str, JType]: - return {name: t for name, t in self._types.items() if t.kind == kind} + return self._types.select(lambda t: t.kind == kind) # ===================================================================================== # The six 1.x accessors leg 3 deferred (#366). Each is implemented **once, here**, over what @@ -1469,10 +1628,13 @@ def get_variables(self) -> Dict[str, List[JLocalVariable]]: are placeholders over the graph, as they are everywhere else on this surface -- so compare variables on ``name``/``type``/``start_line``. """ + # Keyed by each callable's addressing key, so a copy of a contested key is ``@`` + # (#420); walked type by type, which is the order the 1.x dict had. + by_id = self._addressing.by_id return { - f"{klass}.{signature}": sorted(c.local_variables, key=lambda v: (v.start_line, v.name)) - for klass, methods in self.get_all_methods_in_application().items() - for signature, c in methods.items() + by_id[c.id].key: sorted(c.local_variables, key=lambda v: (v.start_line, v.name)) + for _, t, _ in self._types.entries() + for c in t.callable_declarations.values() } def get_class_hierarchy(self) -> nx.DiGraph: @@ -1502,7 +1664,8 @@ def get_class_hierarchy(self) -> nx.DiGraph: every ``:JType``, so both backends read the same list. A type that neither extends nor is extended is an isolated node rather than a missing one, - which is why the nodes are added before the edges. + which is why the nodes are added before the edges. Nodes are type names, so like + :meth:`get_all_classes` this refuses when a name is declared in more than one file (#420). """ graph = nx.DiGraph() for name, declared in self.get_all_classes().items(): @@ -2383,6 +2546,13 @@ def get_class_call_graph_using_symbol_table(self, qualified_class_name: str, met """Call-graph edges out of a class, computed from the symbol table's call sites only.""" # -----[ classes / methods / fields ]----- + def get_class_declarations(self, qualified_class_name: str) -> Dict[str, JType]: + """Every declaration of a qualified type name, by file: one entry for most names, several + where copies of one library are vendored across source roots (#420), and none for a name + the application does not declare. Never raises; :meth:`get_class` refuses a contested + name, and this is how to read each copy.""" + return self._types.declarations(qualified_class_name) + @abstractmethod def get_all_sub_classes(self, qualified_class_name: str) -> Dict[str, JType]: """Classes that extend/implement the given class.""" diff --git a/cldk/analysis/java/codeanalyzer/codeanalyzer.py b/cldk/analysis/java/codeanalyzer/codeanalyzer.py index 6e035e7..1275d50 100644 --- a/cldk/analysis/java/codeanalyzer/codeanalyzer.py +++ b/cldk/analysis/java/codeanalyzer/codeanalyzer.py @@ -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 ( @@ -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 ``"."`` 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 @@ -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 "@" (#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 { @@ -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 "@" (#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 { @@ -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]]: @@ -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)) @@ -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) @@ -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, "" @@ -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) @@ -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]: diff --git a/cldk/analysis/java/java_analysis.py b/cldk/analysis/java/java_analysis.py index 547a851..c3b8295 100644 --- a/cldk/analysis/java/java_analysis.py +++ b/cldk/analysis/java/java_analysis.py @@ -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. @@ -1013,7 +1029,8 @@ def get_test_methods(self) -> Dict[str, str]: Returns: A dictionary mapping ``"."`` — 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; ``".@"`` 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`). @@ -1021,12 +1038,11 @@ def get_test_methods(self) -> Dict[str, str]: :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 "@" (#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. diff --git a/cldk/analysis/java/neo4j/neo4j_backend.py b/cldk/analysis/java/neo4j/neo4j_backend.py index e5a63e3..fd4eff7 100644 --- a/cldk/analysis/java/neo4j/neo4j_backend.py +++ b/cldk/analysis/java/neo4j/neo4j_backend.py @@ -133,8 +133,8 @@ CallingLines, CRUDRow, JavaAnalysisBackend, - duplicate_type_name, - unhomed_endpoint, + NameIndex, + index_types, VIEW_DISPATCH_UNRESOLVED_JSON_ONLY, ) from cldk.analysis.java.neo4j import reconstruct as R @@ -666,45 +666,28 @@ def application(self) -> JApplication: return self._application @cached_property - def _idx(self) -> Tuple[Dict[str, JType], Dict[str, str], Dict[str, Tuple[JType, JCallable]]]: - """The containment tree flattened 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 call-graph endpoint into the ``"."`` node key. - Mirrors :meth:`JCodeanalyzer._index`.""" - types: Dict[str, JType] = {} - file_of: Dict[str, str] = {} - callables: Dict[str, Tuple[JType, JCallable]] = {} - - def add(t: JType, path: str) -> None: - name = t.qualified_name - if name in types: - raise CodeanalyzerExecutionException(duplicate_type_name(name)) - types[name] = t - file_of[name] = path - for c in t.callables.values(): - callables[c.id] = (t, c) - for local in c.types.values(): - add(local, path) - for nested in t.types.values(): - add(nested, path) - - for path, unit in self._application.symbol_table.items(): - for t in unit.types.values(): - add(t, path) - return types, file_of, callables + def _idx(self) -> Tuple[NameIndex[JType], NameIndex[str], Dict[str, Tuple[JType, JCallable]], Dict[str, str]]: + """The containment tree flattened once, as :meth:`JCodeanalyzer._index` flattens it (both + call :func:`index_types`): a name declared in several files is kept, and only a query keyed + by it refuses (#420).""" + return index_types(self._application.symbol_table) @property - def _types(self) -> Dict[str, JType]: + def _types(self) -> NameIndex[JType]: return self._idx[0] @property - def _file_of(self) -> Dict[str, str]: + def _file_of(self) -> NameIndex[str]: return self._idx[1] @property def _callables(self) -> Dict[str, Tuple[JType, JCallable]]: return self._idx[2] + @property + def _callable_file(self) -> Dict[str, str]: + return self._idx[3] + # -----[ the addressing surface (leg 3b) — the three facts the shared implementation needs ]----- #: The one statement leg 3b's Task 1 adds. Anchored on the **bare** ``:JBodyNode`` label and a #: per-callable id prefix, which is the narrowest predicate on this surface. @@ -781,8 +764,8 @@ def _body_nodes(self, callable_ids: Sequence[str]) -> Dict[str, Dict[str, JBodyN def _unit_of(self, callable_id: str) -> JCompilationUnit | None: """The compilation unit a callable was declared in, or ``None`` when it has no file — which is every ``@external`` callable, and nothing else.""" - owner = self._callables.get(callable_id) - return None if owner is None else self._application.symbol_table.get(self._file_of.get(owner[0].qualified_name, "")) + path = self._callable_file.get(callable_id) + return None if path is None else self._application.symbol_table.get(path) def _body_source(self, node: JBodyNode) -> str | None: """See :meth:`JavaAnalysisBackend._body_source` — a real slice of the owning module's @@ -1191,15 +1174,9 @@ 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 - projection writes is homed on the tree; one that is not is a 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 in-memory backend uses.""" - try: - t, c = self._idx[2][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 get_call_graph(self) -> nx.DiGraph: """Build (and cache) the call graph keyed by ``"."`` (J-1): node attrs @@ -1238,8 +1215,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 "@" (#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 { @@ -1248,8 +1226,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 "@" (#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 { @@ -1267,6 +1246,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]]: @@ -1283,8 +1266,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)) @@ -1301,7 +1286,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) @@ -1311,32 +1296,34 @@ def _st_edges_into(self, target_class_name: str, target_method_signature: str) - return for owner, source in self._idx[2].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, "" @@ -1379,7 +1366,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) @@ -1399,15 +1386,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]: @@ -1495,8 +1479,7 @@ def get_all_docstrings(self) -> Dict[str, List[JComment]]: same file. """ out: Dict[str, List[JComment]] = {} - for name, t in self._types.items(): - path = self._idx[1][name] + for _, t, path in self._types.entries(): javadoc = list(t.comments) javadoc += [c for member in t.callables.values() for c in member.comments] javadoc += [c for f in t.fields.values() for c in f.comments] diff --git a/tests/analysis/java/test_java_addressing.py b/tests/analysis/java/test_java_addressing.py index f180443..82e8c40 100644 --- a/tests/analysis/java/test_java_addressing.py +++ b/tests/analysis/java/test_java_addressing.py @@ -512,3 +512,208 @@ def test_the_two_backends_agree_on_every_answer_here(analysis_json): with pytest.raises(Exception) as ga: graph.resolve_callable(name) assert type(la.value) is type(ga.value) and str(la.value) == str(ga.value) + + +@pytest.mark.parametrize("build", ["local", "graph"]) +def test_both_backends_load_duplicates_and_refuse_at_the_same_query(build, analysis_json): + """One name in two files: both backends load, and both refuse at the query keyed by it (#420).""" + import json + + from cldk.utils.exceptions.exceptions import CodeanalyzerExecutionException + from tests.analysis.java.test_jcodeanalyzer import _with_a_vendored_copy + + payload, contested, copy_path = _with_a_vendored_copy(analysis_json) + backend = (_local if build == "local" else _graph)(payload) + with pytest.raises(CodeanalyzerExecutionException) as raised: + backend.get_class(contested) + assert copy_path in str(raised.value) + other = [u for u in json.loads(analysis_json)["application"]["symbol_table"].values() if u["types"]][1] + name = (other["package"] + "." if other.get("package") else "") + next(iter(other["types"])) + assert backend.get_class(name) is not None + + +# ---- one qualified name in two files (#420) ------------------------------------------------------ +MARKET = f"{BEANS_PKG}.MarketSummaryDataBean" +MARKET_COPY_FILE = "vendored/" + MARKET_BEAN_FILE +GAIN = f"{MARKET}.getGainPercent()" + + +def _vendored(payload: str, path: str = MARKET_BEAN_FILE) -> str: + """``payload`` with the unit at ``path`` copied under ``vendored/``, as two services vendoring + one library would: the copy's ids spell its own path, and so do the call edges inside it.""" + import json + + data = json.loads(payload) + app = data["application"] + copy = "vendored/" + path + app["symbol_table"][copy] = json.loads(json.dumps(app["symbol_table"][path]).replace(path, copy)) + inside = f"/java/{path}/" + copied = [json.loads(json.dumps(e).replace(path, copy)) for e in app.get("call_graph") or [] if inside in e["src"] and inside in e["dst"]] + if copied: + app["call_graph"] = app["call_graph"] + copied + return json.dumps(data) + + +def _build(build: str, payload: str): + return (_local if build == "local" else _graph)(payload) + + +@pytest.mark.parametrize("build", ["local", "graph"]) +def test_duplicates_leave_every_uncontested_callable_addressable(build, analysis_json): + """A contested name refuses only the queries keyed by it: ``locate`` and ``resolve_callable`` + still answer for every other callable, and for a position in either copy's file (#420).""" + backend = _build(build, _vendored(analysis_json)) + assert backend.locate(TRADE_DIRECT_FILE, 650).callable.signature == "cancelOrder(java.lang.Integer, boolean)" + assert backend.resolve_callable(CANCEL_INT_BOOL).callable == CANCEL_INT_BOOL + gain = backend.get_class_declarations(MARKET)[MARKET_COPY_FILE].callables["getGainPercent()"] + found = backend.locate(MARKET_COPY_FILE, gain.start_line) + assert found.callable.signature == "getGainPercent()" and found.module.path == MARKET_COPY_FILE + + +@pytest.mark.parametrize("build", ["local", "graph"]) +def test_a_key_both_copies_declare_refuses_and_its_path_spelling_answers(build, analysis_json): + """``.`` declared in both files names neither: resolving it is an ambiguity + that lists each copy, and a lookup keyed by it refuses with both files. Each copy answers to + ``.@``, the spelling the overview and the call graph use, and to + ``in_module=`` (#420).""" + from cldk.utils.exceptions.exceptions import CodeanalyzerExecutionException + + backend = _build(build, _vendored(analysis_json)) + with pytest.raises(AmbiguousName) as ambiguous: + backend.resolve_callable(GAIN) + assert f"{GAIN}@{MARKET_BEAN_FILE}" in str(ambiguous.value) and f"{GAIN}@{MARKET_COPY_FILE}" in str(ambiguous.value) + assert backend.resolve_callable(f"{GAIN}@{MARKET_COPY_FILE}").file == MARKET_COPY_FILE + narrowed = backend.resolve_callable(GAIN, in_module=MARKET_COPY_FILE) + assert (narrowed.callable, narrowed.file) == (f"{GAIN}@{MARKET_COPY_FILE}", MARKET_COPY_FILE) + with pytest.raises(CodeanalyzerExecutionException) as raised: + backend.get_source(GAIN) + assert MARKET_BEAN_FILE in str(raised.value) and MARKET_COPY_FILE in str(raised.value) + keys = {o.key: o.path for o in backend.get_callables_overview() if o.owner == MARKET} + assert keys[f"{GAIN}@{MARKET_BEAN_FILE}"] == MARKET_BEAN_FILE + assert keys[f"{GAIN}@{MARKET_COPY_FILE}"] == MARKET_COPY_FILE + assert GAIN not in keys + copy = backend.get_source(f"{GAIN}@{MARKET_COPY_FILE}") + assert "gainPercent" in copy and copy == backend.get_source(f"{GAIN}@{MARKET_BEAN_FILE}") + assert CANCEL_INT_BOOL in {o.key for o in backend.get_callables_overview()} + + +@pytest.mark.parametrize("build", ["local", "graph"]) +def test_the_call_graph_keeps_each_copy_apart(build, analysis_json_a4): + """Two copies' callables are two nodes each, keyed ``.@``, and each + copy keeps its own edges; uncontested keys are unchanged (#420).""" + plain = _build(build, analysis_json_a4).get_call_graph() + graph = _build(build, _vendored(analysis_json_a4)).get_call_graph() + market = [n for n in plain.nodes if n.startswith(MARKET + ".")] + assert market, "a4 needs calls inside MarketSummaryDataBean" + copied = sum(1 for s, d in plain.edges if s in market and d in market) + assert graph.number_of_edges() == plain.number_of_edges() + copied + for key in market: + assert key not in graph + assert f"{key}@{MARKET_BEAN_FILE}" in graph and f"{key}@{MARKET_COPY_FILE}" in graph + others = [n for n in plain.nodes if n not in market] + assert others and all(n in graph for n in others) + + +@pytest.mark.parametrize("build", ["local", "graph"]) +def test_filtered_answers_refuse_only_when_a_contested_name_is_in_them(build, analysis_json): + """A name-keyed answer refuses only if a contested name would be a key of it; an answer that + carries each entry's file lists every copy; the unfiltered ``get_all_classes`` refuses (#420).""" + from cldk.utils.exceptions.exceptions import CodeanalyzerExecutionException + + backend = _build(build, _vendored(analysis_json)) + assert MARKET not in backend.get_all_entry_point_classes() # the bean is not one + assert backend.get_all_entry_point_classes() + with pytest.raises(CodeanalyzerExecutionException): + backend.get_all_classes() + resource = "src/main/java/com/ibm/websphere/samples/daytrader/jaxrs/BroadcastResource.java" + name = "com.ibm.websphere.samples.daytrader.jaxrs.BroadcastResource" + backend = _build(build, _vendored(analysis_json, resource)) + with pytest.raises(CodeanalyzerExecutionException) as raised: + backend.get_all_entry_point_classes() + assert name in str(raised.value) + paths = sorted(o.path for o in backend.get_entrypoint_classes() if o.qualified_name == name) + assert paths == [resource, "vendored/" + resource] + + +@pytest.mark.parametrize("build", ["local", "graph"]) +def test_class_declarations_list_every_copy_by_file(build, analysis_json): + backend = _build(build, _vendored(analysis_json)) + copies = backend.get_class_declarations(MARKET) + assert sorted(copies) == [MARKET_BEAN_FILE, MARKET_COPY_FILE] + assert all(t.qualified_name == MARKET for t in copies.values()) + assert list(backend.get_class_declarations(f"{DIRECT_PKG}.TradeDirect")) == [TRADE_DIRECT_FILE] + assert backend.get_class_declarations("no.such.Type") == {} + + +@pytest.mark.parametrize("build", ["local", "graph"]) +def test_duplicates_are_logged_once_when_the_index_is_built(build, analysis_json, caplog): + import logging + + with caplog.at_level(logging.WARNING, logger="cldk.analysis.java.backend"): + backend = _build(build, _vendored(analysis_json)) + backend.get_class(f"{DIRECT_PKG}.TradeDirect") + backend.get_class(f"{DIRECT_PKG}.TradeDirect") + warned = [r.getMessage() for r in caplog.records if "more than one file" in r.getMessage()] + assert len(warned) == 1 and MARKET in warned[0] and MARKET_COPY_FILE in warned[0] + + +@pytest.mark.parametrize("build", ["local", "graph"]) +def test_whole_application_callable_answers_with_a_contested_name(build, analysis_json): + """Callable-keyed answers key each copy ``@``; a filtered, class-keyed answer refuses + only when a contested class is in it; the unfiltered class-keyed ones still refuse (#420).""" + from cldk.utils.exceptions.exceptions import CodeanalyzerExecutionException + + backend = _build(build, _vendored(analysis_json)) + variables = backend.get_variables() + assert f"{GAIN}@{MARKET_BEAN_FILE}" in variables and f"{GAIN}@{MARKET_COPY_FILE}" in variables + assert GAIN not in variables and CANCEL_INT_BOOL in variables + plain = _build(build, analysis_json).get_variables() + assert len(variables) == len(plain) + sum(1 for k in plain if k.startswith(MARKET + ".")) + entry = backend.get_all_entry_point_methods() + assert entry and MARKET not in entry + for unfiltered in (backend.get_all_methods_in_application, backend.get_class_hierarchy): + with pytest.raises(CodeanalyzerExecutionException): + unfiltered() + resource = "src/main/java/com/ibm/websphere/samples/daytrader/jaxrs/BroadcastResource.java" + with pytest.raises(CodeanalyzerExecutionException): + _build(build, _vendored(analysis_json, resource)).get_all_entry_point_methods() + + +@pytest.mark.parametrize("build", ["local", "graph"]) +def test_call_graph_queries_on_a_contested_key_refuse_and_its_copies_answer(build, analysis_json_a4): + """A contested ``(class, signature)`` refuses, naming both files, rather than answering ``{}``; + ``@`` asks about one copy; a contested class refuses ``get_class_call_graph`` + rather than merging both copies' edges (#420).""" + from cldk.utils.exceptions.exceptions import CodeanalyzerExecutionException + + plain = _build(build, analysis_json_a4) + backend = _build(build, _vendored(analysis_json_a4)) + with pytest.raises(CodeanalyzerExecutionException) as raised: + backend.get_all_callers(MARKET, "getOpenTSIA()", using_symbol_table=False) + assert MARKET_COPY_FILE in str(raised.value) + with pytest.raises(CodeanalyzerExecutionException): + backend.get_all_callees(MARKET, "getOpenTSIA()", using_symbol_table=False) + want = plain.get_all_callers(MARKET, "getOpenTSIA()", using_symbol_table=False)["caller_details"] + copy = backend.get_all_callers(MARKET, f"getOpenTSIA()@{MARKET_COPY_FILE}", using_symbol_table=False)["caller_details"] + assert want and sorted(d["caller_method"].method.signature for d in copy) == sorted(d["caller_method"].method.signature for d in want) + assert all(d["caller_method"].method.id.find("/vendored/") > 0 for d in copy) + with pytest.raises(CodeanalyzerExecutionException): + backend.get_class_call_graph(MARKET) + trade = f"{DIRECT_PKG}.TradeDirect" + pairs = lambda edges: sorted((s.klass, s.method.signature, t.klass, t.method.signature) for s, t in edges) # noqa: E731 + assert pairs(backend.get_class_call_graph(trade)) == pairs(plain.get_class_call_graph(trade)) + + +@pytest.mark.parametrize("build", ["local", "graph"]) +def test_the_symbol_table_call_graph_answers_for_uncontested_classes(build, analysis_json_a4): + """The symbol-table call graph does not follow a contested name, so a question about an + uncontested class answers as it did without the copy (#420).""" + plain = _build(build, analysis_json_a4) + backend = _build(build, _vendored(analysis_json_a4)) + trade = f"{DIRECT_PKG}.TradeDirect" + pairs = lambda edges: sorted((s.klass, s.method.signature, t.klass, t.method.signature) for s, t in edges) # noqa: E731 + want = pairs(plain.get_class_call_graph_using_symbol_table(trade)) + assert want and pairs(backend.get_class_call_graph_using_symbol_table(trade)) == want + called = sorted({t for _, _, k, t in want if k == trade}) + callers = lambda b, sig: sorted(d["caller_method"].method.signature for d in b.get_all_callers(trade, sig, using_symbol_table=True).get("caller_details", [])) # noqa: E731 + assert called and all(callers(backend, sig) == callers(plain, sig) for sig in called) diff --git a/tests/analysis/java/test_java_analysis.py b/tests/analysis/java/test_java_analysis.py index 612b81e..d7271af 100644 --- a/tests/analysis/java/test_java_analysis.py +++ b/tests/analysis/java/test_java_analysis.py @@ -1165,3 +1165,30 @@ def test_get_comments_in_a_class_miss_returns_empty_list(test_fixture, analysis_ ) assert java_analysis.backend.get_comments_in_a_class("com.example.NoSuchClass") == [] + + +def test_get_class_declarations_reads_every_copy_of_a_contested_name(test_fixture, analysis_json): + """``get_class`` refuses a name declared in two files; ``get_class_declarations`` returns each + copy by file (#420).""" + from tests.analysis.java.test_jcodeanalyzer import _with_a_vendored_copy + + payload, contested, copy_path = _with_a_vendored_copy(analysis_json) + with patch("cldk.analysis.java.codeanalyzer.codeanalyzer.subprocess.run") as run_mock: + run_mock.side_effect = _write_java_output(payload) + # Eager: an earlier test's cached analysis of the same fixture must not be reused. + java_analysis = JavaAnalysis(project_dir=test_fixture, backend=_BK, analysis_level=AnalysisLevel.symbol_table, target_files=None, eager_analysis=True) + copies = java_analysis.get_class_declarations(contested) + assert copy_path in copies and len(copies) == 2 + assert java_analysis.get_class_declarations("com.example.NoSuchClass") == {} + + +def test_get_test_methods_answers_with_a_contested_name(test_fixture, analysis_json): + """A contested class name does not refuse ``get_test_methods``, whose answer is keyed by + callable (#420).""" + from tests.analysis.java.test_jcodeanalyzer import _with_a_vendored_copy + + payload, _, _ = _with_a_vendored_copy(analysis_json) + with patch("cldk.analysis.java.codeanalyzer.codeanalyzer.subprocess.run") as run_mock: + run_mock.side_effect = _write_java_output(payload) + java_analysis = JavaAnalysis(project_dir=test_fixture, backend=_BK, analysis_level=AnalysisLevel.symbol_table, target_files=None, eager_analysis=True) + assert isinstance(java_analysis.get_test_methods(), dict) diff --git a/tests/analysis/java/test_java_public_surface.py b/tests/analysis/java/test_java_public_surface.py index 50b7804..47ed4c8 100644 --- a/tests/analysis/java/test_java_public_surface.py +++ b/tests/analysis/java/test_java_public_surface.py @@ -122,6 +122,7 @@ "resolve_callable": "(self, name: 'str', *, in_class: 'str | None' = None, in_module: 'str | None' = None) -> 'SliceNode'", "resolve_value": "(self, name: 'str', *, within: 'str') -> 'SliceNode'", "get_compilation_units": "(self) -> 'List[JCompilationUnit]'", + "get_class_declarations": "(self, qualified_class_name: 'str') -> 'Dict[str, JType]'", "get_constructors": "(self, qualified_class_name: 'str') -> 'Dict[str, JCallable]'", "get_entry_point_classes": "(self) -> 'Dict[str, JType]'", "get_entry_point_methods": "(self) -> 'Dict[str, Dict[str, JCallable]]'", diff --git a/tests/analysis/java/test_jcodeanalyzer.py b/tests/analysis/java/test_jcodeanalyzer.py index 4c78ccb..8766d0a 100644 --- a/tests/analysis/java/test_jcodeanalyzer.py +++ b/tests/analysis/java/test_jcodeanalyzer.py @@ -581,3 +581,52 @@ def test_facade_reuses_language_keyed_cache(analysis_json_fixture, tmp_path): ) assert not run_mock.called assert len(analysis.get_symbol_table()) == 138 + + +def _with_a_vendored_copy(payload: str) -> tuple[str, str, str]: + """``payload`` with its first compilation unit copied under a second path: one qualified name, + declared in two files, as two services vendoring one library would (#420).""" + data = json.loads(payload) + table = data["application"]["symbol_table"] + path, unit = next(iter(table.items())) + copy_path = "vendored/" + path + table[copy_path] = json.loads(json.dumps(unit).replace(path, copy_path)) + qualified = (unit.get("package") + "." if unit.get("package") else "") + next(iter(unit["types"])) + return json.dumps(data), qualified, copy_path + + +def test_duplicate_qualified_names_load_and_raise_only_where_queried(test_fixture, analysis_json): + """An application with one name in two files loads; only a query for that name refuses (#420).""" + payload, contested, copy_path = _with_a_vendored_copy(analysis_json) + analyzer, _ = _analyzer(payload, project_dir=test_fixture) # construction succeeds + assert len(analyzer.get_symbol_table()) == len(json.loads(analysis_json)["application"]["symbol_table"]) + 1 + with pytest.raises(CodeanalyzerExecutionException) as raised: + analyzer.get_class(contested) + assert contested in str(raised.value) and copy_path in str(raised.value) + assert "codeanalyzer-java emitted" not in str(raised.value) # the source tree, not the emitter + with pytest.raises(CodeanalyzerExecutionException): + analyzer.get_java_file(contested) + with pytest.raises(CodeanalyzerExecutionException): + analyzer.get_all_classes() # an answer keyed by every name + others = [u for u in json.loads(analysis_json)["application"]["symbol_table"].values() if u["types"]][1:] + assert others, "the fixture needs a second, uncontested unit" + other = others[0] + other_name = (other["package"] + "." if other.get("package") else "") + next(iter(other["types"])) + assert analyzer.get_class(other_name) is not None # uncontested names answer as before + + +def test_assigning_a_name_replaces_every_declaration_of_it(): + """``index[name] = value`` leaves that one declaration, so a contested name becomes answerable.""" + from cldk.analysis.java.backend import NameIndex + index = NameIndex() + index.add("x.A", 1, "a/A.java") + index.add("x.A", 2, "b/A.java") + with pytest.raises(CodeanalyzerExecutionException): + index["x.A"] + index["x.A"] = 3 + assert index["x.A"] == 3 and index.contested() == {} + assert index.declarations("x.A") == {"a/A.java": 3} # the first declaration's file + index["x.B"] = 4 + assert index.declarations("x.B") == {"": 4} # a new name has none + del index["x.A"] + assert "x.A" not in index