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.

feat(apex): reach other sfdx projects only through a declared dependency or namespace (#4421)

Raghav Chamadiya5b8ae09b4f1f
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.md
index c094faf84..bce92edd3 100644
--- a/docs/architecture/language-support.md
+++ b/docs/architecture/language-support.md
@@ -970,8 +970,9 @@ declared names keep their written case. CumulusCI `%%%NAMESPACE%%%` tokens are
blanked byte for byte before parsing.
Apex has no imports, so a type name resolves to the top-level class its own
-sfdx project declares, compared without case; a name two files of one project
-declare is read in the copy deployed with the caller, else refused. Static,
+sfdx project declares, compared without case, then to an un-namespaced package
+it declares a dependency on; another project is reached only through its
+namespace prefix (`usf3.Foo`), and nothing binds across projects otherwise. Static,
inner-class, typed, chained, inherited and `super` calls follow Java's tiers,
and a bare name never reaches another class's method. Ceiling: a call site does
not record `new`, so a constructor written in lower case is missed.
diff --git a/packages/core/src/repowise/core/ingestion/call_language_strategies.py b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
index 65ceffb6f..470e0ab96 100644
--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py
+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
@@ -28,7 +28,7 @@ from .resolvers.jvm_gradle import (
source_set_dir,
)
from .symbol_identity import outer_scope
-from .type_names import bare_type_name
+from .type_names import bare_type_name, dotted_type_segments
@dataclass(frozen=True, slots=True)
@@ -182,6 +182,7 @@ class LanguageStrategiesMixin:
# Apex project namespaces (lazy ApexNamespaces)
self._apex_namespaces: Any = None
+ self._apex_retyping = False
# C/C++ same-target resolution (lazy CppWorkspaceIndex)
self._cpp_index: Any = None
@@ -636,17 +637,16 @@ class LanguageStrategiesMixin:
The head is a member type of the caller's class or of a class around
it (an inner class wins inside its outer), else the one top-level type
- of that name in the caller's project. A head naming no type that is
- the project's own namespace prefix is dropped; any other prefix is a
- managed package's and names nothing here. Each later segment is a
+ of that name the caller's project reaches. A head naming no type is a
+ namespace prefix (see ``prefixed_type``). Each later segment is a
member type of the one before it.
"""
index = self._get_apex_namespaces()
- head, *rest = written.split(".")
+ head, *rest = dotted_type_segments(written)
type_id = self._apex_head_type(file_path, caller_id, head)
- if type_id is None and rest and index.strips_prefix(file_path, head):
- head, *rest = rest
- type_id = index.top_level_type(file_path, head)
+ if type_id is None and rest:
+ prefix, (head, *rest) = head, rest
+ type_id = index.prefixed_type(file_path, prefix, head)
for segment in rest:
if type_id is None:
return None
@@ -727,7 +727,18 @@ class LanguageStrategiesMixin:
return None
type_id = self._apex_type(file_path, caller_id, receiver)
if type_id is None:
- return None
+ # ``Affiliations.get()`` on a local declared ``affiliations``.
+ variable = self._apex_variable_spelling(file_path, caller_id, receiver)
+ # One hop: the typed lookup asks this strategy again with the declared type.
+ if variable is None or self._apex_retyping:
+ return None
+ self._apex_retyping = True
+ try:
+ return self._resolve_typed_receiver(
+ file_path, replace(call, receiver_name=variable), caller_id
+ )
+ finally:
+ self._apex_retyping = False
return self._apex_member_call(file_path, call, caller_id, type_id)
def _apex_member_call(
@@ -760,6 +771,17 @@ class LanguageStrategiesMixin:
return ResolvedCall(caller_id, sym_id, 0.93, call.line, "receiver_same_file")
return ResolvedCall(caller_id, sym_id, 0.90, call.line, "receiver_same_package")
+ def _apex_variable_spelling(self, file_path: str, caller_id: str, receiver: str) -> str | None:
+ """The local, parameter or field *receiver* names in another case, as declared."""
+ if "." in receiver:
+ return None
+ declared = (
+ *self._declared_types_in(file_path, caller_id, "apex"),
+ *self._field_types_in(file_path, "apex").get(self._caller_class_id(caller_id), {}),
+ )
+ folded = receiver.lower()
+ return next((name for name in declared if name.lower() == folded and name != receiver), None)
+
def _apex_variable(self, file_path: str, caller_id: str, receiver: str) -> bool:
"""Is the head of *receiver* a local, parameter or field the caller declares?"""
head = receiver.partition(".")[0]
diff --git a/packages/core/src/repowise/core/ingestion/call_overload_selection.py b/packages/core/src/repowise/core/ingestion/call_overload_selection.py
index 24a634da1..d5d00afec 100644
--- a/packages/core/src/repowise/core/ingestion/call_overload_selection.py
+++ b/packages/core/src/repowise/core/ingestion/call_overload_selection.py
@@ -8,8 +8,10 @@ from __future__ import annotations
from collections import defaultdict
from dataclasses import replace
+from functools import cache
-from .call_receiver_typing import _FUNCTION_KINDS
+from .call_receiver_typing import _FUNCTION_KINDS, _TYPE_KINDS
+from .language_data import get_builtin_types
from .languages.receiver_types import external_type_name
from .models import CallSite, ParsedFile, Symbol
from .resolved_call import ResolvedCall
@@ -170,26 +172,79 @@ def _closest_fit(
return best[0] if len(best) == 1 else None
+# What an Apex argument of each builtin type converts to without a cast.
+_APEX_CONVERSIONS = {
+ "integer": frozenset({"long", "decimal", "double"}),
+ "long": frozenset({"decimal", "double"}),
+ "decimal": frozenset({"double"}),
+ "id": frozenset({"string"}),
+ "string": frozenset({"id"}),
+ "date": frozenset({"datetime"}),
+}
+
+
+# Builtin types no repository class can extend or implement.
+_APEX_VALUE_TYPES = frozenset(
+ {"blob", "boolean", "date", "datetime", "decimal", "double", "id", "integer", "list",
+ "long", "map", "set", "string", "time"}
+)
+
+
def _exact_apex_fit(
- members: list[tuple[str, list[str]]], argument_types: tuple[str | None, ...]
+ members: list[tuple[str, list[str]]],
+ argument_types: tuple[str | None, ...],
+ repo_types: frozenset[str],
) -> str | None:
"""The one Apex member whose parameters are exactly the typed arguments' types.
- Apex widens and converts (``Integer`` to ``Long``, ``Id`` to ``String``) by
- rules the Java tables do not hold, so only an exact match, compared
- without case, is evidence: it is the most specific member whatever else
- takes the call. Anything less leaves the tie unbroken.
+ Apex widens and converts by rules the Java tables do not hold, so only an
+ exact match, compared without case, is evidence. Where the members differ
+ on an untyped argument's parameter, it decides only when no other member
+ could take the typed arguments too: that argument may be one the exact
+ member cannot take.
"""
- exact = [
- member
- for member, parameters in members
- if all(
- index < len(parameters) and parameters[index].lower() == argument.lower()
- for index, argument in enumerate(argument_types)
- if argument is not None
+ typed = [(index, argument.lower()) for index, argument in enumerate(argument_types) if argument]
+
+ def takes(parameters: list[str], accepts) -> bool:
+ return all(
+ index < len(parameters) and accepts(parameters[index].lower(), argument)
+ for index, argument in typed
)
- ]
- return exact[0] if len(exact) == 1 else None
+
+ exact = [member for member, parameters in members if takes(parameters, str.__eq__)]
+ if len(exact) != 1:
+ return None
+ if _untyped_agree(members, argument_types, False):
+ # The untyped arguments cannot tell the members apart.
+ return exact[0]
+ others = [parameters for member, parameters in members if member != exact[0]]
+
+ def may_take(parameter: str, argument: str) -> bool:
+ return _apex_may_take(parameter, argument, repo_types)
+
+ return None if any(takes(parameters, may_take) for parameters in others) else exact[0]
+
+
+def _apex_may_take(parameter: str, argument: str, repo_types: frozenset[str]) -> bool:
+ """Could an Apex parameter of type *parameter* take an argument of type *argument*?
+
+ By an implicit conversion, as ``Object``, or as a supertype. A
+ repository class may extend or implement any class or interface that is
+ not a value type; an sObject (``Account``, ``ApexTrigger``) reaches only
+ ``SObject``.
+ """
+ if parameter in (argument, "object") or parameter in _APEX_CONVERSIONS.get(argument, ()):
+ return True
+ if argument in _apex_builtin_types():
+ return False
+ if argument not in repo_types:
+ return parameter == "sobject"
+ return parameter not in _APEX_VALUE_TYPES
+
+
+@cache
+def _apex_builtin_types() -> frozenset[str]:
+ return frozenset(name.lower() for name in get_builtin_types("apex"))
def _untyped_agree(
@@ -484,11 +539,21 @@ class OverloadSelectionMixin:
return found
typed = [(m, erased_parameter_types(self._symbols_by_id[m])) for m in found]
if self._symbols_by_id[found[0]].language == "apex":
- closest = _exact_apex_fit(typed, argument_types)
+ closest = _exact_apex_fit(typed, argument_types, self._folded_type_names())
else:
closest = _closest_fit(typed, argument_types, expanded)
return found if closest is None else [closest]
+ def _folded_type_names(self) -> frozenset[str]:
+ """The repository's Apex type names, lowercased, built once."""
+ if self._folded_types is None:
+ self._folded_types = frozenset(
+ symbol.name.lower()
+ for symbol in self._symbols_by_id.values()
+ if symbol.language == "apex" and symbol.kind in _TYPE_KINDS
+ )
+ return self._folded_types
+
def _typed_arguments(self, file_path: str, call: CallSite) -> CallSite:
"""*call* with each named argument's declared type beside its literals' types.
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 5ad0375c2..2382ac6fc 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -378,6 +378,7 @@ class CallResolver(
self._known_type_names = frozenset(
symbol.name for symbol in self._symbols_by_id.values() if symbol.kind in _TYPE_KINDS
)
+ self._folded_types: frozenset[str] | None = None
# Narrowed to C# for the extension index: the set above is a bare
# cross-language name match, so a type of that name in any language
# would admit an extension on the BCL type it shadows.
@@ -1962,6 +1963,9 @@ class CallResolver(
if key in merged_methods:
return merged_methods[key], "import"
+ # An Apex type is one its project reaches (a strategy answers that), never repo-wide.
+ if self._language_of(file_path) == "apex":
+ return None
return self._repo_wide_method(key, spelled or key[0])
def _repo_wide_method(self, key: tuple[str, str], spelled: str) -> tuple[str, str] | None:
diff --git a/packages/core/src/repowise/core/ingestion/heritage_resolver.py b/packages/core/src/repowise/core/ingestion/heritage_resolver.py
index c193bb6d6..ea020e70a 100644
--- a/packages/core/src/repowise/core/ingestion/heritage_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/heritage_resolver.py
@@ -29,6 +29,7 @@ from __future__ import annotations
from collections import defaultdict
from collections.abc import Callable, Iterable
from dataclasses import dataclass
+from pathlib import Path
from typing import Any, TypeVar
import structlog
@@ -149,8 +150,10 @@ class HeritageResolver:
# Keep reference for cross-language checks in Tier 3
self._parsed_files = parsed_files
- # Built on the first Apex relation (see ``_apex_parent``).
+ # Built on the first Apex relation (see ``_apex_namespaces_index``).
self._apex_namespaces: Any = None
+ # The one Apex file whose heritage clauses are being read.
+ self._apex_texts: dict[str, str] = {}
self._build_indices(parsed_files)
@@ -244,6 +247,28 @@ class HeritageResolver:
parent_name = rel.parent_name
edge_type = _heritage_kind_to_edge_type(rel.kind)
+ # Apex has no imports: the parent is a type its project reaches, or none.
+ if self._is_apex(file_path):
+ index = self._apex_namespaces_index()
+ # Two parents may share a last segment (``Database.Batchable`` and
+ # ``Plugin.Batchable``); the one the repository declares is the edge.
+ found = {
+ file_types[parent_name]
+ if "." not in written and parent_name in file_types
+ else index.type_path(file_path, written)
+ for written in self._apex_written_parents(file_path, rel)
+ } - {None}
+ if len(found) != 1:
+ return None
+ apex_parent = found.pop()
+ return ResolvedHeritage(
+ child_id=child_id,
+ parent_id=apex_parent,
+ edge_type=edge_type,
+ confidence=0.95 if apex_parent.startswith(f"{file_path}::") else 0.90,
+ line=rel.line,
+ )
+
if parent_name in file_types:
return ResolvedHeritage(
child_id=child_id,
@@ -278,17 +303,6 @@ class HeritageResolver:
line=rel.line,
)
- # Apex has no imports: the parent is a type of the child's own project.
- apex_parent = self._apex_parent(file_path, parent_name)
- if apex_parent is not None:
- return ResolvedHeritage(
- child_id=child_id,
- parent_id=apex_parent,
- edge_type=edge_type,
- confidence=0.90,
- line=rel.line,
- )
-
# Tier 3: global unique match — only within the same language
candidates = self._global_types.get(parent_name, [])
if len(candidates) == 1:
@@ -306,15 +320,30 @@ class HeritageResolver:
return None
- def _apex_parent(self, file_path: str, parent_name: str) -> str | None:
+ def _is_apex(self, file_path: str) -> bool:
parsed = self._parsed_files.get(file_path)
- if parsed is None or parsed.file_info.language != "apex":
- return None
+ return parsed is not None and parsed.file_info.language == "apex"
+
+ def _apex_written_parents(self, file_path: str, rel: HeritageRelation) -> list[str]:
+ """The parent's paths as the Apex clause writes them (``Outer.Inner``)."""
+ from .languages.apex_namespace import written_parents
+
+ text = self._apex_texts.get(file_path)
+ if text is None:
+ abs_path = self._parsed_files[file_path].file_info.abs_path
+ try:
+ text = Path(abs_path).read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ text = ""
+ self._apex_texts = {file_path: text}
+ return written_parents(text, rel.line, rel.parent_name)
+
+ def _apex_namespaces_index(self) -> Any:
if self._apex_namespaces is None:
from .languages.apex_namespace import build_apex_namespaces
self._apex_namespaces = build_apex_namespaces(self._parsed_files)
- return self._apex_namespaces.top_level_type(file_path, parent_name)
+ return self._apex_namespaces
def _heritage_kind_to_edge_type(kind: str) -> str:
diff --git a/packages/core/src/repowise/core/ingestion/languages/apex_namespace.py b/packages/core/src/repowise/core/ingestion/languages/apex_namespace.py
index 38d3a05c0..fa3c19f5f 100644
--- a/packages/core/src/repowise/core/ingestion/languages/apex_namespace.py
+++ b/packages/core/src/repowise/core/ingestion/languages/apex_namespace.py
@@ -9,9 +9,10 @@ The namespace. One sfdx project (the directory holding ``sfdx-project.json``,
all its package directories together) is one flat namespace; files under no
project, the legacy ``src/`` layout, share one more. A repository of many
projects (LightningFlowComponents ships 192) declares the same class name in
-several of them, and a name is only ever looked up in the caller's own project.
-The project's ``namespace`` is the prefix the code may write before its own
-classes (``npsp.Foo``); any other prefix names a managed package's class. A
+several of them, and a name is looked up in the caller's own project, then in
+the un-namespaced packages it declares a dependency on. A namespace prefix
+(``npsp.Foo``, ``usf3.Foo``) names the repo project of that namespace; any
+other prefix names a managed package's class. A
project may also keep a second copy of its classes outside its package
directories (a legacy ``mdapi/`` export); a name declared in both is read in the
copy the caller is deployed with.
@@ -25,6 +26,7 @@ the spelling the repository declares. Declarations keep their own spelling.
from __future__ import annotations
import json
+import re
from collections import defaultdict
from collections.abc import Iterable
from dataclasses import dataclass, replace
@@ -32,67 +34,120 @@ from pathlib import Path, PurePosixPath
from typing import Any
from ..symbol_identity import outer_scope, symbol_id_path
+from ..type_names import bare_type_name, dotted_type_segments
_SFDX_PROJECT = "sfdx-project.json"
_TYPE_KINDS = frozenset({"class", "interface", "enum"})
+@dataclass(frozen=True, slots=True)
+class _Manifest:
+ """What one ``sfdx-project.json`` declares."""
+
+ namespace: str = "" # lowercased; "" when the project has none
+ package_dirs: tuple[str, ...] = () # repo-relative, no trailing slash
+ packages: frozenset[str] = frozenset() # the packages its directories build
+ dependencies: frozenset[str] = frozenset() # the packages they depend on
+
+
@dataclass(frozen=True, slots=True)
class ApexNamespaces:
"""Which project each Apex file belongs to, and the types each project declares."""
#: Apex file -> its project directory (repo-relative; "" is the repo root).
project_of: dict[str, str]
- #: project -> its own namespace prefixes, lowercased.
- own_prefixes: dict[str, frozenset[str]]
- #: project -> its package directories (repo-relative, no trailing slash).
- package_dirs: dict[str, tuple[str, ...]]
+ #: project -> what its manifest declares.
+ manifests: dict[str, _Manifest]
#: (project, lowercased name) -> ids of the top-level types declared so.
top_level: dict[tuple[str, str], tuple[str, ...]]
#: (outer type id, lowercased name) -> id of the member type declared so.
members: dict[tuple[str, str], str]
+ #: project -> the un-namespaced projects building a package it depends on.
+ dependencies: dict[str, tuple[str, ...]]
+ #: lowercased namespace -> the projects declaring it.
+ by_namespace: dict[str, tuple[str, ...]]
def top_level_type(self, file_path: str, name: str) -> str | None:
- """The one top-level type *name* means from *file_path*'s project, or None.
-
- A name declared twice in one project is read in the declaration
- deployed with the caller: the one in the caller's package directory,
- or, for a caller outside every package directory, the one outside them
- too. Any other pair is a tie nothing breaks, and neither is chosen.
+ """The one top-level type *name* means from *file_path*, or None.
+
+ Looked up in the caller's own project, else in the un-namespaced
+ projects it declares a dependency on (a namespaced one is reached only
+ through its prefix). A name declared twice in one project is read in
+ the declaration deployed with the caller: the one in the caller's
+ package directory, or outside them all for a caller outside them. Any
+ other pair is a tie, and neither is chosen.
"""
project = self.project_of.get(file_path)
if project is None:
return None
+ if (project, name.lower()) in self.top_level:
+ found = self._declared(project, name, self._deploy_unit(project, file_path))
+ else:
+ found = tuple(
+ type_id
+ for dependency in self.dependencies.get(project, ())
+ for type_id in self._declared(dependency, name)
+ )
+ return found[0] if len(found) == 1 else None
+
+ def prefixed_type(self, file_path: str, prefix: str, name: str) -> str | None:
+ """The type ``prefix.name`` means, *prefix* being the namespace of a repo project."""
+ project = self.project_of.get(file_path)
+ if project is None or not prefix:
+ return None
+ if prefix.lower() == self.manifests[project].namespace:
+ found = self._declared(project, name, self._deploy_unit(project, file_path))
+ return found[0] if len(found) == 1 else None
+ found = tuple(
+ type_id
+ for other in self.by_namespace.get(prefix.lower(), ())
+ for type_id in self._declared(other, name)
+ )
+ return found[0] if len(found) == 1 else None
+
+ def member_type(self, owner_id: str, name: str) -> str | None:
+ return self.members.get((owner_id, name.lower()))
+
+ def type_path(self, file_path: str, written: str) -> str | None:
+ """The type a written path (``Outer.Inner``, ``usf3.Outer.Inner``) names from *file_path*.
+
+ The head is a top-level type the caller reaches, else a namespace
+ prefix; each later segment is a member type of the one before. An
+ outer type that is unknown or external names nothing.
+ """
+ head, *rest = dotted_type_segments(written)
+ type_id = self.top_level_type(file_path, head)
+ if type_id is None and rest:
+ prefix, (head, *rest) = head, rest
+ type_id = self.prefixed_type(file_path, prefix, head)
+ for segment in rest:
+ if type_id is None:
+ return None
+ type_id = self.member_type(type_id, segment)
+ return type_id
+
+ def _declared(self, project: str, name: str, unit: str | None = None) -> tuple[str, ...]:
+ """*project*'s top-level types named *name*, narrowed to deploy *unit* when several."""
found = self.top_level.get((project, name.lower()), ())
if len(found) > 1:
- unit = self._deploy_unit(project, file_path)
found = tuple(
type_id
for type_id in found
if self._deploy_unit(project, symbol_id_path(type_id)) == unit
)
- return found[0] if len(found) == 1 else None
+ return found
def _deploy_unit(self, project: str, path: str) -> str | None:
"""The package directory *path* is deployed from, or None outside them all."""
return next(
- (d for d in self.package_dirs.get(project, ()) if path.startswith(f"{d}/")), None
+ (d for d in self.manifests[project].package_dirs if path.startswith(f"{d}/")), None
)
- def member_type(self, owner_id: str, name: str) -> str | None:
- return self.members.get((owner_id, name.lower()))
-
- def strips_prefix(self, file_path: str, segment: str) -> bool:
- """Is *segment* the caller's own project namespace, written before one of its classes?"""
- project = self.project_of.get(file_path)
- return project is not None and segment.lower() in self.own_prefixes.get(project, ())
def build_apex_namespaces(parsed_files: dict[str, Any]) -> ApexNamespaces:
"""Index every parsed Apex file by project. Reads each ``sfdx-project.json`` once."""
project_of: dict[str, str] = {}
- prefixes: dict[str, frozenset[str]] = {}
- package_dirs: dict[str, tuple[str, ...]] = {}
top_level: dict[tuple[str, str], list[str]] = defaultdict(list)
members: dict[tuple[str, str], str] = {}
projects = _ProjectFinder()
@@ -101,8 +156,6 @@ def build_apex_namespaces(parsed_files: dict[str, Any]) -> ApexNamespaces:
continue
project = projects.project_of(path, parsed.file_info.abs_path)
project_of[path] = project
- prefixes.setdefault(project, projects.prefixes.get(project, frozenset()))
- package_dirs.setdefault(project, projects.package_dirs.get(project, ()))
for symbol in parsed.symbols:
if symbol.kind not in _TYPE_KINDS:
continue
@@ -110,10 +163,16 @@ def build_apex_namespaces(parsed_files: dict[str, Any]) -> ApexNamespaces:
top_level[(project, symbol.name.lower())].append(symbol.id)
else:
members.setdefault((outer_scope(symbol.id), symbol.name.lower()), symbol.id)
+ manifests = {p: projects.manifests.get(p, _Manifest()) for p in set(project_of.values())}
+ by_namespace: dict[str, list[str]] = defaultdict(list)
+ for project, manifest in manifests.items():
+ if manifest.namespace:
+ by_namespace[manifest.namespace].append(project)
return ApexNamespaces(
project_of=project_of,
- own_prefixes=prefixes,
- package_dirs=package_dirs,
+ manifests=manifests,
+ dependencies={p: _dependencies(p, manifests) for p in manifests},
+ by_namespace={ns: tuple(found) for ns, found in by_namespace.items()},
top_level={key: tuple(ids) for key, ids in top_level.items()},
members=members,
)
@@ -124,8 +183,7 @@ class _ProjectFinder:
def __init__(self) -> None:
self._dirs: dict[str, str] = {}
- self.prefixes: dict[str, frozenset[str]] = {}
- self.package_dirs: dict[str, tuple[str, ...]] = {}
+ self.manifests: dict[str, _Manifest] = {}
def project_of(self, path: str, abs_path: str) -> str:
rel = PurePosixPath(path)
@@ -142,7 +200,7 @@ class _ProjectFinder:
manifest = root / directory / _SFDX_PROJECT
if manifest.is_file():
found = directory
- self.prefixes[found], self.package_dirs[found] = _read_manifest(manifest, directory)
+ self.manifests[found] = _read_manifest(manifest, directory)
elif directory:
found = self._project_of_dir(PurePosixPath(directory).parent.as_posix(), root)
else:
@@ -151,17 +209,53 @@ class _ProjectFinder:
return found
-def _read_manifest(manifest: Path, project: str) -> tuple[frozenset[str], tuple[str, ...]]:
- """``(own namespace prefixes, package directories)`` an ``sfdx-project.json`` declares."""
+def _read_manifest(manifest: Path, project: str) -> _Manifest:
+ """What an ``sfdx-project.json`` declares; nothing when it cannot be read."""
try:
data = json.loads(manifest.read_text(encoding="utf-8-sig"))
namespace = data.get("namespace")
- entries = data.get("packageDirectories") or []
- written = [e.get("path") for e in entries if isinstance(e, dict)]
+ entries = [e for e in data.get("packageDirectories") or [] if isinstance(e, dict)]
+ dependencies = [d for e in entries for d in e.get("dependencies") or []]
except (OSError, ValueError, AttributeError, TypeError):
- return frozenset(), ()
- prefixes = frozenset({namespace.lower()}) if isinstance(namespace, str) and namespace else frozenset()
- return prefixes, _package_dirs(written, project)
+ return _Manifest()
+ return _Manifest(
+ namespace=namespace.lower() if isinstance(namespace, str) else "",
+ package_dirs=_package_dirs([e.get("path") for e in entries], project),
+ packages=_names(e.get("package") for e in entries),
+ # ``[email protected]`` is a version of the package ``Base``.
+ dependencies=_names(
+ d.get("package", "").partition("@")[0] for d in dependencies if isinstance(d, dict)
+ ),
+ )
+
+
+def _dependencies(project: str, manifests: dict[str, _Manifest]) -> tuple[str, ...]:
+ """The un-namespaced projects building a package *project* depends on."""
+ wanted = manifests[project].dependencies
+ return tuple(
+ other
+ for other, manifest in manifests.items()
+ if other != project and not manifest.namespace and manifest.packages & wanted
+ )
+
+
+def written_parents(text: str, line: int, parent: str) -> list[str]:
+ """The paths a heritage clause on *line* writes for parents named *parent*.
+
+ The relation keeps only the last segment; the clause runs from the
+ declaration line to its opening brace. ``[parent]`` when none is found.
+ """
+ header = "\n".join(text.splitlines()[line - 1 : line + 9]).partition("{")[0]
+ clause = re.split(r"(?i)\b(?:extends|implements)\b", header, maxsplit=1)
+ paths = ["".join(m.split()) for m in _DOTTED_NAME.findall(clause[1] if len(clause) > 1 else "")]
+ return [p for p in paths if bare_type_name(p).lower() == parent.lower()] or [parent]
+
+
+_DOTTED_NAME = re.compile(r"[A-Za-z_]\w*(?:\s*\.\s*[A-Za-z_]\w*)*")
+
+
+def _names(values: Iterable[Any]) -> frozenset[str]:
+ return frozenset(value for value in values if isinstance(value, str) and value)
def _package_dirs(written: list[Any], project: str) -> tuple[str, ...]:
diff --git a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
index 938efc005..7c70567d9 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -970,11 +970,17 @@ def _usable_type_name(raw: str, language: str) -> tuple[str | None, bool]:
return None, False
inner = unwrap_pointer_like(raw) if language == "cpp" else None
name = inner or (raw if raw.isidentifier() else bare_type_name(raw))
- if not is_resolvable_type_name(name, language):
+ if not is_resolvable_type_name(name, language) and not _apex_member_of_repo_type(raw, language):
return None, False
return written_type_key(name, raw, language), inner is not None
+def _apex_member_of_repo_type(raw: str, language: str) -> bool:
+ """``LoggerPlugin.Batchable``: a member type named like a builtin, qualified by a repo type."""
+ qualifier = type_qualifier(raw) if language == "apex" else None
+ return bool(qualifier) and is_resolvable_type_name(bare_type_name(qualifier), language)
+
+
# Languages whose constructor parameter lists sit at class scope, unextracted,
# with defaults closing on `=`: a declaration inside parentheses owns no field.
_PARAMETERS_AT_CLASS_SCOPE = frozenset({"dart"})
diff --git a/packages/core/src/repowise/core/ingestion/type_names.py b/packages/core/src/repowise/core/ingestion/type_names.py
index 5b2dc5e8f..a52b7d875 100644
--- a/packages/core/src/repowise/core/ingestion/type_names.py
+++ b/packages/core/src/repowise/core/ingestion/type_names.py
@@ -157,6 +157,11 @@ def type_qualifier(raw: str) -> str:
return head.rstrip("".join(_QUALIFIER_SEPARATORS))
+def dotted_type_segments(raw: str) -> list[str]:
+ """``ns.Outer.Inner<T>`` -> ``["ns", "Outer", "Inner"]``: a dotted type path, segment by segment."""
+ return [segment.strip() for segment in strip_type_arguments(raw.strip()).split(".")]
+
+
# C++ template heads whose ``operator->`` forwards to their argument, so
# ``shared_ptr<Foo> p`` makes ``p->m()`` a call on ``Foo``. Only these: a
# container holds a ``T`` without being one, and unwrapping ``vector<Foo>``
diff --git a/tests/unit/ingestion/test_apex_resolution.py b/tests/unit/ingestion/test_apex_resolution.py
index 86f16b2fe..1c7945151 100644
--- a/tests/unit/ingestion/test_apex_resolution.py
+++ b/tests/unit/ingestion/test_apex_resolution.py
@@ -308,3 +308,148 @@ def test_a_property_is_never_the_callee(tmp_path: Path) -> None:
})
calls = _calls(_build(tmp_path), _id("Caller.cls", "Caller::go"))
assert calls == {_id("Base.cls", "Base::status"): "receiver_same_package"}
+
+
+def _with_dependency(root: Path, files: dict[str, str], package: str, depends_on: str) -> None:
+ _project(root, files)
+ manifest = {
+ "packageDirectories": [
+ {
+ "path": "force-app",
+ "package": package,
+ "dependencies": [{"package": f"{depends_on}@1.0.0-0"}] if depends_on else [],
+ }
+ ],
+ "namespace": "",
+ }
+ (root / "sfdx-project.json").write_text(json.dumps(manifest))
+
+
+def test_another_project_is_reached_only_through_a_dependency(tmp_path: Path) -> None:
+ base = "public virtual class Base {\n public static void help() {}\n}\n"
+ child = (
+ "public class Child extends Base {\n"
+ " void go() { Base.help(); }\n"
+ "}\n"
+ )
+ _with_dependency(tmp_path / "base", {"Base.cls": base}, "BasePack", "")
+ _with_dependency(tmp_path / "uses", {"Child.cls": child}, "Uses", "BasePack")
+ _with_dependency(tmp_path / "other", {"Child.cls": child}, "Other", "")
+ graph = _build(tmp_path)
+ base_id = _id("Base.cls", "Base", "base")
+ assert graph.has_edge(_id("Child.cls", "Child", "uses"), base_id)
+ assert _calls(graph, _id("Child.cls", "Child::go", "uses")) == {
+ _id("Base.cls", "Base::help", "base"): "receiver_same_package"
+ }
+ # No declared dependency: no heritage edge and no call edge across projects.
+ assert not graph.has_edge(_id("Child.cls", "Child", "other"), base_id)
+ assert _calls(graph, _id("Child.cls", "Child::go", "other")) == {}
+
+
+def test_a_namespaced_project_is_reached_through_its_prefix(tmp_path: Path) -> None:
+ _project(tmp_path / "base", {"Util.cls": "public class Util {\n public static void help() {}\n}\n"}, namespace="usf3")
+ _project(tmp_path / "uses", {
+ "Caller.cls": "public class Caller {\n void go() { usf3.Util.help(); Util.help(); }\n}\n",
+ })
+ calls = _calls(_build(tmp_path), _id("Caller.cls", "Caller::go", "uses"))
+ assert calls == {_id("Util.cls", "Util::help", "base"): "receiver_same_package"}
+
+
+def test_an_exact_argument_type_decides_only_when_no_other_overload_could_take_it(
+ tmp_path: Path,
+) -> None:
+ _project(tmp_path, {
+ "Log.cls": (
+ "public class Log {\n"
+ " public static void add(Exception error, Long code) {}\n"
+ " public static void add(String message, Integer level) {}\n"
+ " public static void put(Id record, Account owner) {}\n"
+ " public static void put(String name, Integer level) {}\n"
+ " public static void link(Account owner, String note) {}\n"
+ " public static void link(Contact person, Integer rank) {}\n"
+ "}\n"
+ ),
+ "Caller.cls": (
+ "public class Caller {\n"
+ " void go(String name, Contact person) {\n"
+ " Log.add('x', unknown);\n"
+ " Log.put(name, unknown);\n"
+ " Log.link(person, unknown);\n"
+ " }\n"
+ "}\n"
+ ),
+ })
+ calls = _calls(_build(tmp_path), _id("Caller.cls", "Caller::go"))
+ # A String never becomes an Exception, so ``add`` is chosen; it may become
+ # an Id, so the untyped argument could still mean the first ``put``, which
+ # stands for the set.
+ assert set(calls) == {
+ _id("Log.cls", "Log::add#2(String,Integer)"),
+ _id("Log.cls", "Log::put#2(Id,Account)"),
+ # One sObject never stands for another, so the Contact member is chosen.
+ _id("Log.cls", "Log::link#2(Contact,Integer)"),
+ }
+
+
+def test_a_variable_in_another_case_and_a_builtin_named_member_type(tmp_path: Path) -> None:
+ _project(tmp_path, {
+ "Plugin.cls": (
+ "public class Plugin {\n"
+ " public interface Batchable { void start(); }\n"
+ " public void run() {}\n"
+ "}\n"
+ ),
+ "Caller.cls": (
+ "public class Caller {\n"
+ " void go(Plugin.Batchable batch) {\n"
+ " Plugin worker = new Plugin();\n"
+ " WORKER.run();\n"
+ " batch.start();\n"
+ " }\n"
+ "}\n"
+ ),
+ })
+ calls = _calls(_build(tmp_path), _id("Caller.cls", "Caller::go"))
+ assert calls[_id("Plugin.cls", "Plugin::run")] == "receiver_typed_same_package"
+ assert calls[_id("Plugin.cls", "Batchable::start")] == "receiver_typed_same_package"
+
+
+def test_a_qualified_parent_is_read_through_its_outer_type(tmp_path: Path) -> None:
+ _project(tmp_path, {
+ "Metadata.cls": "public class Metadata {\n public virtual class FlowNode {}\n}\n",
+ "Other.cls": "public class Other {}\n",
+ "Right.cls": "public class Right extends Metadata.FlowNode {}\n",
+ "Wrong.cls": "public class Wrong extends Other.FlowNode {}\n",
+ "Managed.cls": "public class Managed extends pkg.Outer.FlowNode {}\n",
+ })
+ graph = _build(tmp_path)
+ flow_node = _id("Metadata.cls", "Metadata::FlowNode")
+ assert graph.has_edge(_id("Right.cls", "Right"), flow_node)
+ assert not graph.has_edge(_id("Wrong.cls", "Wrong"), flow_node)
+ assert not graph.has_edge(_id("Managed.cls", "Managed"), flow_node)
+
+
+def test_the_own_namespace_prefix_never_reaches_a_dependency(tmp_path: Path) -> None:
+ util = "public class Util {\n public static void help() {}\n}\n"
+ _with_dependency(tmp_path / "base", {"Util.cls": util}, "BasePack", "")
+ _with_dependency(
+ tmp_path / "uses",
+ {
+ "Caller.cls": (
+ "public class Caller {\n"
+ " void prefixed() { acme.Util.help(); }\n"
+ " void bare() { Util.help(); }\n"
+ "}\n"
+ )
+ },
+ "Uses",
+ "BasePack",
+ )
+ manifest = tmp_path / "uses" / "sfdx-project.json"
+ manifest.write_text(manifest.read_text().replace('"namespace": ""', '"namespace": "acme"'))
+ graph = _build(tmp_path)
+ # Only the unprefixed call reaches the dependency's class.
+ assert _calls(graph, _id("Caller.cls", "Caller::prefixed", "uses")) == {}
+ assert _calls(graph, _id("Caller.cls", "Caller::bare", "uses")) == {
+ _id("Util.cls", "Util::help", "base"): "receiver_same_package"
+ }