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): resolve calls, heritage and type references in each sfdx project's namespace (#4417)

Raghav Chamadiya362ba22a79d0
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.md
index 32de4ccef..78645d0f3 100644
--- a/docs/architecture/language-support.md
+++ b/docs/architecture/language-support.md
@@ -967,8 +967,14 @@ inline SOQL/SOSL and DML are their own nodes and never produce call sites.
Keywords and type names are case-insensitive: visibility and heritage read the
AST rather than keyword text, and builtin types are compared folded, while
declared names keep their written case. CumulusCI `%%%NAMESPACE%%%` tokens are
-blanked byte for byte before parsing. Apex has no import statement, so
-cross-file calls resolve only through the repository-wide tiers.
+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,
+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.
A `@RestResource` class's `@Http*` methods are HTTP providers at
`/services/apexrest` plus its `urlMapping`, and are entry points in the graph.
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index b2bd76030..33858ffa7 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -75,8 +75,9 @@ Scala, Elixir and F# have dedicated import resolvers with known gaps; see
\* COBOL is excluded from dead-code claims: JCL, schedulers and dynamic program
calls are entry paths the repository graph cannot observe.
Apex (`.cls`, `.trigger`, `.apex`) is parsed for symbols, heritage and calls,
-and is excluded from dead-code claims the same way until triggers, annotations
-and platform interfaces are modelled as entry points. Apex test coverage from the
+resolved case-insensitively within each sfdx project's namespace, and is
+excluded from dead-code claims the same way until triggers, annotations and
+platform interfaces are modelled as entry points. Apex test coverage from the
Salesforce CLI is read as a coverage report ([formats](TEST_INTELLIGENCE.md#supported-formats)).
## How accurate is the graph per language
diff --git a/packages/core/src/repowise/core/ingestion/call_inheritance.py b/packages/core/src/repowise/core/ingestion/call_inheritance.py
index 6a8f712a0..beaa54964 100644
--- a/packages/core/src/repowise/core/ingestion/call_inheritance.py
+++ b/packages/core/src/repowise/core/ingestion/call_inheritance.py
@@ -19,8 +19,8 @@ _MAX_ANCESTOR_EXPAND_DEPTH = 3
def _is_super_call(call: CallSite, language: str) -> bool:
- """Python's ``super().m()`` (a chained call) or Java's ``super.m()``."""
- if language == "java":
+ """Python's ``super().m()`` (a chained call), or Java's and Apex's ``super.m()``."""
+ if language in ("java", "apex"):
return call.receiver_name == "super"
receiver = call.receiver_call
return (
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 91c5c9e55..65ceffb6f 100644
--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py
+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
@@ -142,11 +142,14 @@ _LANGUAGE_CALL_STRATEGIES: dict[str, _LanguageCallStrategies] = {
"rust": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),
"cpp": _CPP_STRATEGIES,
"c": _CPP_STRATEGIES,
- # Apex has no strategy of its own yet. A member or chained call no tier
- # claims stays unresolved rather than binding by bare name, which is the
- # measured Java rule: ``System.debug()`` and ``acc.get('x')`` would
- # otherwise bind any one repo method called ``debug`` or ``get``.
- "apex": _LanguageCallStrategies(member_bare_fallback=False),
+ # Apex resolves type names in its project namespace; no bare-name fallback (Java's rule).
+ "apex": _LanguageCallStrategies(
+ free=("_resolve_apex_namespace_type",),
+ member=("_resolve_apex_receiver_type",),
+ member_fallback=_TYPED_RECEIVER,
+ member_bare_fallback=False,
+ inherited_typed_receiver=True,
+ ),
}
@@ -177,6 +180,9 @@ class LanguageStrategiesMixin:
self._jvm_index: Any = None
self._jvm_index_built = False
+ # Apex project namespaces (lazy ApexNamespaces)
+ self._apex_namespaces: Any = None
+
# C/C++ same-target resolution (lazy CppWorkspaceIndex)
self._cpp_index: Any = None
self._cpp_index_built = False
@@ -617,6 +623,149 @@ class LanguageStrategiesMixin:
return ResolvedCall(caller_id, sym_id, 0.90, call.line, "same_package")
return None
+ def _get_apex_namespaces(self) -> Any:
+ """Lazily build the ApexNamespaces index."""
+ 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
+
+ def _apex_type(self, file_path: str, caller_id: str, written: str) -> str | None:
+ """The type id an Apex type path (``Foo``, ``Outer.Inner``, ``ns.Foo``) names here.
+
+ 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
+ member type of the one before it.
+ """
+ index = self._get_apex_namespaces()
+ head, *rest = written.split(".")
+ 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)
+ for segment in rest:
+ if type_id is None:
+ return None
+ type_id = index.member_type(type_id, segment)
+ return type_id
+
+ def _apex_head_type(self, file_path: str, caller_id: str, name: str) -> str | None:
+ """The type a bare Apex type name means in *caller_id*.
+
+ A member type of the caller's class, or of one of its ancestors (a
+ handler subclass writes its base's ``DmlWrapper`` bare), then the same
+ for each class around it, then a top-level type.
+ """
+ index = self._get_apex_namespaces()
+ caller = self._symbols_by_id.get(caller_id)
+ scope = (
+ caller_id
+ if caller is not None and caller.kind in _TYPE_KINDS
+ else self._caller_class_id(caller_id)
+ )
+ while "::" in scope:
+ for owner in (scope, *self._ancestors_of(scope)):
+ member = index.member_type(owner, name)
+ if member is not None:
+ return member
+ scope = outer_scope(scope)
+ return index.top_level_type(file_path, name)
+
+ def _apex_type_call(
+ self, file_path: str, caller_id: str, type_id: str, line: int, origin: str
+ ) -> ResolvedCall | None:
+ """``new T(..)``: *type_id*'s constructors when it declares any, else the type."""
+ symbol = self._symbols_by_id[type_id]
+ path = self._symbol_paths_by_id[type_id]
+ target = self._file_methods.get(path, {}).get((symbol.name, symbol.name), type_id)
+ if target == caller_id:
+ return None
+ if path == file_path:
+ return ResolvedCall(caller_id, target, 0.93, line, "receiver_same_file")
+ return ResolvedCall(caller_id, target, 0.90, line, origin)
+
+ def _resolve_apex_namespace_type(
+ self,
+ file_path: str,
+ call: CallSite,
+ caller_id: str,
+ ) -> ResolvedCall | None:
+ """``new Foo(..)``: the type its name means in the caller's project.
+
+ A bare Apex name reaches no other class's method, so only a type is
+ looked up. The class and its constructors share the name, which is
+ why the uniqueness-gated global tier refuses this call.
+ """
+ type_id = self._apex_head_type(file_path, caller_id, call.target_name)
+ # Only the type's own spelling: ``execute()`` inherited from a platform
+ # class is not ``new Execute()``.
+ if type_id is None or self._symbols_by_id[type_id].name != call.target_name:
+ return None
+ hit = self._apex_type_call(file_path, caller_id, type_id, call.line, "same_package")
+ if hit is not None and hit.origin == "receiver_same_file":
+ return replace(hit, confidence=0.95, origin="same_file")
+ return hit
+
+ def _resolve_apex_receiver_type(
+ self,
+ file_path: str,
+ call: CallSite,
+ caller_id: str,
+ ) -> ResolvedCall | None:
+ """``Foo.m()``, ``Outer.Inner.m()``, ``new Outer.Inner()``: the receiver names a type.
+
+ A receiver the caller declares as a local, parameter or field is a
+ variable, whatever class shares its folded name: it is left to the
+ typed fallback. ``this`` and ``super`` are left to their own tiers.
+ """
+ receiver = call.receiver_name or ""
+ if receiver in ("this", "super") or self._apex_variable(file_path, caller_id, receiver):
+ return None
+ type_id = self._apex_type(file_path, caller_id, receiver)
+ if type_id is None:
+ return None
+ return self._apex_member_call(file_path, call, caller_id, type_id)
+
+ def _apex_member_call(
+ self, file_path: str, call: CallSite, caller_id: str, type_id: str
+ ) -> ResolvedCall | None:
+ """The member *call* names on the type *type_id*: a member type, a method, an inherited one.
+
+ The name as written first: ``X.errors()`` is the method even where
+ ``X`` also nests a class ``Errors``, which ``new X.Errors()`` means.
+ """
+ sym_id = self._declares(type_id, call.target_name)
+ if sym_id is None:
+ member = self._get_apex_namespaces().member_type(type_id, call.target_name)
+ else:
+ member = sym_id if self._symbols_by_id[sym_id].kind in _TYPE_KINDS else None
+ if member is not None:
+ return self._apex_type_call(
+ file_path, caller_id, member, call.line, "receiver_same_package"
+ )
+ # A property of the name is data, never the callee: an ancestor's method may be.
+ if sym_id is None or self._symbols_by_id[sym_id].kind not in _FUNCTION_KINDS:
+ sym_id = self._ancestor_method(
+ type_id, call.target_name, caller_id, class_chain_first=True
+ )
+ if sym_id is None or sym_id == caller_id:
+ return None
+ if self._symbols_by_id[sym_id].kind not in _FUNCTION_KINDS:
+ return None
+ if self._symbol_paths_by_id.get(sym_id) == file_path:
+ 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(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]
+ type_name, _, _ = self._receiver_type_and_scope(file_path, caller_id, "apex", head)
+ return type_name is not None
+
def _resolve_dart_named_constructor(
self,
file_path: str,
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 421051e52..24a634da1 100644
--- a/packages/core/src/repowise/core/ingestion/call_overload_selection.py
+++ b/packages/core/src/repowise/core/ingestion/call_overload_selection.py
@@ -170,6 +170,28 @@ def _closest_fit(
return best[0] if len(best) == 1 else None
+def _exact_apex_fit(
+ members: list[tuple[str, list[str]]], argument_types: tuple[str | None, ...]
+) -> 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.
+ """
+ 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
+ )
+ ]
+ return exact[0] if len(exact) == 1 else None
+
+
def _untyped_agree(
members: list[tuple[str, list[str]]], argument_types: tuple[str | None, ...], expanded: bool
) -> bool:
@@ -461,7 +483,10 @@ class OverloadSelectionMixin:
if len(found) < 2 or not argument_types:
return found
typed = [(m, erased_parameter_types(self._symbols_by_id[m])) for m in found]
- closest = _closest_fit(typed, argument_types, expanded)
+ if self._symbols_by_id[found[0]].language == "apex":
+ closest = _exact_apex_fit(typed, argument_types)
+ else:
+ closest = _closest_fit(typed, argument_types, expanded)
return found if closest is None else [closest]
def _typed_arguments(self, file_path: str, call: CallSite) -> CallSite:
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 27319f655..5ad0375c2 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -119,7 +119,7 @@ log = structlog.get_logger(__name__)
# Languages with an implicit method receiver, where a bare ``foo()`` binds to
# the caller's instance. Go, Python, PHP and JS/TS spell the receiver out, so a
# bare call there is a free function and this tier would resolve it wrongly.
-_IMPLICIT_RECEIVER_LANGUAGES = frozenset({"java", "csharp", "cpp", "kotlin"})
+_IMPLICIT_RECEIVER_LANGUAGES = frozenset({"java", "csharp", "cpp", "kotlin", "apex"})
# Languages where a call the caller's own class cannot answer is looked for on
# its ancestors, for an explicit ``self``/``this`` receiver and an implicit one.
@@ -129,7 +129,9 @@ _IMPLICIT_RECEIVER_LANGUAGES = frozenset({"java", "csharp", "cpp", "kotlin"})
#
# C# is present: the tier answers with a name's overload set, and
# ``resolve_file`` narrows it to the member the argument count names.
-_INHERITED_LANGUAGES = frozenset({"java", "kotlin", "python", "typescript", "swift", "csharp"})
+_INHERITED_LANGUAGES = frozenset(
+ {"java", "kotlin", "python", "typescript", "swift", "csharp", "apex"}
+)
# VB.NET's own-instance receivers, lowercased: the language is case-insensitive.
_VBNET_SELF_RECEIVERS = frozenset({"me", "myclass"})
@@ -137,7 +139,8 @@ _VBNET_SELF_RECEIVERS = frozenset({"me", "myclass"})
# Languages where a bare name is scoped lexically: it can only mean the
# caller's own module, an explicit ``import`` or ``open``, or the prelude, so
# repo-wide uniqueness is no evidence and only wildcard imports may merge names.
-_LEXICAL_BARE_NAME_LANGUAGES = frozenset({"elixir", "fsharp"})
+# An Apex bare name is never another class's method, however unique.
+_LEXICAL_BARE_NAME_LANGUAGES = frozenset({"elixir", "fsharp", "apex"})
# Languages whose imports name what they bring into scope, so only wildcard
# imports may merge an imported file's names: ``use a::{B, C}`` binds B and C,
@@ -204,7 +207,7 @@ _EXTENSION_KINDS = frozenset({"impl"})
# Languages admitted to the full return-type chain lane; each is admitted
# explicitly, once measured.
PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES: frozenset[str] = frozenset(
- {"cpp", "csharp", "dart", "go", "java", "kotlin", "python"}
+ {"apex", "cpp", "csharp", "dart", "go", "java", "kotlin", "python"}
)
# Chain languages that type the inner call by the identity of the type it
@@ -213,7 +216,7 @@ _RETURNED_TYPE_ID_LANGUAGES = frozenset({"dart", "go", "kotlin", "python"})
# Chain lanes that need a file or import/re-export identity for the head type:
# a repository-global simple type name is not a language binding.
-_BOUND_CHAIN_LANGUAGES = frozenset({"java", "csharp", "typescript", "go"})
+_BOUND_CHAIN_LANGUAGES = frozenset({"java", "csharp", "typescript", "go", "apex"})
def _overload_return_types(
@@ -1288,11 +1291,11 @@ class CallResolver(
A receiver records one hop, but the parser keeps every link of a chain
as its own site on the chain's first line, so the hop below is read
- off the site *inner* names. C#, Dart, Go, Java and Kotlin read it, so a builder chain
- types each link from the one before; elsewhere an inner call is still
- typed as if nothing were chained under it.
+ off the site *inner* names. Apex, C#, Dart, Go, Java and Kotlin read it, so a
+ builder chain types each link from the one before; elsewhere an inner call
+ is still typed as if nothing were chained under it.
"""
- if language not in ("csharp", "dart", "go", "java", "kotlin"):
+ if language not in ("apex", "csharp", "dart", "go", "java", "kotlin"):
return None
sites = self._chained_sites.get(file_path)
if sites is None:
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index 5ddfb5680..729804330 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -21,6 +21,7 @@ from ..cohesion import (
UNIT_FANOUT_LANGUAGES,
withdraw_declaration_hint,
)
+from ..languages.apex_namespace import spell_apex_names
from ..languages.python_modules import dotted_module_for
from ..models import Import, ParsedFile, Symbol, combine_load_kinds
from ..resolvers import ResolverContext, resolve_import
@@ -400,6 +401,8 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
"""
self._invalidate_metric_caches()
self._qualify_python_symbols()
+ # Apex names are case-insensitive; every resolver keys on the declared spelling.
+ spell_apex_names(self._parsed_files.values())
# Clear import/call edges but keep structural edges (defines, has_method)
edges_to_remove = [
diff --git a/packages/core/src/repowise/core/ingestion/heritage_resolver.py b/packages/core/src/repowise/core/ingestion/heritage_resolver.py
index dc9f59d26..c193bb6d6 100644
--- a/packages/core/src/repowise/core/ingestion/heritage_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/heritage_resolver.py
@@ -149,6 +149,8 @@ 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``).
+ self._apex_namespaces: Any = None
self._build_indices(parsed_files)
@@ -276,6 +278,17 @@ 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:
@@ -293,6 +306,16 @@ class HeritageResolver:
return None
+ def _apex_parent(self, file_path: str, parent_name: str) -> str | None:
+ parsed = self._parsed_files.get(file_path)
+ if parsed is None or parsed.file_info.language != "apex":
+ return None
+ 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)
+
def _heritage_kind_to_edge_type(kind: str) -> str:
"""Map HeritageKind to graph edge_type string.
diff --git a/packages/core/src/repowise/core/ingestion/languages/apex_namespace.py b/packages/core/src/repowise/core/ingestion/languages/apex_namespace.py
new file mode 100644
index 000000000..38d3a05c0
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/languages/apex_namespace.py
@@ -0,0 +1,245 @@
+"""Apex's implicit class namespace, and its case-insensitive names.
+
+Apex has no import statement. Every top-level class, interface and enum of a
+Salesforce project is visible by name from every other Apex file deployed with
+it, and identifiers are case-insensitive: ``accountservice.run()`` calls
+``AccountService.Run``. Two facts follow, and this module holds both.
+
+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
+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.
+
+The spelling. Every resolver index is keyed on the declared name, so the one
+seam that folds case is :func:`spell_apex_names`, run once before the graph is
+resolved: it rewrites the names Apex call sites and heritage clauses wrote to
+the spelling the repository declares. Declarations keep their own spelling.
+"""
+
+from __future__ import annotations
+
+import json
+from collections import defaultdict
+from collections.abc import Iterable
+from dataclasses import dataclass, replace
+from pathlib import Path, PurePosixPath
+from typing import Any
+
+from ..symbol_identity import outer_scope, symbol_id_path
+
+_SFDX_PROJECT = "sfdx-project.json"
+_TYPE_KINDS = frozenset({"class", "interface", "enum"})
+
+
+@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, 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]
+
+ 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.
+ """
+ project = self.project_of.get(file_path)
+ if project is None:
+ return None
+ 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
+
+ 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
+ )
+
+ 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()
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language != "apex":
+ 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
+ if symbol.parent_name is None:
+ top_level[(project, symbol.name.lower())].append(symbol.id)
+ else:
+ members.setdefault((outer_scope(symbol.id), symbol.name.lower()), symbol.id)
+ return ApexNamespaces(
+ project_of=project_of,
+ own_prefixes=prefixes,
+ package_dirs=package_dirs,
+ top_level={key: tuple(ids) for key, ids in top_level.items()},
+ members=members,
+ )
+
+
+class _ProjectFinder:
+ """The nearest ``sfdx-project.json`` above a file, each directory asked once."""
+
+ def __init__(self) -> None:
+ self._dirs: dict[str, str] = {}
+ self.prefixes: dict[str, frozenset[str]] = {}
+ self.package_dirs: dict[str, tuple[str, ...]] = {}
+
+ def project_of(self, path: str, abs_path: str) -> str:
+ rel = PurePosixPath(path)
+ root = Path(abs_path)
+ for _ in rel.parts:
+ root = root.parent
+ return self._project_of_dir(rel.parent.as_posix(), root)
+
+ def _project_of_dir(self, directory: str, root: Path) -> str:
+ directory = "" if directory == "." else directory
+ found = self._dirs.get(directory)
+ if found is not None:
+ return found
+ manifest = root / directory / _SFDX_PROJECT
+ if manifest.is_file():
+ found = directory
+ self.prefixes[found], self.package_dirs[found] = _read_manifest(manifest, directory)
+ elif directory:
+ found = self._project_of_dir(PurePosixPath(directory).parent.as_posix(), root)
+ else:
+ found = ""
+ self._dirs[directory] = found
+ return found
+
+
+def _read_manifest(manifest: Path, project: str) -> tuple[frozenset[str], tuple[str, ...]]:
+ """``(own namespace prefixes, package directories)`` an ``sfdx-project.json`` declares."""
+ 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)]
+ 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)
+
+
+def _package_dirs(written: list[Any], project: str) -> tuple[str, ...]:
+ """The written package directories, repo-relative.
+
+ Ceiling: one outside the project (``../shared``) is not read.
+ """
+ found = []
+ for path in written:
+ if not isinstance(path, str):
+ continue
+ path = PurePosixPath(path.replace("\\", "/")).as_posix().removeprefix("./").rstrip("/")
+ if path not in ("", ".") and not path.startswith(".."):
+ found.append(PurePosixPath(project, path).as_posix())
+ return tuple(found)
+
+
+def spell_apex_names(parsed_files: Iterable[Any]) -> None:
+ """Rewrite the names Apex call sites and heritage clauses wrote to their declared spelling.
+
+ A written name the repository declares as written is kept. Otherwise its
+ case-folded form must match exactly one declared spelling; a name declared
+ in two spellings (``getRecordTypeId`` and ``GetRecordTypeId``) is left as
+ written, a missed edge rather than a guessed one. A call's receiver is left
+ alone: it may be a variable that shares a class's folded name, which the
+ resolver tells apart. Idempotent, so a cached parse may pass through twice.
+
+ A receiver-less call means its own file's declaration of the name first
+ (of the same kind), however another class spells it: ``ContactFromDi(..)``
+ in a class declaring ``contactFromDi`` is that method. A call site does not
+ record ``new``, so a capitalised receiver-less name some type folds to is a
+ constructor (``new OrgConfig()`` inside a method ``orgConfig``), and any
+ other capitalised one matches only its own file's member (``new Contact()``,
+ the sObject, never becomes another class's method ``contact``). Ceilings: a
+ file declaring ``contact()`` reads its own ``new Contact()`` as that method,
+ and a constructor written in lower case (``new accountService()``) misses.
+ """
+ apex = [parsed for parsed in parsed_files if parsed.file_info.language == "apex"]
+ repo = _Spellings(symbol for parsed in apex for symbol in parsed.symbols)
+ for parsed in apex:
+ own = _Spellings(parsed.symbols)
+ for index, call in enumerate(parsed.calls):
+ target = repo.call_target(call, own)
+ if target != call.target_name:
+ parsed.calls[index] = replace(call, target_name=target)
+ for relation in parsed.heritage:
+ relation.parent_name = repo.spelled(relation.parent_name, repo.types)
+
+
+class _Spellings:
+ """``{folded name: declared spellings}`` for a set of Apex symbols, by kind."""
+
+ def __init__(self, symbols: Iterable[Any]) -> None:
+ self.names: dict[str, set[str]] = defaultdict(set)
+ self.types: dict[str, set[str]] = defaultdict(set)
+ self.members: dict[str, set[str]] = defaultdict(set)
+ for symbol in symbols:
+ self.names[symbol.name.lower()].add(symbol.name)
+ kind = self.types if symbol.kind in _TYPE_KINDS else self.members
+ kind[symbol.name.lower()].add(symbol.name)
+
+ def spelled(self, name: str, declared: dict[str, set[str]]) -> str:
+ """*name* as *declared* spells it, when that is one spelling and *name* is none."""
+ spellings = declared.get(name.lower())
+ if not spellings or name in self.names.get(name.lower(), ()) or len(spellings) > 1:
+ return name
+ return next(iter(spellings))
+
+ def call_target(self, call: Any, own: _Spellings) -> str:
+ """The spelling a call's target means; *own* is the caller file's."""
+ name = call.target_name
+ if call.receiver_name or call.receiver_call:
+ return self.spelled(name, self.names)
+ folded = name.lower()
+ if not name[:1].isupper():
+ table, mine = self.members, own.members
+ elif folded in self.types:
+ table, mine = self.types, own.types
+ else:
+ return own.spelled(name, own.members)
+ return own.spelled(name, mine) if folded in mine else self.spelled(name, table)
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 f6a599118..938efc005 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -347,8 +347,7 @@ _PY_FAMILY = (_PY_ANNOTATED, _PY_CONSTRUCTED, _PY_SELF_ANNOTATED, _PY_SELF_CONST
_TS_FAMILY = (_TS_ANNOTATED, _TS_PARAMETER_PROPERTY, _TS_CONSTRUCTED)
_LANGUAGE_PATTERNS: dict[str, tuple[re.Pattern[str], ...]] = {
- # Apex declares Java's way (``Foo foo``) and has no ``var``. Read for
- # overload choice now; no receiver strategy is registered for it yet.
+ # Apex declares Java's way (``Foo foo``) and has no ``var``.
"apex": (_TYPED_DECLARATION,),
"cpp": (_CPP_DECLARATION,),
"csharp": _C_FAMILY,
@@ -374,7 +373,7 @@ RECEIVER_TYPE_LANGUAGES = frozenset(_LANGUAGE_PATTERNS)
# writes ``self.foo.bar()``, a dotted receiver the grammar mints no call site
# for, so class scope could only bind a bare local to a field. Membership rests
# on the scan actually finding typed fields in the language's idiom.
-IMPLICIT_FIELD_LANGUAGES = frozenset({"csharp", "dart", "java", "kotlin", "swift"})
+IMPLICIT_FIELD_LANGUAGES = frozenset({"apex", "csharp", "dart", "java", "kotlin", "swift"})
# Languages whose scan keeps a declaration of a builtin type, marked external,
# so the resolver can refuse a call on it instead of matching the method name.
@@ -382,8 +381,9 @@ IMPLICIT_FIELD_LANGUAGES = frozenset({"csharp", "dart", "java", "kotlin", "swift
# extension methods, Kotlin and Swift extensions and Rust trait impls all can.
EXTERNAL_TYPE_LANGUAGES = frozenset({"java"})
# Those, and Kotlin, whose scan keeps the marked declaration without refusing:
-# a call on it may still reach a repo extension of the builtin.
-_MARKED_BUILTIN_LANGUAGES = EXTERNAL_TYPE_LANGUAGES | {"kotlin"}
+# a call on it may still reach a repo extension of the builtin. Apex keeps it so
+# a builtin-typed local still reads as a variable and types overload arguments.
+_MARKED_BUILTIN_LANGUAGES = EXTERNAL_TYPE_LANGUAGES | {"kotlin", "apex"}
_EXTERNAL_TYPE = "external:"
# A decorator that changes what the symbol it wraps *is*: `@shared_task` leaves
diff --git a/packages/core/src/repowise/core/ingestion/parser/calls.py b/packages/core/src/repowise/core/ingestion/parser/calls.py
index 5db03c564..cc0237651 100644
--- a/packages/core/src/repowise/core/ingestion/parser/calls.py
+++ b/packages/core/src/repowise/core/ingestion/parser/calls.py
@@ -371,7 +371,7 @@ def _call_from_match(
line=line,
argument_count=_count_arguments(arg_nodes[0]) if arg_nodes else None,
receiver_call=receiver_call,
- argument_types=_argument_literal_types(arguments, src),
+ argument_types=_argument_literal_types(arguments, src, language),
argument_names=_argument_names(arguments, src),
scope_name=_node_text(scope_nodes[0], src).strip() if scope_nodes else None,
edge_type=(
diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.py
index 1d2257589..bc029e3b1 100644
--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py
+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py
@@ -388,13 +388,21 @@ _JAVA_INTEGER_LITERALS = frozenset(
_JAVA_FLOATING_LITERALS = frozenset({"decimal_floating_point_literal", "hex_floating_point_literal"})
+# Apex literal nodes and the type each one has; ``null`` matches no exact type.
+_APEX_LITERAL_TYPES = {
+ "string_literal": "String",
+ "boolean": "Boolean",
+ "decimal_floating_point_literal": "Decimal",
+}
+
+
def _overload_arguments(language: str, arg_nodes: list[Node]) -> list[Node]:
- """A call's argument expressions, for a language whose overloads read them (Java).
+ """A call's argument expressions, for a language whose overloads read them (Java, Apex).
Read from the argument list already in hand, the way ``_count_arguments``
counts it.
"""
- if language != "java" or not arg_nodes:
+ if language not in ("java", "apex") or not arg_nodes:
return []
skip_types = frozenset({"(", ")", ","})
return [
@@ -402,12 +410,15 @@ def _overload_arguments(language: str, arg_nodes: list[Node]) -> list[Node]:
]
-def _argument_literal_types(arguments: list[Node], src: str) -> tuple[str | None, ...] | None:
+def _argument_literal_types(
+ arguments: list[Node], src: str, language: str = "java"
+) -> tuple[str | None, ...] | None:
"""The type of each literal argument, None where an argument is no literal.
None overall when no argument is a literal.
"""
- types = tuple(_java_literal_type(argument, src) for argument in arguments)
+ literal_type = _apex_literal_type if language == "apex" else _java_literal_type
+ types = tuple(literal_type(argument, src) for argument in arguments)
return types if any(types) else None
@@ -445,6 +456,12 @@ def _java_literal_type(node: Node, src: str) -> str | None:
return _JAVA_LITERAL_TYPES.get(node.type)
+def _apex_literal_type(node: Node, src: str) -> str | None:
+ if node.type == "int":
+ return "Long" if node_text(node, src).endswith(("l", "L")) else "Integer"
+ return _APEX_LITERAL_TYPES.get(node.type)
+
+
def _find_enclosing_symbol(
line: int,
symbol_ranges: list[tuple[int, int, str]],
diff --git a/packages/core/src/repowise/core/ingestion/queries/apex.scm b/packages/core/src/repowise/core/ingestion/queries/apex.scm
index b18d4da80..ae61c8e3b 100644
--- a/packages/core/src/repowise/core/ingestion/queries/apex.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/apex.scm
@@ -119,13 +119,14 @@
arguments: (argument_list) @call.arguments
) @call.site
-; new Foo().bar(args) / new Outer.Inner().bar(args)
+; new Foo().bar(args) / new Outer.Inner().bar(args): the whole type path is
+; the receiver, so the member type is read in the class that qualifies it.
(method_invocation
object: (object_creation_expression
type: [
- (type_identifier) @call.receiver
- (scoped_type_identifier (type_identifier) @call.receiver .)
- ]
+ (type_identifier)
+ (scoped_type_identifier)
+ ] @call.receiver
)
name: (identifier) @call.target
arguments: (argument_list) @call.arguments
@@ -144,10 +145,14 @@
arguments: (argument_list) @call.arguments
) @call.site
-; new Outer.Inner(args): the inner class is the target; its last segment is
-; the name it is declared under.
+; new Outer.Inner(args): the inner class is the target, declared under its
+; last segment, and the qualifier before it the receiver, so the member type
+; is looked up in the class the qualifier names (``ns.Outer`` included), never
+; by the bare name, which a same-named type in the caller's own file would take.
(object_creation_expression
type: (scoped_type_identifier
+ .
+ (_) @call.receiver
(type_identifier) @call.target .)
arguments: (argument_list) @call.arguments
) @call.site
diff --git a/packages/core/src/repowise/core/ingestion/type_names.py b/packages/core/src/repowise/core/ingestion/type_names.py
index 23f15b0cb..5b2dc5e8f 100644
--- a/packages/core/src/repowise/core/ingestion/type_names.py
+++ b/packages/core/src/repowise/core/ingestion/type_names.py
@@ -98,12 +98,12 @@ def written_type_key(name: str, raw: str, language: str) -> str:
"""*name*, the bare type *raw* spells, as receiver lookups key it.
A C# head keeps its arity (``IFoo`1``), since a same-file ``IFoo`` may be
- another type; a Java member type keeps its outer type (``Token.Tag``),
- which picks among same-named member types.
+ another type; a Java or Apex member type keeps its outer type
+ (``Token.Tag``), which picks among same-named member types.
"""
if language == "csharp" and (arity := type_argument_count(raw)):
return f"{name}`{arity}"
- if language == "java":
+ if language in ("java", "apex"):
return java_type_path(raw) or name
return name
diff --git a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
index 5c2607dae..3e133a0f0 100644
--- a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
+++ b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
@@ -51,6 +51,7 @@ import structlog
from .cohesion import OWN_TYPE_NAME_HINT, withdraw_declaration_hint
from .models import ParsedFile
+from .symbol_identity import symbol_id_path
if TYPE_CHECKING:
import networkx as nx
@@ -918,6 +919,58 @@ def _find_jvm_type_file(
return None
+# ---------------------------------------------------------------------------
+# Strategy: Apex
+# ---------------------------------------------------------------------------
+
+def _resolve_apex_type_refs(
+ parsed: ParsedFile,
+ ctx: ResolverContext,
+ graph: nx.DiGraph,
+ defined_names: dict[str, set[str]],
+) -> int:
+ """Resolve Apex type references to the type the caller's project declares.
+
+ Apex has no imports: a type name is a top-level class of the file's own
+ sfdx project, compared without case (see ``languages.apex_namespace``).
+ A name the file declares itself is its own, and draws no edge. The edges
+ do not widen call scope: Apex calls bind through the project namespace
+ in the call resolver, never through a file a type was read from.
+ """
+ if not parsed.type_refs or ctx.parsed_files is None:
+ return 0
+ index = _apex_namespaces(ctx)
+ from_path = parsed.file_info.path
+ # Names the file declares itself, then each name already linked.
+ skip = {s.name.lower() for s in parsed.symbols if s.kind in _TYPE_DECLARATION_KINDS}
+ emitted = 0
+ for ref in parsed.type_refs:
+ name = ref.type_name
+ if not name or name.lower() in skip:
+ continue
+ skip.add(name.lower())
+ type_id = index.top_level_type(from_path, name)
+ target = symbol_id_path(type_id) if type_id else from_path
+ if target == from_path or not graph.has_node(target):
+ continue
+ _add_or_merge_type_use_edge(
+ graph, src=from_path, dst=target, type_name=name, origin=ref.origin, widens_scope=False
+ )
+ emitted += 1
+ return emitted
+
+
+def _apex_namespaces(ctx: ResolverContext) -> Any:
+ """The ApexNamespaces index, built once per resolver context."""
+ index = getattr(ctx, "_apex_namespaces", None)
+ if index is None:
+ from .languages.apex_namespace import build_apex_namespaces
+
+ index = build_apex_namespaces(ctx.parsed_files)
+ ctx._apex_namespaces = index # type: ignore[attr-defined]
+ return index
+
+
# ---------------------------------------------------------------------------
# Strategy registry
# ---------------------------------------------------------------------------
@@ -939,6 +992,7 @@ _STRATEGIES: dict[str, Strategy] = {
"javascript": _resolve_ts_type_refs,
"java": _resolve_jvm_type_refs,
"kotlin": _resolve_jvm_type_refs,
+ "apex": _resolve_apex_type_refs,
}
diff --git a/tests/unit/ingestion/parser/golden/apex.json b/tests/unit/ingestion/parser/golden/apex.json
index 251ec7bb0..f6e60a9bb 100644
--- a/tests/unit/ingestion/parser/golden/apex.json
+++ b/tests/unit/ingestion/parser/golden/apex.json
@@ -348,7 +348,9 @@
"bare_name_fallback": false,
"spawned": false,
"argument_types": null,
- "argument_names": null
+ "argument_names": [
+ "name"
+ ]
},
{
"target_name": "log",
@@ -363,7 +365,9 @@
"bare_name_fallback": false,
"spawned": false,
"argument_types": null,
- "argument_names": null
+ "argument_names": [
+ "name"
+ ]
},
{
"target_name": "debug",
@@ -423,11 +427,13 @@
"bare_name_fallback": false,
"spawned": false,
"argument_types": null,
- "argument_names": null
+ "argument_names": [
+ "acc"
+ ]
},
{
"target_name": "Builder",
- "receiver_name": null,
+ "receiver_name": "Result",
"caller_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::execute",
"line": 30,
"argument_count": 0,
@@ -442,7 +448,7 @@
},
{
"target_name": "build",
- "receiver_name": "Builder",
+ "receiver_name": "Result.Builder",
"caller_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::execute",
"line": 30,
"argument_count": 0,
@@ -467,7 +473,9 @@
"supplied_props": null,
"bare_name_fallback": false,
"spawned": false,
- "argument_types": null,
+ "argument_types": [
+ "String"
+ ],
"argument_names": null
},
{
diff --git a/tests/unit/ingestion/parser/test_apex.py b/tests/unit/ingestion/parser/test_apex.py
index 43f6e1900..2d3eea165 100644
--- a/tests/unit/ingestion/parser/test_apex.py
+++ b/tests/unit/ingestion/parser/test_apex.py
@@ -161,7 +161,10 @@ class TestApexCalls:
(None, "AccountSelector"),
("selector", "byName"),
("AccountSelector", "log"),
- ("Builder", "build"),
+ # ``new Wrapper.Builder().build()``: the type path is the receiver,
+ # and the qualifier is the receiver of the inner class's construction.
+ ("Wrapper.Builder", "build"),
+ ("Wrapper", "Builder"),
("this", "helper"),
(None, "helper"),
("System", "debug"),
diff --git a/tests/unit/ingestion/test_apex_resolution.py b/tests/unit/ingestion/test_apex_resolution.py
new file mode 100644
index 000000000..86f16b2fe
--- /dev/null
+++ b/tests/unit/ingestion/test_apex_resolution.py
@@ -0,0 +1,310 @@
+"""Apex call, heritage and type resolution: the project namespace and case folding."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+
+_CLASSES = "force-app/main/default/classes"
+
+
+def _build(repo: Path):
+ traverser = FileTraverser(repo)
+ parser = ASTParser()
+ builder = GraphBuilder(repo_path=repo)
+ for fi in traverser.traverse():
+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))
+ return builder.build()
+
+
+def _project(root: Path, files: dict[str, str], namespace: str = "") -> None:
+ root.mkdir(parents=True, exist_ok=True)
+ manifest = {"packageDirectories": [{"path": "force-app", "default": True}], "namespace": namespace}
+ (root / "sfdx-project.json").write_text(json.dumps(manifest))
+ for name, body in files.items():
+ path = root / (name if "/" in name else f"{_CLASSES}/{name}")
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(body)
+
+
+def _calls(graph, caller: str) -> dict[str, str]:
+ """``{callee id: resolution origin}`` for every call edge out of *caller*."""
+ return {
+ callee: data.get("resolution_origin")
+ for _, callee, data in graph.out_edges(caller, data=True)
+ if data.get("edge_type") == "calls"
+ }
+
+
+def _id(name: str, symbol: str, project: str = "") -> str:
+ prefix = f"{project}/" if project else ""
+ return f"{prefix}{_CLASSES}/{name}::{symbol}"
+
+
+_SERVICE = """public class AccountService {
+ public AccountService() {}
+ public AccountService(Integer size) {}
+ public static void run() {}
+ public void save() {}
+ public class Result {
+ public Boolean ok() { return true; }
+ }
+}
+"""
+
+
+def test_new_binds_the_constructor_of_a_project_class(tmp_path: Path) -> None:
+ # The class and its constructors share a name, which the global tier refuses.
+ _project(tmp_path, {
+ "AccountService.cls": _SERVICE,
+ "Caller.cls": "public class Caller {\n void go() { new AccountService(5); }\n}\n",
+ })
+ calls = _calls(_build(tmp_path), _id("Caller.cls", "Caller::go"))
+ assert calls == {_id("AccountService.cls", "AccountService::AccountService#1"): "same_package"}
+
+
+def test_names_resolve_in_any_case(tmp_path: Path) -> None:
+ _project(tmp_path, {
+ "AccountService.cls": _SERVICE,
+ "Caller.cls": (
+ "public class Caller {\n"
+ " void go() {\n"
+ " ACCOUNTSERVICE.Run();\n"
+ " accountservice svc = new accountService();\n"
+ " }\n"
+ "}\n"
+ ),
+ })
+ calls = _calls(_build(tmp_path), _id("Caller.cls", "Caller::go"))
+ assert calls[_id("AccountService.cls", "AccountService::run")] == "receiver_same_package"
+
+
+def test_static_inner_and_typed_receivers(tmp_path: Path) -> None:
+ _project(tmp_path, {
+ "AccountService.cls": _SERVICE,
+ "Caller.cls": (
+ "public class Caller {\n"
+ " private AccountService held;\n"
+ " void go() {\n"
+ " AccountService.run();\n"
+ " AccountService.Result r = new AccountService.Result();\n"
+ " r.ok();\n"
+ " held.save();\n"
+ " }\n"
+ "}\n"
+ ),
+ })
+ calls = _calls(_build(tmp_path), _id("Caller.cls", "Caller::go"))
+ assert calls == {
+ _id("AccountService.cls", "AccountService::run"): "receiver_same_package",
+ _id("AccountService.cls", "AccountService::Result"): "receiver_same_package",
+ _id("AccountService.cls", "Result::ok"): "receiver_typed_same_package",
+ _id("AccountService.cls", "AccountService::save"): "receiver_field_same_package",
+ }
+
+
+def test_inner_class_wins_inside_its_outer(tmp_path: Path) -> None:
+ _project(tmp_path, {
+ "Result.cls": "public class Result {\n public void ok() {}\n}\n",
+ "AccountService.cls": (
+ "public class AccountService {\n"
+ " void go() { new Result(); }\n"
+ " public class Result {}\n"
+ "}\n"
+ ),
+ })
+ calls = _calls(_build(tmp_path), _id("AccountService.cls", "AccountService::go"))
+ assert set(calls) == {_id("AccountService.cls", "AccountService::Result")}
+
+
+def test_a_local_variable_is_not_the_class_its_name_folds_to(tmp_path: Path) -> None:
+ _project(tmp_path, {
+ "Logger.cls": "public class Logger {\n public static void info() {}\n}\n",
+ "Caller.cls": (
+ "public class Caller {\n"
+ " void go(String logger) {\n"
+ " logger.info();\n"
+ " }\n"
+ "}\n"
+ ),
+ })
+ assert _calls(_build(tmp_path), _id("Caller.cls", "Caller::go")) == {}
+
+
+def test_platform_and_other_namespace_prefixes_name_no_repo_class(tmp_path: Path) -> None:
+ _project(tmp_path, {
+ "Test.cls": "public class Test {\n public static void startTest() {}\n}\n",
+ "Caller.cls": (
+ "public class Caller {\n"
+ " void go() {\n"
+ " System.Test.startTest();\n"
+ " other.Test.startTest();\n"
+ " npsp.Test.startTest();\n"
+ " }\n"
+ "}\n"
+ ),
+ }, namespace="npsp")
+ # Only the project's own prefix reaches the repo class.
+ calls = _calls(_build(tmp_path), _id("Caller.cls", "Caller::go"))
+ assert calls == {_id("Test.cls", "Test::startTest"): "receiver_same_package"}
+
+
+def test_each_project_resolves_its_own_copy(tmp_path: Path) -> None:
+ caller = "public class Caller {\n void go() { Util.help(); }\n}\n"
+ util = "public class Util {\n public static void help() {}\n}\n"
+ for project in ("one", "two"):
+ _project(tmp_path / project, {"Util.cls": util, "Caller.cls": caller})
+ graph = _build(tmp_path)
+ for project in ("one", "two"):
+ calls = _calls(graph, _id("Caller.cls", "Caller::go", project))
+ assert calls == {_id("Util.cls", "Util::help", project): "receiver_same_package"}
+
+
+def test_a_legacy_copy_outside_the_package_directories(tmp_path: Path) -> None:
+ util = "public class Util {\n public static void help() {}\n}\n"
+ _project(tmp_path, {
+ "Util.cls": util,
+ "Caller.cls": "public class Caller {\n void go() { Util.help(); }\n}\n",
+ "mdapi/classes/Util.cls": util,
+ "mdapi/classes/Other.cls": "public class Other {\n void go() { Util.help(); }\n}\n",
+ })
+ graph = _build(tmp_path)
+ assert _calls(graph, _id("Caller.cls", "Caller::go")) == {
+ _id("Util.cls", "Util::help"): "receiver_same_package"
+ }
+ assert _calls(graph, "mdapi/classes/Other.cls::Other::go") == {
+ "mdapi/classes/Util.cls::Util::help": "receiver_same_package"
+ }
+
+
+def test_inherited_methods(tmp_path: Path) -> None:
+ _project(tmp_path, {
+ "Base.cls": (
+ "public virtual class Base {\n"
+ " protected void helper() {}\n"
+ " public virtual void run() {}\n"
+ "}\n"
+ ),
+ "Child.cls": (
+ "public class Child extends BASE {\n"
+ " public override void run() {\n"
+ " helper();\n"
+ " this.helper();\n"
+ " super.run();\n"
+ " }\n"
+ "}\n"
+ ),
+ })
+ graph = _build(tmp_path)
+ assert graph.has_edge(_id("Child.cls", "Child"), _id("Base.cls", "Base"))
+ calls = _calls(graph, _id("Child.cls", "Child::run"))
+ assert calls == {
+ _id("Base.cls", "Base::helper"): "enclosing_inherited",
+ _id("Base.cls", "Base::run"): "self_inherited",
+ }
+
+
+def test_a_bare_call_never_reaches_another_class_method(tmp_path: Path) -> None:
+ _project(tmp_path, {
+ "Other.cls": "public class Other {\n public void unique() {}\n}\n",
+ "Caller.cls": "public class Caller {\n void go() { unique(); }\n}\n",
+ })
+ assert _calls(_build(tmp_path), _id("Caller.cls", "Caller::go")) == {}
+
+
+def test_a_bare_call_means_its_own_class_however_another_spells_it(tmp_path: Path) -> None:
+ _project(tmp_path, {
+ "Other.cls": "public class Other {\n public void ContactFromDi() {}\n}\n",
+ "Caller.cls": (
+ "public class Caller {\n"
+ " void go() { ContactFromDi(); }\n"
+ " void contactFromDi() {}\n"
+ "}\n"
+ ),
+ })
+ calls = _calls(_build(tmp_path), _id("Caller.cls", "Caller::go"))
+ assert set(calls) == {_id("Caller.cls", "Caller::contactFromDi")}
+
+
+def test_a_capitalised_bare_call_is_a_constructor_not_a_method(tmp_path: Path) -> None:
+ # ``new Contact()`` is the sObject, not the repo method ``contact``.
+ _project(tmp_path, {
+ "Model.cls": "public class Model {\n public void contact() {}\n}\n",
+ "Caller.cls": "public class Caller {\n void go() { new Contact(); }\n}\n",
+ })
+ assert _calls(_build(tmp_path), _id("Caller.cls", "Caller::go")) == {}
+
+
+def test_an_overload_is_chosen_by_an_exact_argument_type(tmp_path: Path) -> None:
+ _project(tmp_path, {
+ "Log.cls": (
+ "public class Log {\n"
+ " public static void add(String message) {}\n"
+ " public static void add(Exception error) {}\n"
+ "}\n"
+ ),
+ "Caller.cls": (
+ "public class Caller {\n"
+ " void go(Exception e) { Log.add(e); }\n"
+ "}\n"
+ ),
+ })
+ calls = _calls(_build(tmp_path), _id("Caller.cls", "Caller::go"))
+ assert set(calls) == {_id("Log.cls", "Log::add#1(Exception)")}
+
+
+def test_a_chained_call_is_typed_by_the_inner_return_type(tmp_path: Path) -> None:
+ _project(tmp_path, {
+ "Query.cls": (
+ "public class Query {\n"
+ " public static Query make() { return new Query(); }\n"
+ " public Query field(String name) { return this; }\n"
+ "}\n"
+ ),
+ "Caller.cls": "public class Caller {\n void go() { Query.make().field('Id'); }\n}\n",
+ })
+ calls = _calls(_build(tmp_path), _id("Caller.cls", "Caller::go"))
+ assert calls[_id("Query.cls", "Query::field")] == "return_type_same_package"
+
+
+def test_type_references_draw_file_edges(tmp_path: Path) -> None:
+ _project(tmp_path, {
+ "Shape.cls": "public interface Shape {}\n",
+ "Caller.cls": "public class Caller {\n void go(SHAPE s) {}\n}\n",
+ })
+ graph = _build(tmp_path)
+ data = graph.get_edge_data(f"{_CLASSES}/Caller.cls", f"{_CLASSES}/Shape.cls")
+ assert data is not None and data["edge_type"] == "type_use"
+
+
+def test_a_lower_case_bare_call_is_not_a_constructor(tmp_path: Path) -> None:
+ # ``execute()`` inherited from a platform class is not ``new Execute()``.
+ _project(tmp_path, {
+ "Execute.cls": "public class Execute {}\n",
+ "Other.cls": "public class Other {\n public void execute() {}\n}\n",
+ "Job.cls": "public class Job implements Queueable {\n void go() { execute(); }\n}\n",
+ })
+ assert _calls(_build(tmp_path), _id("Job.cls", "Job::go")) == {}
+
+
+def test_a_malformed_manifest_still_resolves(tmp_path: Path) -> None:
+ _project(tmp_path, {
+ "AccountService.cls": _SERVICE,
+ "Caller.cls": "public class Caller {\n void go() { AccountService.run(); }\n}\n",
+ })
+ (tmp_path / "sfdx-project.json").write_text('{"packageDirectories": 5, "namespace": 7}')
+ calls = _calls(_build(tmp_path), _id("Caller.cls", "Caller::go"))
+ assert calls == {_id("AccountService.cls", "AccountService::run"): "receiver_same_package"}
+
+
+def test_a_property_is_never_the_callee(tmp_path: Path) -> None:
+ # The child's property ``status`` hides nothing: the call is the base's method.
+ _project(tmp_path, {
+ "Base.cls": "public virtual class Base {\n public static String status() { return ''; }\n}\n",
+ "Child.cls": "public class Child extends Base {\n public String status { get; set; }\n}\n",
+ "Caller.cls": "public class Caller {\n void go() { Child.status(); }\n}\n",
+ })
+ calls = _calls(_build(tmp_path), _id("Caller.cls", "Caller::go"))
+ assert calls == {_id("Base.cls", "Base::status"): "receiver_same_package"}
diff --git a/tests/unit/ingestion/test_return_type_chain_resolution.py b/tests/unit/ingestion/test_return_type_chain_resolution.py
index 5b393f329..4aca1a07b 100644
--- a/tests/unit/ingestion/test_return_type_chain_resolution.py
+++ b/tests/unit/ingestion/test_return_type_chain_resolution.py
@@ -216,7 +216,7 @@ def test_unbound_global_return_type_preserves_legacy_fallback(
def test_only_audited_lanes_are_enabled_by_default() -> None:
assert (
- frozenset({"cpp", "csharp", "dart", "go", "java", "kotlin", "python"})
+ frozenset({"apex", "cpp", "csharp", "dart", "go", "java", "kotlin", "python"})
== PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES
)