Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(apex): parse Apex classes, triggers and anonymous scripts (#4404)
Raghav Chamadiyaf77374efdcdc
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.mdindex 120984335..6debf88c4 100644--- a/docs/architecture/language-support.md+++ b/docs/architecture/language-support.md@@ -944,6 +944,17 @@ XML literals, tuple literals used as expressions, a nested double quote inside ainterpolation hole, an omitted argument in a call that also carries typearguments, and some multi-line LINQ layouts, each recovered from locally.+### Apex++The grammar is the language pack's `apex`, loaded as COBOL's is. It keeps+Java's node and field names, so `apex.scm`, heritage and type heads follow Java;+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.+### QMLModule specs resolve against an index built from the `qmldir` manifests in thediff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex 3d147640d..8492f2f4f 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -74,6 +74,9 @@ Scala, Elixir and F# have dedicated import resolvers with known gaps; see\* COBOL is excluded from dead-code claims: JCL, schedulers and dynamic programcalls 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.## How accurate is the graph per languagediff --git a/packages/core/src/repowise/core/analysis/dead_code/passes/unused_internals.py b/packages/core/src/repowise/core/analysis/dead_code/passes/unused_internals.pyindex 415ef58eb..71dc2492b 100644--- a/packages/core/src/repowise/core/analysis/dead_code/passes/unused_internals.py+++ b/packages/core/src/repowise/core/analysis/dead_code/passes/unused_internals.py@@ -4,7 +4,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING-from ..constants import _is_fixture_path+from ..constants import _DEAD_CODE_EXEMPT_LANGUAGES, _is_fixture_pathfrom ..contract_methods import is_contract_methodfrom ..decorator_rules import _declared_deliberately_unused, _is_framework_registeredfrom ..finding_helpers import _symbol_span@@ -15,6 +15,12 @@ from ..symbol_rules import _ENTRY_POINT_SYMBOL_NAMES, _UNCALLABLE_TYPE_KINDS, _nif TYPE_CHECKING:from ..analyzer import DeadCodeAnalyzer+# Rust: the compiler's ``dead_code`` lint already reports these, with macro+# expansion and types a static graph cannot match. The exempt languages+# (COBOL, Apex) are entered by a runtime the graph cannot see, as in the file+# and export passes.+_UNJUDGED_LANGUAGES = _DEAD_CODE_EXEMPT_LANGUAGES | {"rust"}+class UnusedInternalPass:"""Judges every private symbol node of the graph."""@@ -84,9 +90,7 @@ class UnusedInternalPass:"""Whether a graph node is a private symbol the unused-internal pass may judge."""if node_data.get("node_type") != "symbol":return False- # Rust: the compiler's ``dead_code`` lint already reports these, with- # macro expansion and types a static graph cannot match.- if node_data.get("language") == "rust":+ if node_data.get("language") in _UNJUDGED_LANGUAGES:return False# ``internal`` is assembly-, module- or crate-wide, so a missing call# edge is no evidence; no pass judges it, which drops an unmodifieddiff --git a/packages/core/src/repowise/core/generation/onboarding/grounding.py b/packages/core/src/repowise/core/generation/onboarding/grounding.pyindex 9758ee70e..2d23b88e6 100644--- a/packages/core/src/repowise/core/generation/onboarding/grounding.py+++ b/packages/core/src/repowise/core/generation/onboarding/grounding.py@@ -80,6 +80,9 @@ _CODE_EXTENSIONS = frozenset("astro","m","mm",+ "cls",+ "trigger",+ "apex",})_DOCUMENT_EXTENSIONS = frozenset(diff --git a/packages/core/src/repowise/core/ingestion/call_language_strategies.py b/packages/core/src/repowise/core/ingestion/call_language_strategies.pyindex 10894ec0c..91c5c9e55 100644--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py@@ -142,6 +142,11 @@ _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),}diff --git a/packages/core/src/repowise/core/ingestion/extractors/docstrings.py b/packages/core/src/repowise/core/ingestion/extractors/docstrings.pyindex 197d96e97..0ca02e132 100644--- a/packages/core/src/repowise/core/ingestion/extractors/docstrings.py+++ b/packages/core/src/repowise/core/ingestion/extractors/docstrings.py@@ -488,6 +488,7 @@ _SYMBOL_DOC: dict[str, Callable[[Node, str], str | None]] = {"fsharp": _fsharp_symbol_doc,"rust": _rust_symbol_doc,"java": _javadoc,+ "apex": _javadoc, # ApexDoc**dict.fromkeys(_C_LIKE, _block_or_line_doc),"kotlin": _javadoc,"elixir": _elixir_symbol_doc,diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.pyindex 51c309876..122af6be7 100644--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py@@ -21,6 +21,7 @@ from collections.abc import Callablefrom ...languages.registry import REGISTRY as _LANG_REGISTRYfrom ...models import HeritageRelationfrom ..helpers import node_text+from .apex import _extract_apex_heritagefrom .cpp import _extract_cpp_heritagefrom .csharp import _extract_csharp_heritagefrom .dart import _extract_dart_heritage@@ -55,6 +56,7 @@ HERITAGE_EXTRACTORS: dict[str, Callable[..., None]] = {"vue": _extract_ts_js_heritage,"astro": _extract_ts_js_heritage,"java": _extract_java_heritage,+ "apex": _extract_apex_heritage,"go": _extract_go_heritage,"rust": _extract_rust_heritage,"cpp": _extract_cpp_heritage,diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/apex.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/apex.pynew file mode 100644index 000000000..fdad4ffed--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/apex.py@@ -0,0 +1,26 @@+"""Apex heritage extraction."""++from __future__ import annotations++from tree_sitter import Node++from ...models import HeritageRelation+from ...type_names import bare_type_name+from ..helpers import node_text+from .java import _interfaces+++def _extract_apex_heritage(+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]+) -> None:+ """``class Foo extends Bar implements IFoo`` / ``interface IFoo extends IBar``.++ Java's shape, except that the superclass is read from its type node: Apex+ keywords are case-insensitive, so the clause's text may open ``EXTENDS``.+ """+ superclass = def_node.child_by_field_name("superclass")+ if superclass is not None and superclass.named_children:+ parent = bare_type_name(node_text(superclass.named_children[-1], src))+ if parent:+ out.append(HeritageRelation(child_name=name, parent_name=parent, kind="extends", line=line))+ _interfaces(def_node, name, line, src, out)diff --git a/packages/core/src/repowise/core/ingestion/extractors/signatures.py b/packages/core/src/repowise/core/ingestion/extractors/signatures.pyindex b6d432937..c62ad22cc 100644--- a/packages/core/src/repowise/core/ingestion/extractors/signatures.py+++ b/packages/core/src/repowise/core/ingestion/extractors/signatures.py@@ -74,6 +74,14 @@ def build_signature(node_type: str, name: str, params_text: str, def_node: Node,return f"typealias {name} = {node_text(target, src)}"if node_type == "enum_declaration":return f"enum {name}"+ if node_type == "trigger_declaration":+ # Apex: the sObject and the DML events are the trigger's whole contract.+ sobject = def_node.child_by_field_name("object")+ events = ", ".join(+ node_text(e, src) for e in def_node.children_by_field_name("events") if e.is_named+ )+ on = f" on {node_text(sobject, src)}" if sobject is not None else ""+ return f"trigger {name}{on} ({events})"if node_type in ("method_definition", "method_signature"):# TypeScript/JavaScript class methodreturn f"{name}{params_text}{_ret(('return_type',))}"diff --git a/packages/core/src/repowise/core/ingestion/extractors/visibility.py b/packages/core/src/repowise/core/ingestion/extractors/visibility.pyindex 8cbfd8f3b..0371945c8 100644--- a/packages/core/src/repowise/core/ingestion/extractors/visibility.py+++ b/packages/core/src/repowise/core/ingestion/extractors/visibility.py@@ -207,6 +207,57 @@ def public_by_default(_name: str, _mods: list[str]) -> str:return "public"+def apex_visibility(_name: str, _mods: list[str]) -> str:+ """Apex's default access, private; ``refine_apex_visibility`` reads the keyword.++ The modifier text is not searched: it carries the annotations, and+ ``@SuppressWarnings('PMD.AvoidGlobalModifier')`` would read as ``global``.+ """+ return "private"+++# ``global`` (managed-package API) and ``webservice`` (SOAP, global only) are+# wider than ``public``; the vocabulary has nothing wider, so they record as it.+_APEX_ACCESS = (+ ("global", "public"),+ ("webservice", "public"),+ ("public", "public"),+ ("protected", "protected"),+ ("private", "private"),+)+++def _apex_modifier_keywords(def_node: Node) -> set[str]:+ """The keyword node types under a declaration's ``modifiers``, any case."""+ modifiers = next((c for c in def_node.children if c.type == "modifiers"), None)+ if modifiers is None:+ return set()+ return {+ keyword.type+ for modifier in modifiers.children+ if modifier.type == "modifier"+ for keyword in modifier.children+ }+++def refine_apex_visibility(def_node: Node) -> str:+ """The access keyword an Apex declaration writes, else its scope's default.++ Keywords are ``modifier`` children of ``modifiers``, typed by the keyword+ whatever case it is written in. With none, an interface member is public+ and anything else is private. A trigger is public.+ """+ if def_node.type == "trigger_declaration":+ # Run by the platform on DML from any context; it takes no modifier.+ return "public"+ written = _apex_modifier_keywords(def_node)+ for keyword, visibility in _APEX_ACCESS:+ if keyword in written:+ return visibility+ parent = def_node.parent+ return "public" if parent is not None and parent.type == "interface_body" else "private"++# Elixir spells privacy in the definition keyword rather than in a modifier:# `defp` / `defmacrop` / `defguardp` are module-private, their unsuffixed# forms are public. elixir.scm captures the keyword as @symbol.modifiers.diff --git a/packages/core/src/repowise/core/ingestion/lang_helpers/source_prep.py b/packages/core/src/repowise/core/ingestion/lang_helpers/source_prep.pyindex 578e50cba..057d27c03 100644--- a/packages/core/src/repowise/core/ingestion/lang_helpers/source_prep.py+++ b/packages/core/src/repowise/core/ingestion/lang_helpers/source_prep.py@@ -1,4 +1,4 @@-"""Byte-preserving source sanitizers for grammar gaps in Pascal and Objective-C."""+"""Byte-preserving source sanitizers for grammar gaps in Pascal, Objective-C and Apex."""from __future__ import annotations@@ -117,3 +117,14 @@ def prepare_objectivec_source(source: bytes) -> bytes:passes blank in place, so every offset outside a match is unchanged."""return _blank_objc_trailing_macros(_blank_matches(source, _OBJC_BARE_MACRO_LINE_RE))+++# CumulusCI namespace-injection tokens (``%%%NAMESPACE%%%``,+# ``%%%NAMESPACE_DOT%%%``) that the build rewrites before deploy. The source+# is not Apex until then, and the grammar errors on them.+_APEX_NAMESPACE_TOKEN_RE = re.compile(rb"%%%[A-Z_]+%%%")+++def prepare_apex_source(source: bytes) -> bytes:+ """Blank CumulusCI namespace tokens in place, preserving offsets."""+ return _blank_matches(source, _APEX_NAMESPACE_TOKEN_RE)diff --git a/packages/core/src/repowise/core/ingestion/lang_helpers/type_heads.py b/packages/core/src/repowise/core/ingestion/lang_helpers/type_heads.pyindex 7616a467b..03f0ae765 100644--- a/packages/core/src/repowise/core/ingestion/lang_helpers/type_heads.py+++ b/packages/core/src/repowise/core/ingestion/lang_helpers/type_heads.py@@ -3,6 +3,7 @@from __future__ import annotationsfrom collections.abc import Callable+from functools import cachefrom tree_sitter import Node@@ -427,6 +428,28 @@ def _java_head_step(node: Node, src: str) -> str | Node | None:return _first_named_child(node)+# ---------------------------------------------------------------------------+# Apex type-reference head extraction+# ---------------------------------------------------------------------------+++@cache+def _apex_builtin_types_folded() -> frozenset[str]:+ return frozenset(name.lower() for name in get_builtin_types("apex"))+++def _apex_head_type_identifier(type_node: Node, src: str) -> str | None:+ """The head of an Apex type, read with Java's walker.++ Apex type names are case-insensitive (``string``, ``LIST<Account>``), so+ the builtin filter compares them folded. The name keeps its written case.+ """+ head = _walk_to_head(type_node, src, _java_head_step, 8)+ if head is None or head.lower() in _apex_builtin_types_folded():+ return None+ return _resolvable(head, "apex")++# ---------------------------------------------------------------------------# Kotlin type-reference head extraction# ---------------------------------------------------------------------------@@ -684,6 +707,7 @@ TYPE_HEAD_EXTRACTORS: dict[str, Callable[[Node, str], str | None]] = {"typescript": _ts_head_type_identifier,"javascript": _ts_head_type_identifier,"java": _java_head_type_identifier,+ "apex": _apex_head_type_identifier,"kotlin": _kotlin_head_type_identifier,"rust": _rust_head_type_identifier,"pascal": _pascal_head_type_identifier,diff --git a/packages/core/src/repowise/core/ingestion/language_configs.py b/packages/core/src/repowise/core/ingestion/language_configs.pyindex 8e26e44c0..b411bc2dc 100644--- a/packages/core/src/repowise/core/ingestion/language_configs.py+++ b/packages/core/src/repowise/core/ingestion/language_configs.py@@ -34,6 +34,7 @@ from .extractors.imports import (ImportExtractor,)from .extractors.visibility import (+ apex_visibility,csharp_visibility,dart_visibility,elixir_visibility,@@ -401,6 +402,27 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {}),),+ # Apex reads Java's node names; there are no imports to extract.+ "apex": LanguageConfig(+ symbol_node_types={+ "class_declaration": "class",+ "interface_declaration": "interface",+ "enum_declaration": "enum",+ # A trigger is one body the platform runs on DML events.+ "trigger_declaration": "function",+ "method_declaration": "method",+ "constructor_declaration": "function",+ # Only a field with an accessor list is captured (a property).+ "field_declaration": "variable",+ },+ import_node_types=[],+ export_node_types=[],+ visibility_fn=apex_visibility,+ parent_extraction="nesting",+ parent_class_types=frozenset(+ {"class_declaration", "interface_declaration", "enum_declaration"}+ ),+ ),"swift": LanguageConfig(import_extractor=SWIFT_IMPORTS,symbol_node_types={diff --git a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.pyindex 738f13782..f6a599118 100644--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py@@ -347,6 +347,9 @@ _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": (_TYPED_DECLARATION,),"cpp": (_CPP_DECLARATION,),"csharp": _C_FAMILY,"dart": _DART_FAMILY,@@ -868,6 +871,7 @@ _LANGUAGE_BLOCK_COMMENTS: dict[str, re.Pattern[str]] = {}_LANGUAGE_COMMENTS: dict[str, re.Pattern[str]] = {+ "apex": _LINE_COMMENT,"cpp": _LINE_COMMENT,"csharp": _LINE_COMMENT,"dart": _LINE_COMMENT,diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.pyindex b725bcad1..856c280be 100644--- a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py+++ b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py@@ -11,6 +11,7 @@ extension-to-language map is built first-spec-wins, so order is significantfrom __future__ import annotationsfrom ..spec import LanguageSpec+from .apex import SPEC as _APEXfrom .asciidoc import SPEC as _ASCIIDOCfrom .astro import SPEC as _ASTROfrom .c import SPEC as _C@@ -110,6 +111,7 @@ ALL_SPECS: tuple[LanguageSpec, ...] = (_COBOL,_GDSCRIPT,_VBNET,+ _APEX,# -----------------------------------------------------------------# Config / data / markup languages (passthrough — no AST)# -----------------------------------------------------------------diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/apex.py b/packages/core/src/repowise/core/ingestion/languages/specs/apex.pynew file mode 100644index 000000000..ba91a6e1a--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/languages/specs/apex.py@@ -0,0 +1,99 @@+"""LanguageSpec for Salesforce Apex classes, triggers and anonymous scripts."""++from ..spec import LanguageSpec++SPEC = LanguageSpec(+ tag="apex",+ display_name="Apex",+ # .apex is an anonymous-Apex script: top-level statements, no class.+ extensions=frozenset({".cls", ".trigger", ".apex"}),+ # The language pack ships the aheber/tree-sitter-sfapex Apex grammar+ # (inline SOQL/SOSL and DML are structured nodes in it), loaded the same+ # way as COBOL.+ grammar_package="tree_sitter_language_pack",+ grammar_loader="get_language",+ grammar_loader_args=("apex",),+ scm_file="apex.scm",+ heritage_node_types=frozenset(+ {"class_declaration", "interface_declaration", "enum_declaration"}+ ),+ # Apex has no import statement: every top-level class in a package+ # directory is visible by name, so there is nothing for a resolver to read.+ import_support="none",+ # Triggers, @AuraEnabled/@InvocableMethod/@RestResource members, platform+ # interfaces (Queueable, Batchable, ...) and global API are entered by the+ # org runtime, Lightning, Flows and managed-package subscribers, none of+ # which the static graph sees yet. Unused/unreachable claims stay off+ # until those entry points are modelled.+ dead_code_exempt=True,+ # FooTest / FooTests. Foo_Test, Foo_TEST and Test_Foo already match the+ # generic stem rules, which compare lowercased.+ test_camel_suffixes=("Test", "Tests"),+ manifest_files=("sfdx-project.json",),+ blocked_dirs=(".sfdx", ".sf"),+ # Platform types written as a constructor target (``new Map<..>`` and+ # ``new List<..>`` are generic and never captured as one). Matched as+ # written; the parser drops the call site.+ builtin_calls=frozenset(+ {+ "System", "Database", "Schema", "Test", "Limits", "Math", "JSON",+ "UserInfo", "String", "Integer", "Long", "Decimal", "Double",+ "Boolean", "Date", "Datetime", "Time", "Blob", "Id", "Object",+ "Exception", "DmlException", "QueryException", "AuraHandledException",+ "IllegalArgumentException", "NullPointerException", "ListException",+ "StringException", "TypeException", "CalloutException",+ "SObjectException", "SecurityException", "JSONException",+ "Http", "HttpRequest", "HttpResponse", "PageReference", "Pattern",+ "SelectOption", "Url", "Version", "Savepoint",+ }+ ),+ # Only the root exception type. Platform interfaces (Queueable, Batchable,+ # Schedulable, Comparable, ...) stay in the heritage list on purpose: they+ # are what marks a class's contract methods as runtime-invoked.+ builtin_parents=frozenset({"Exception"}),+ # Primitives, collections and the System, Database and Schema types that+ # never resolve to a class the repository declares. Apex type names are+ # case-insensitive, so readers compare these folded (see type_heads).+ # Standard sObjects (Account, Contact, ...) are absent: they are schema+ # references, not platform classes.+ builtin_types=frozenset(+ {+ # Primitives and the root types+ "Blob", "Boolean", "Date", "Datetime", "Decimal", "Double", "Id",+ "Integer", "Long", "Object", "String", "Time", "SObject",+ # Collections+ "List", "Map", "Set", "Iterator", "Iterable",+ # System namespace+ "System", "Database", "Schema", "Test", "Limits", "Math", "JSON",+ "JSONParser", "JSONGenerator", "JSONToken", "UserInfo", "Type",+ "Http", "HttpRequest", "HttpResponse", "HttpCalloutMock",+ "WebServiceMock", "StubProvider", "PageReference", "ApexPages",+ "SelectOption", "LoggingLevel", "Pattern", "Matcher", "Url",+ "Crypto", "EncodingUtil", "Messaging", "Trigger", "TriggerOperation",+ "Savepoint", "Approval", "Search", "Label", "Site", "Network",+ "EventBus", "RestContext", "RestRequest", "RestResponse", "Version",+ "Address", "Location", "Continuation", "Callable", "Comparable",+ "Queueable", "QueueableContext", "Schedulable", "SchedulableContext",+ "Finalizer", "FinalizerContext",+ # Database namespace+ "SaveResult", "UpsertResult", "DeleteResult", "UndeleteResult",+ "MergeResult", "QueryLocator", "QueryLocatorIterator", "Batchable",+ "BatchableContext", "Stateful", "AllowsCallouts", "DMLOptions",+ "LeadConvert", "LeadConvertResult",+ # Schema namespace+ "SObjectType", "SObjectField", "DescribeSObjectResult",+ "DescribeFieldResult", "PicklistEntry", "DisplayType", "FieldSet",+ "FieldSetMember", "ChildRelationship", "RecordTypeInfo",+ # Exceptions+ "Exception", "DmlException", "QueryException", "AuraHandledException",+ "IllegalArgumentException", "NullPointerException", "ListException",+ "StringException", "TypeException", "CalloutException",+ "SObjectException", "SecurityException", "JSONException",+ "LimitException", "MathException", "NoAccessException",+ "HandledException", "AsyncException", "EmailException",+ "NoDataFoundException", "SerializationException",+ "VisualforceException", "XmlException",+ }+ ),+ color_hex="#1797C0",+)diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex e89a97761..c8407ff28 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -45,6 +45,7 @@ LanguageTag = Literal["cobol","gdscript","vbnet",+ "apex",# Passthrough code languages (no AST parser yet — empty ParsedFile,# files enter the graph via the generic resolver). Before these tags# existed the traverser silently skipped such files as unknown, so e.g.diff --git a/packages/core/src/repowise/core/ingestion/parser/calls.py b/packages/core/src/repowise/core/ingestion/parser/calls.pyindex 7102d9158..5db03c564 100644--- a/packages/core/src/repowise/core/ingestion/parser/calls.py+++ b/packages/core/src/repowise/core/ingestion/parser/calls.py@@ -174,7 +174,9 @@ def _dart_argument_count(selector: Node | None) -> int | None:# The receiver captures that are themselves a member access, by language (the# queries widen only these two), and what a plain dotted path of names looks# like once whitespace is gone.-_PATH_RECEIVERS = frozenset({("typescript", "member_expression"), ("python", "attribute")})+_PATH_RECEIVERS = frozenset(+ {("typescript", "member_expression"), ("python", "attribute"), ("apex", "field_access")}+)_DOTTED_PATH = re.compile(r"[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+")diff --git a/packages/core/src/repowise/core/ingestion/parser/symbol_rules.py b/packages/core/src/repowise/core/ingestion/parser/symbol_rules.pyindex 926da41e3..c7b386717 100644--- a/packages/core/src/repowise/core/ingestion/parser/symbol_rules.py+++ b/packages/core/src/repowise/core/ingestion/parser/symbol_rules.py@@ -18,6 +18,7 @@ from ..extractors import ()from ..extractors.bindings.ts_js import declarator_binds_callable, declarator_value_is_module_reffrom ..extractors.visibility import (+ refine_apex_visibility,refine_cpp_visibility,refine_csharp_visibility,refine_java_visibility,@@ -381,6 +382,10 @@ def _refine_visibility(# interface or annotation body, which the modifier-text fn cannot see.if language == "java":return refine_java_visibility(def_node), False+ # Apex: the keyword is read from the AST, where annotation text cannot+ # pass for one, and an interface member is public.+ if language == "apex":+ return refine_apex_visibility(def_node), False# TS/JS: a top-level declaration is only public when exported —# inline, via ``export { x }`` lists, or ``export default x``.if language in _TS_JS_LANGUAGES:diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.pyindex e41e90971..1d2257589 100644--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py@@ -43,7 +43,11 @@ from .lang_helpers.objc import (_objc_symbol_name,)from .lang_helpers.pascal import _dedupe_pascal_interface_symbols, _qualified_pascal_parent-from .lang_helpers.source_prep import prepare_objectivec_source, prepare_pascal_source+from .lang_helpers.source_prep import (+ prepare_apex_source,+ prepare_objectivec_source,+ prepare_pascal_source,+)from .lang_helpers.ts_js import _ts_nested_object_method_ownerfrom .lang_helpers.type_heads import (TYPE_HEAD_EXTRACTORS,@@ -93,6 +97,7 @@ __all__ = ["import_load_kind","in_anonymous_class","is_anonymous_member",+ "prepare_apex_source","prepare_objectivec_source","prepare_pascal_source","scope_segment",diff --git a/packages/core/src/repowise/core/ingestion/queries/apex.scm b/packages/core/src/repowise/core/ingestion/queries/apex.scmnew file mode 100644index 000000000..b18d4da80--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/queries/apex.scm@@ -0,0 +1,168 @@+; =============================================================================+; repowise — Apex symbol and call queries+; tree-sitter-language-pack "apex" (aheber/tree-sitter-sfapex)+; =============================================================================+; The grammar is Java-shaped and keeps Java's node and field names, so these+; patterns follow java.scm. Apex has no import statement. Inline SOQL/SOSL+; (query_expression) and DML (dml_expression) are not calls and are left out.++; ---------------------------------------------------------------------------+; Symbols+; ---------------------------------------------------------------------------++; The whole ``modifiers`` node is the modifier capture: its annotations+; (@AuraEnabled, @IsTest, @InvocableMethod, @RestResource, ...) lead it, so+; they reach Symbol.decorators exactly as Java's do.+(class_declaration+ (modifiers)? @symbol.modifiers+ name: (identifier) @symbol.name+) @symbol.def++(interface_declaration+ (modifiers)? @symbol.modifiers+ name: (identifier) @symbol.name+) @symbol.def++(enum_declaration+ (modifiers)? @symbol.modifiers+ name: (identifier) @symbol.name+) @symbol.def++; ``trigger Name on SObject (events) { ... }``: the sObject and events are in+; the signature (see extractors/signatures.py).+(trigger_declaration+ name: (identifier) @symbol.name+) @symbol.def++(method_declaration+ (modifiers)? @symbol.modifiers+ name: (identifier) @symbol.name+ parameters: (formal_parameters) @symbol.params+) @symbol.def++(constructor_declaration+ (modifiers)? @symbol.modifiers+ name: (identifier) @symbol.name+ parameters: (formal_parameters) @symbol.params+) @symbol.def++; A property is a field with an accessor list: ``public String name { get; set; }``.+; Plain fields are not symbols, as in Java.+(field_declaration+ (modifiers)? @symbol.modifiers+ declarator: (variable_declarator+ name: (identifier) @symbol.name)+ (accessor_list)+) @symbol.def++; ---------------------------------------------------------------------------+; Calls+; ---------------------------------------------------------------------------++; foo(args). ``!object`` keeps member calls out: unlike java.scm's+; unconstrained pattern, ``a.b.c()`` and ``Outer.Inner.m()`` must never+; arrive as a receiver-less ``c()``/``m()`` that the resolver would read+; as a call on the caller's own class.+(method_invocation+ !object+ name: (identifier) @call.target+ arguments: (argument_list) @call.arguments+) @call.site++; obj.method(args) / Class.staticMethod(args)+(method_invocation+ object: (identifier) @call.receiver+ name: (identifier) @call.target+ arguments: (argument_list) @call.arguments+) @call.site++; this.field.method(args): the field is the receiver, typed against the+; caller's own class (see java.scm for why only this/super qualify).+(method_invocation+ object: (field_access+ object: [(this) (super)]+ field: (identifier) @call.receiver+ )+ name: (identifier) @call.target+ arguments: (argument_list) @call.arguments+) @call.site++; Outer.Inner.staticMethod(args), a.b.c(args): the dotted+; path is the receiver (parser/calls.py keeps it only as a plain path of+; names). A path headed by this/super takes the pattern above at its first hop.+(method_invocation+ object: (field_access+ object: [(identifier) (field_access)]+ ) @call.receiver+ name: (identifier) @call.target+ arguments: (argument_list) @call.arguments+) @call.site++; this.method(args) / super.method(args)+(method_invocation+ object: [(this) (super)] @call.receiver+ name: (identifier) @call.target+ arguments: (argument_list) @call.arguments+) @call.site++; ((Foo) x).bar(args): the cast names the receiver's type.+(method_invocation+ object: (parenthesized_expression+ (cast_expression+ .+ type: (type_identifier) @call.receiver+ .+ value: (_)+ )+ )+ name: (identifier) @call.target+ arguments: (argument_list) @call.arguments+) @call.site++; new Foo().bar(args) / new Outer.Inner().bar(args)+(method_invocation+ object: (object_creation_expression+ type: [+ (type_identifier) @call.receiver+ (scoped_type_identifier (type_identifier) @call.receiver .)+ ]+ )+ name: (identifier) @call.target+ arguments: (argument_list) @call.arguments+) @call.site++; obj.method1().method2(args)+(method_invocation+ object: (method_invocation) @call.receiver_call+ name: (identifier) @call.target+ arguments: (argument_list) @call.arguments+) @call.site++; new ClassName(args)+(object_creation_expression+ type: (type_identifier) @call.target+ 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.+(object_creation_expression+ type: (scoped_type_identifier+ (type_identifier) @call.target .)+ arguments: (argument_list) @call.arguments+) @call.site++; ---------------------------------------------------------------------------+; Type references (``@param.type``), as in java.scm+; ---------------------------------------------------------------------------++(formal_parameter type: (_) @param.type)+(field_declaration type: (_) @param.type)+(method_declaration type: (_) @param.type)+(object_creation_expression type: (_) @param.type)+(local_variable_declaration type: (_) @param.type)+(enhanced_for_statement type: (_) @param.type)+(superclass (_) @param.type)+(interfaces (type_list (_) @param.type))+(extends_interfaces (type_list (_) @param.type))+(type_arguments (_) @param.type)diff --git a/packages/core/src/repowise/core/ingestion/sfc_source.py b/packages/core/src/repowise/core/ingestion/sfc_source.pyindex 29a2d25f9..56c203253 100644--- a/packages/core/src/repowise/core/ingestion/sfc_source.py+++ b/packages/core/src/repowise/core/ingestion/sfc_source.py@@ -892,4 +892,8 @@ def prepare_source(language: str, source: bytes, *, path: str | None = None) ->from .parser_helpers import prepare_objectivec_sourcereturn prepare_objectivec_source(source)+ if language == "apex" and source:+ from .parser_helpers import prepare_apex_source++ return prepare_apex_source(source)return sourcediff --git a/packages/core/src/repowise/core/ingestion/symbol_identity.py b/packages/core/src/repowise/core/ingestion/symbol_identity.pyindex 663e94da5..c03816604 100644--- a/packages/core/src/repowise/core/ingestion/symbol_identity.py+++ b/packages/core/src/repowise/core/ingestion/symbol_identity.py@@ -301,6 +301,7 @@ def _rust_cfg_predicate(symbol: Symbol) -> str | None:# variant (C ``#if`` branches, Rust ``cfg``) registers here as its own function._DISCRIMINATORS: dict[str, Callable[[Symbol], str | None]] = {"java": _parameter_count,+ "apex": _parameter_count,"csharp": _parameter_count,"cpp": _parameter_count,"kotlin": _parameter_count,diff --git a/tests/fixtures/lang_samples/apex/AccountService.cls b/tests/fixtures/lang_samples/apex/AccountService.clsnew file mode 100644index 000000000..1edfcf56d--- /dev/null+++ b/tests/fixtures/lang_samples/apex/AccountService.cls@@ -0,0 +1,49 @@+/**+ * Account operations exposed to Lightning.+ */+public with sharing class AccountService extends BaseService implements Queueable, Database.AllowsCallouts {+ public String status { get; set; }+ private static final Integer LIMIT_SIZE = 50;++ public AccountService() {+ this(LIMIT_SIZE);+ }++ public AccountService(Integer size) {+ super(size);+ }++ /** Accounts matching a name. */+ @AuraEnabled(cacheable=true)+ public static List<Account> findByName(String name) {+ AccountSelector selector = new AccountSelector();+ List<Account> rows = selector.byName(name);+ AccountSelector.log(name);+ System.debug(rows.size());+ return [SELECT Id, Name FROM Account WHERE Name = :name LIMIT 50];+ }++ public void execute(QueueableContext context) {+ Account acc = new Account(Name = 'x');+ insert acc;+ this.notify(acc);+ new Result.Builder().build();+ Result.Codes.lookup('A');+ }++ private void notify(Account acc) {+ helper();+ }++ private void helper() {}++ public class Result {+ public Boolean ok { get; private set; }+ }++ public interface Notifier extends Callable {+ void send(String message);+ }++ public enum Mode { SYNC, ASYNC }+}diff --git a/tests/fixtures/lang_samples/apex/AccountTrigger.trigger b/tests/fixtures/lang_samples/apex/AccountTrigger.triggernew file mode 100644index 000000000..7a41c3e5e--- /dev/null+++ b/tests/fixtures/lang_samples/apex/AccountTrigger.trigger@@ -0,0 +1,4 @@+trigger AccountTrigger on Account (before insert, after update) {+ AccountTriggerHandler.run(Trigger.new);+ new AccountService().execute(null);+}diff --git a/tests/unit/dead_code/test_cobol_external_entry.py b/tests/unit/dead_code/test_cobol_external_entry.pyindex aef0d08cb..68e9bec35 100644--- a/tests/unit/dead_code/test_cobol_external_entry.py+++ b/tests/unit/dead_code/test_cobol_external_entry.py@@ -3,6 +3,7 @@from __future__ import annotationsimport networkx as nx+import pytestfrom repowise.core.analysis.dead_code.analyzer import DeadCodeAnalyzer@@ -46,3 +47,28 @@ def test_ordinary_code_language_remains_in_scope() -> None:{"detect_zombie_packages": False})assert {finding.kind for finding in report.findings} == {"unreachable_file"}+++def _private_method_graph(language: str) -> nx.DiGraph:+ graph = nx.DiGraph()+ path = f"src/Payroll.{language}"+ graph.add_node(path, node_type="file", language=language, is_entry_point=True,+ is_test=False, symbol_count=1)+ graph.add_node(f"{path}::Helper", node_type="symbol", file_path=path, language=language,+ name="Helper", kind="class", visibility="private", start_line=5, end_line=8)+ graph.add_edge(path, f"{path}::Helper", edge_type="defines")+ return graph++[email protected]("language", ["apex", "cobol"])+def test_exempt_language_private_symbol_is_not_an_unused_internal(language: str) -> None:+ # Apex private symbols back triggers, @AuraEnabled and test classes the+ # graph cannot see yet, so the internal pass honours the exemption too.+ report = DeadCodeAnalyzer(_private_method_graph(language), git_meta_map={}).analyze(+ {"detect_zombie_packages": False}+ )+ assert report.findings == []+ control = DeadCodeAnalyzer(_private_method_graph("java"), git_meta_map={}).analyze(+ {"detect_zombie_packages": False}+ )+ assert "unused_internal" in {finding.kind for finding in control.findings}diff --git a/tests/unit/health/golden/health_engine.json b/tests/unit/health/golden/health_engine.jsonindex 2fcd804a0..d0ba1a4e5 100644--- a/tests/unit/health/golden/health_engine.json+++ b/tests/unit/health/golden/health_engine.json@@ -863,6 +863,44 @@},"lang_samples": {"metrics": [+ {+ "file_path": "apex/AccountService.cls",+ "score": null,+ "max_ccn": null,+ "max_nesting": null,+ "nloc": 40,+ "has_test_file": false,+ "module": "apex",+ "duplication_pct": null,+ "line_coverage_pct": null,+ "branch_coverage_pct": null,+ "defect_score": null,+ "maintainability_score": null,+ "performance_score": null,+ "structure_deduction": null,+ "history_deduction": null,+ "is_test": false,+ "code_origin": "production"+ },+ {+ "file_path": "apex/AccountTrigger.trigger",+ "score": null,+ "max_ccn": null,+ "max_nesting": null,+ "nloc": 4,+ "has_test_file": false,+ "module": "apex",+ "duplication_pct": null,+ "line_coverage_pct": null,+ "branch_coverage_pct": null,+ "defect_score": null,+ "maintainability_score": null,+ "performance_score": null,+ "structure_deduction": null,+ "history_deduction": null,+ "is_test": false,+ "code_origin": "production"+ },{"file_path": "cpp/assertions.cpp","score": 10.0,@@ -5000,8 +5038,8 @@"history_hotspot": null,"production_average": 9.59,"production_file_count": 63,- "unanalysed_file_count": 4,- "analysed_share": 0.9403+ "unanalysed_file_count": 6,+ "analysed_share": 0.913},"repo_function_mod_p80": null,"suggestions": [diff --git a/tests/unit/ingestion/parser/golden/apex.json b/tests/unit/ingestion/parser/golden/apex.jsonnew file mode 100644index 000000000..251ec7bb0--- /dev/null+++ b/tests/unit/ingestion/parser/golden/apex.json@@ -0,0 +1,663 @@+{+ "apex/AccountService.cls": {+ "file_info": {+ "path": "lang_samples/apex/AccountService.cls",+ "language": "apex",+ "size_bytes": 1303,+ "is_test": false,+ "is_config": false,+ "is_api_contract": false,+ "is_entry_point": false,+ "is_manifest_entry": false,+ "is_reachability_root": false+ },+ "symbols": [+ {+ "id": "lang_samples/apex/AccountService.cls::AccountService",+ "name": "AccountService",+ "qualified_name": "lang_samples.apex.AccountService.AccountService",+ "kind": "class",+ "signature": "class AccountService",+ "start_line": 4,+ "end_line": 49,+ "docstring": "Account operations exposed to Lightning.",+ "decorators": [],+ "visibility": "public",+ "is_async": false,+ "complexity_estimate": 1,+ "language": "apex",+ "parent_name": null,+ "is_exported_symbol": false,+ "is_declaration": false,+ "type_parameter_count": null,+ "extension_receiver": null,+ "written_receiver": null,+ "modifiers": [],+ "alias_of": null+ },+ {+ "id": "lang_samples/apex/AccountService.cls::AccountService::status",+ "name": "status",+ "qualified_name": "lang_samples.apex.AccountService.AccountService.status",+ "kind": "variable",+ "signature": "status",+ "start_line": 5,+ "end_line": 5,+ "docstring": null,+ "decorators": [],+ "visibility": "public",+ "is_async": false,+ "complexity_estimate": 1,+ "language": "apex",+ "parent_name": "AccountService",+ "is_exported_symbol": false,+ "is_declaration": false,+ "type_parameter_count": null,+ "extension_receiver": null,+ "written_receiver": null,+ "modifiers": [],+ "alias_of": null+ },+ {+ "id": "lang_samples/apex/AccountService.cls::AccountService::AccountService#0",+ "name": "AccountService",+ "qualified_name": "lang_samples.apex.AccountService.AccountService.AccountService",+ "kind": "method",+ "signature": "AccountService()",+ "start_line": 8,+ "end_line": 10,+ "docstring": null,+ "decorators": [],+ "visibility": "public",+ "is_async": false,+ "complexity_estimate": 1,+ "language": "apex",+ "parent_name": "AccountService",+ "is_exported_symbol": false,+ "is_declaration": false,+ "type_parameter_count": null,+ "extension_receiver": null,+ "written_receiver": null,+ "modifiers": [],+ "alias_of": null+ },+ {+ "id": "lang_samples/apex/AccountService.cls::AccountService::AccountService#1",+ "name": "AccountService",+ "qualified_name": "lang_samples.apex.AccountService.AccountService.AccountService",+ "kind": "method",+ "signature": "AccountService(Integer size)",+ "start_line": 12,+ "end_line": 14,+ "docstring": null,+ "decorators": [],+ "visibility": "public",+ "is_async": false,+ "complexity_estimate": 1,+ "language": "apex",+ "parent_name": "AccountService",+ "is_exported_symbol": false,+ "is_declaration": false,+ "type_parameter_count": null,+ "extension_receiver": null,+ "written_receiver": null,+ "modifiers": [],+ "alias_of": null+ },+ {+ "id": "lang_samples/apex/AccountService.cls::AccountService::findByName",+ "name": "findByName",+ "qualified_name": "lang_samples.apex.AccountService.AccountService.findByName",+ "kind": "method",+ "signature": "findByName(String name) -> List<Account>",+ "start_line": 17,+ "end_line": 24,+ "docstring": "Accounts matching a name.",+ "decorators": [+ "@AuraEnabled(cacheable=true)\n public static"+ ],+ "visibility": "public",+ "is_async": false,+ "complexity_estimate": 1,+ "language": "apex",+ "parent_name": "AccountService",+ "is_exported_symbol": false,+ "is_declaration": false,+ "type_parameter_count": null,+ "extension_receiver": null,+ "written_receiver": null,+ "modifiers": [],+ "alias_of": null+ },+ {+ "id": "lang_samples/apex/AccountService.cls::AccountService::execute",+ "name": "execute",+ "qualified_name": "lang_samples.apex.AccountService.AccountService.execute",+ "kind": "method",+ "signature": "execute(QueueableContext context) -> void",+ "start_line": 26,+ "end_line": 32,+ "docstring": null,+ "decorators": [],+ "visibility": "public",+ "is_async": false,+ "complexity_estimate": 1,+ "language": "apex",+ "parent_name": "AccountService",+ "is_exported_symbol": false,+ "is_declaration": false,+ "type_parameter_count": null,+ "extension_receiver": null,+ "written_receiver": null,+ "modifiers": [],+ "alias_of": null+ },+ {+ "id": "lang_samples/apex/AccountService.cls::AccountService::notify",+ "name": "notify",+ "qualified_name": "lang_samples.apex.AccountService.AccountService.notify",+ "kind": "method",+ "signature": "notify(Account acc) -> void",+ "start_line": 34,+ "end_line": 36,+ "docstring": null,+ "decorators": [],+ "visibility": "private",+ "is_async": false,+ "complexity_estimate": 1,+ "language": "apex",+ "parent_name": "AccountService",+ "is_exported_symbol": false,+ "is_declaration": false,+ "type_parameter_count": null,+ "extension_receiver": null,+ "written_receiver": null,+ "modifiers": [],+ "alias_of": null+ },+ {+ "id": "lang_samples/apex/AccountService.cls::AccountService::helper",+ "name": "helper",+ "qualified_name": "lang_samples.apex.AccountService.AccountService.helper",+ "kind": "method",+ "signature": "helper() -> void",+ "start_line": 38,+ "end_line": 38,+ "docstring": null,+ "decorators": [],+ "visibility": "private",+ "is_async": false,+ "complexity_estimate": 1,+ "language": "apex",+ "parent_name": "AccountService",+ "is_exported_symbol": false,+ "is_declaration": false,+ "type_parameter_count": null,+ "extension_receiver": null,+ "written_receiver": null,+ "modifiers": [],+ "alias_of": null+ },+ {+ "id": "lang_samples/apex/AccountService.cls::AccountService::Result",+ "name": "Result",+ "qualified_name": "lang_samples.apex.AccountService.AccountService.Result",+ "kind": "class",+ "signature": "class Result",+ "start_line": 40,+ "end_line": 42,+ "docstring": null,+ "decorators": [],+ "visibility": "public",+ "is_async": false,+ "complexity_estimate": 1,+ "language": "apex",+ "parent_name": "AccountService",+ "is_exported_symbol": false,+ "is_declaration": false,+ "type_parameter_count": null,+ "extension_receiver": null,+ "written_receiver": null,+ "modifiers": [],+ "alias_of": null+ },+ {+ "id": "lang_samples/apex/AccountService.cls::Result::ok",+ "name": "ok",+ "qualified_name": "lang_samples.apex.AccountService.Result.ok",+ "kind": "variable",+ "signature": "ok",+ "start_line": 41,+ "end_line": 41,+ "docstring": null,+ "decorators": [],+ "visibility": "public",+ "is_async": false,+ "complexity_estimate": 1,+ "language": "apex",+ "parent_name": "Result",+ "is_exported_symbol": false,+ "is_declaration": false,+ "type_parameter_count": null,+ "extension_receiver": null,+ "written_receiver": null,+ "modifiers": [],+ "alias_of": null+ },+ {+ "id": "lang_samples/apex/AccountService.cls::AccountService::Notifier",+ "name": "Notifier",+ "qualified_name": "lang_samples.apex.AccountService.AccountService.Notifier",+ "kind": "interface",+ "signature": "interface Notifier",+ "start_line": 44,+ "end_line": 46,+ "docstring": null,+ "decorators": [],+ "visibility": "public",+ "is_async": false,+ "complexity_estimate": 1,+ "language": "apex",+ "parent_name": "AccountService",+ "is_exported_symbol": false,+ "is_declaration": false,+ "type_parameter_count": null,+ "extension_receiver": null,+ "written_receiver": null,+ "modifiers": [],+ "alias_of": null+ },+ {+ "id": "lang_samples/apex/AccountService.cls::Notifier::send",+ "name": "send",+ "qualified_name": "lang_samples.apex.AccountService.Notifier.send",+ "kind": "method",+ "signature": "send(String message) -> void",+ "start_line": 45,+ "end_line": 45,+ "docstring": null,+ "decorators": [],+ "visibility": "public",+ "is_async": false,+ "complexity_estimate": 1,+ "language": "apex",+ "parent_name": "Notifier",+ "is_exported_symbol": false,+ "is_declaration": false,+ "type_parameter_count": null,+ "extension_receiver": null,+ "written_receiver": null,+ "modifiers": [],+ "alias_of": null+ },+ {+ "id": "lang_samples/apex/AccountService.cls::AccountService::Mode",+ "name": "Mode",+ "qualified_name": "lang_samples.apex.AccountService.AccountService.Mode",+ "kind": "enum",+ "signature": "enum Mode",+ "start_line": 48,+ "end_line": 48,+ "docstring": null,+ "decorators": [],+ "visibility": "public",+ "is_async": false,+ "complexity_estimate": 1,+ "language": "apex",+ "parent_name": "AccountService",+ "is_exported_symbol": false,+ "is_declaration": false,+ "type_parameter_count": null,+ "extension_receiver": null,+ "written_receiver": null,+ "modifiers": [],+ "alias_of": null+ }+ ],+ "imports": [],+ "exports": [+ "AccountService"+ ],+ "export_aliases": {},+ "calls": [+ {+ "target_name": "AccountSelector",+ "receiver_name": null,+ "caller_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::findByName",+ "line": 19,+ "argument_count": 0,+ "receiver_call": null,+ "scope_name": null,+ "edge_type": "calls",+ "supplied_props": null,+ "bare_name_fallback": false,+ "spawned": false,+ "argument_types": null,+ "argument_names": null+ },+ {+ "target_name": "byName",+ "receiver_name": "selector",+ "caller_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::findByName",+ "line": 20,+ "argument_count": 1,+ "receiver_call": null,+ "scope_name": null,+ "edge_type": "calls",+ "supplied_props": null,+ "bare_name_fallback": false,+ "spawned": false,+ "argument_types": null,+ "argument_names": null+ },+ {+ "target_name": "log",+ "receiver_name": "AccountSelector",+ "caller_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::findByName",+ "line": 21,+ "argument_count": 1,+ "receiver_call": null,+ "scope_name": null,+ "edge_type": "calls",+ "supplied_props": null,+ "bare_name_fallback": false,+ "spawned": false,+ "argument_types": null,+ "argument_names": null+ },+ {+ "target_name": "debug",+ "receiver_name": "System",+ "caller_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::findByName",+ "line": 22,+ "argument_count": 1,+ "receiver_call": null,+ "scope_name": null,+ "edge_type": "calls",+ "supplied_props": null,+ "bare_name_fallback": false,+ "spawned": false,+ "argument_types": null,+ "argument_names": null+ },+ {+ "target_name": "size",+ "receiver_name": "rows",+ "caller_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::findByName",+ "line": 22,+ "argument_count": 0,+ "receiver_call": null,+ "scope_name": null,+ "edge_type": "calls",+ "supplied_props": null,+ "bare_name_fallback": false,+ "spawned": false,+ "argument_types": null,+ "argument_names": null+ },+ {+ "target_name": "Account",+ "receiver_name": null,+ "caller_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::execute",+ "line": 27,+ "argument_count": 1,+ "receiver_call": null,+ "scope_name": null,+ "edge_type": "calls",+ "supplied_props": null,+ "bare_name_fallback": false,+ "spawned": false,+ "argument_types": null,+ "argument_names": null+ },+ {+ "target_name": "notify",+ "receiver_name": "this",+ "caller_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::execute",+ "line": 29,+ "argument_count": 1,+ "receiver_call": null,+ "scope_name": null,+ "edge_type": "calls",+ "supplied_props": null,+ "bare_name_fallback": false,+ "spawned": false,+ "argument_types": null,+ "argument_names": null+ },+ {+ "target_name": "Builder",+ "receiver_name": null,+ "caller_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::execute",+ "line": 30,+ "argument_count": 0,+ "receiver_call": null,+ "scope_name": null,+ "edge_type": "calls",+ "supplied_props": null,+ "bare_name_fallback": false,+ "spawned": false,+ "argument_types": null,+ "argument_names": null+ },+ {+ "target_name": "build",+ "receiver_name": "Builder",+ "caller_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::execute",+ "line": 30,+ "argument_count": 0,+ "receiver_call": null,+ "scope_name": null,+ "edge_type": "calls",+ "supplied_props": null,+ "bare_name_fallback": false,+ "spawned": false,+ "argument_types": null,+ "argument_names": null+ },+ {+ "target_name": "lookup",+ "receiver_name": "Result.Codes",+ "caller_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::execute",+ "line": 31,+ "argument_count": 1,+ "receiver_call": null,+ "scope_name": null,+ "edge_type": "calls",+ "supplied_props": null,+ "bare_name_fallback": false,+ "spawned": false,+ "argument_types": null,+ "argument_names": null+ },+ {+ "target_name": "helper",+ "receiver_name": null,+ "caller_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::notify",+ "line": 35,+ "argument_count": 0,+ "receiver_call": null,+ "scope_name": null,+ "edge_type": "calls",+ "supplied_props": null,+ "bare_name_fallback": false,+ "spawned": false,+ "argument_types": null,+ "argument_names": null+ }+ ],+ "heritage": [+ {+ "child_name": "AccountService",+ "parent_name": "BaseService",+ "kind": "extends",+ "line": 4+ },+ {+ "child_name": "AccountService",+ "parent_name": "Queueable",+ "kind": "implements",+ "line": 4+ },+ {+ "child_name": "AccountService",+ "parent_name": "AllowsCallouts",+ "kind": "implements",+ "line": 4+ },+ {+ "child_name": "Notifier",+ "parent_name": "Callable",+ "kind": "extends",+ "line": 44+ }+ ],+ "docstring": null,+ "parse_errors": [],+ "content_hash": "6949da34bdf9a93e9ad34a77548866187f44e3bea69f007715cdbcfbad9f5df0",+ "type_refs": [+ {+ "type_name": "BaseService",+ "line": 4,+ "origin": "extends"+ },+ {+ "type_name": "Account",+ "line": 18,+ "origin": "method_param"+ },+ {+ "type_name": "AccountSelector",+ "line": 19,+ "origin": "field_type"+ },+ {+ "type_name": "Account",+ "line": 20,+ "origin": "field_type"+ },+ {+ "type_name": "Account",+ "line": 27,+ "origin": "field_type"+ },+ {+ "type_name": "Builder",+ "line": 30,+ "origin": "composite_literal"+ },+ {+ "type_name": "Account",+ "line": 34,+ "origin": "param_type"+ }+ ],+ "local_refs": [],+ "registrars": [],+ "references": []+ },+ "apex/AccountTrigger.trigger": {+ "file_info": {+ "path": "lang_samples/apex/AccountTrigger.trigger",+ "language": "apex",+ "size_bytes": 152,+ "is_test": false,+ "is_config": false,+ "is_api_contract": false,+ "is_entry_point": false,+ "is_manifest_entry": false,+ "is_reachability_root": false+ },+ "symbols": [+ {+ "id": "lang_samples/apex/AccountTrigger.trigger::AccountTrigger",+ "name": "AccountTrigger",+ "qualified_name": "lang_samples.apex.AccountTrigger.AccountTrigger",+ "kind": "function",+ "signature": "trigger AccountTrigger on Account (before insert, after update)",+ "start_line": 1,+ "end_line": 4,+ "docstring": null,+ "decorators": [],+ "visibility": "public",+ "is_async": false,+ "complexity_estimate": 1,+ "language": "apex",+ "parent_name": null,+ "is_exported_symbol": false,+ "is_declaration": false,+ "type_parameter_count": null,+ "extension_receiver": null,+ "written_receiver": null,+ "modifiers": [],+ "alias_of": null+ }+ ],+ "imports": [],+ "exports": [+ "AccountTrigger"+ ],+ "export_aliases": {},+ "calls": [+ {+ "target_name": "run",+ "receiver_name": "AccountTriggerHandler",+ "caller_symbol_id": "lang_samples/apex/AccountTrigger.trigger::AccountTrigger",+ "line": 2,+ "argument_count": 1,+ "receiver_call": null,+ "scope_name": null,+ "edge_type": "calls",+ "supplied_props": null,+ "bare_name_fallback": false,+ "spawned": false,+ "argument_types": null,+ "argument_names": null+ },+ {+ "target_name": "AccountService",+ "receiver_name": null,+ "caller_symbol_id": "lang_samples/apex/AccountTrigger.trigger::AccountTrigger",+ "line": 3,+ "argument_count": 0,+ "receiver_call": null,+ "scope_name": null,+ "edge_type": "calls",+ "supplied_props": null,+ "bare_name_fallback": false,+ "spawned": false,+ "argument_types": null,+ "argument_names": null+ },+ {+ "target_name": "execute",+ "receiver_name": "AccountService",+ "caller_symbol_id": "lang_samples/apex/AccountTrigger.trigger::AccountTrigger",+ "line": 3,+ "argument_count": 1,+ "receiver_call": null,+ "scope_name": null,+ "edge_type": "calls",+ "supplied_props": null,+ "bare_name_fallback": false,+ "spawned": false,+ "argument_types": null,+ "argument_names": null+ }+ ],+ "heritage": [],+ "docstring": null,+ "parse_errors": [],+ "content_hash": "0c93f053393375048548902958583dcef31915350a0a0d910be501293a7a114a",+ "type_refs": [+ {+ "type_name": "AccountService",+ "line": 3,+ "origin": "composite_literal"+ }+ ],+ "local_refs": [],+ "registrars": [],+ "references": []+ }+}diff --git a/tests/unit/ingestion/parser/test_apex.py b/tests/unit/ingestion/parser/test_apex.pynew file mode 100644index 000000000..43f6e1900--- /dev/null+++ b/tests/unit/ingestion/parser/test_apex.py@@ -0,0 +1,236 @@+"""Unit tests for the Apex language pipeline.++Tests parse inline byte strings so no filesystem I/O is needed. Covers+symbols and kinds, inner classes, triggers, properties, annotations as+decorators, visibility, heritage, calls versus type references, the CumulusCI+namespace-token sanitiser, non-ASCII source and case variants.+"""++from __future__ import annotations++from repowise.core.ingestion.parser import ASTParser+from repowise.core.ingestion.sfc_source import prepare_source+from tests.unit.ingestion.parser._helpers import _make_file_info++CLASS_SOURCE = b"""\+/**+ * Account operations.+ */+@IsTest+public with sharing class AccountService extends BaseService implements Queueable, Database.Batchable<SObject> {+ public String status { get; set; }+ private Integer hidden;+ @SuppressWarnings('PMD.AvoidGlobalModifier')+ Integer count { get; private set; }++ public AccountService() { this(1); }+ public AccountService(Integer size) { super(size); }++ /** Find accounts. */+ @AuraEnabled(cacheable=true)+ global static List<Account> find(String name, Outer.Inner opt) {+ AccountSelector selector = new AccountSelector();+ selector.byName(name);+ AccountSelector.log(name);+ new Wrapper.Builder().build();+ Outer.Inner.staticCall();+ rows.items.size();+ System.debug(name);+ this.helper();+ helper();+ insert new Account(Name = name);+ return [SELECT Id FROM Account WHERE Name = :name];+ }++ void helper() {}+ webservice static String ws() { return ''; }++ public class Wrapper {+ public void build() {}+ }++ public interface Notifier extends IBase {+ void send(String message);+ }++ public enum Mode { SYNC, ASYNC }+}+"""++TRIGGER_SOURCE = b"""\+trigger AccountTrigger on Account (before insert, after update) {+ AccountTriggerHandler.run(Trigger.new);+}+"""+++def _parse(parser: ASTParser, source: bytes, path: str = "classes/AccountService.cls"):+ return parser.parse_file(_make_file_info(path, "apex"), source)+++def _by_name(result) -> dict:+ """Symbols by name; a class wins over its same-named constructors."""+ return {s.name: s for s in sorted(result.symbols, key=lambda s: s.kind == "class")}+++class TestApexSymbols:+ def test_kinds(self, parser: ASTParser) -> None:+ kinds = {(s.name, s.kind) for s in _parse(parser, CLASS_SOURCE).symbols}+ assert {+ ("AccountService", "class"),+ ("find", "method"),+ ("Wrapper", "class"),+ ("build", "method"),+ ("Notifier", "interface"),+ ("send", "method"),+ ("Mode", "enum"),+ ("status", "variable"),+ ("count", "variable"),+ } <= kinds++ def test_plain_field_is_not_a_symbol(self, parser: ASTParser) -> None:+ assert "hidden" not in _by_name(_parse(parser, CLASS_SOURCE))++ def test_constructor_overloads_get_their_own_ids(self, parser: ASTParser) -> None:+ ctors = [s for s in _parse(parser, CLASS_SOURCE).symbols if s.name == "AccountService"]+ ids = {s.id for s in ctors if s.kind != "class"}+ assert len(ids) == 2++ def test_inner_class_members_name_their_class(self, parser: ASTParser) -> None:+ symbols = _by_name(_parse(parser, CLASS_SOURCE))+ assert symbols["Wrapper"].parent_name == "AccountService"+ assert symbols["build"].parent_name == "Wrapper"+ assert symbols["send"].parent_name == "Notifier"++ def test_annotations_are_decorators(self, parser: ASTParser) -> None:+ symbols = _by_name(_parse(parser, CLASS_SOURCE))+ assert symbols["find"].decorators[0].startswith("@AuraEnabled(cacheable=true)")+ assert symbols["AccountService"].decorators[0].startswith("@IsTest")+ assert symbols["helper"].decorators == []++ def test_apexdoc(self, parser: ASTParser) -> None:+ symbols = _by_name(_parse(parser, CLASS_SOURCE))+ assert symbols["AccountService"].docstring == "Account operations."+ assert symbols["find"].docstring == "Find accounts."++ def test_visibility(self, parser: ASTParser) -> None:+ symbols = _by_name(_parse(parser, CLASS_SOURCE))+ assert symbols["find"].visibility == "public" # global+ assert symbols["ws"].visibility == "public" # webservice+ assert symbols["helper"].visibility == "private" # no keyword+ assert symbols["send"].visibility == "public" # interface member+ # Annotation text naming ``Global`` is not an access keyword.+ assert symbols["count"].visibility == "private"++ def test_trigger(self, parser: ASTParser) -> None:+ result = _parse(parser, TRIGGER_SOURCE, "triggers/AccountTrigger.trigger")+ (trigger,) = result.symbols+ assert (trigger.name, trigger.kind, trigger.visibility) == (+ "AccountTrigger",+ "function",+ "public",+ )+ assert trigger.signature == "trigger AccountTrigger on Account (before insert, after update)"+ (call,) = result.calls+ assert (call.receiver_name, call.target_name) == ("AccountTriggerHandler", "run")+ assert call.caller_symbol_id == trigger.id+++class TestApexHeritage:+ def test_extends_and_implements(self, parser: ASTParser) -> None:+ rels = {(h.child_name, h.kind, h.parent_name) for h in _parse(parser, CLASS_SOURCE).heritage}+ assert ("AccountService", "extends", "BaseService") in rels+ # Platform interfaces stay: they mark runtime-invoked contract methods.+ assert ("AccountService", "implements", "Queueable") in rels+ assert ("AccountService", "implements", "Batchable") in rels+ assert ("Notifier", "extends", "IBase") in rels++ def test_uppercase_keywords(self, parser: ASTParser) -> None:+ source = b"PUBLIC CLASS Foo EXTENDS Bar IMPLEMENTS Baz { }"+ rels = {(h.kind, h.parent_name) for h in _parse(parser, source, "Foo.cls").heritage}+ assert rels == {("extends", "Bar"), ("implements", "Baz")}+++class TestApexCalls:+ def _calls(self, parser: ASTParser) -> set[tuple[str | None, str]]:+ return {(c.receiver_name, c.target_name) for c in _parse(parser, CLASS_SOURCE).calls}++ def test_member_static_and_constructor_calls(self, parser: ASTParser) -> None:+ calls = self._calls(parser)+ assert {+ (None, "AccountSelector"),+ ("selector", "byName"),+ ("AccountSelector", "log"),+ ("Builder", "build"),+ ("this", "helper"),+ (None, "helper"),+ ("System", "debug"),+ } <= calls++ def test_dotted_receivers_keep_their_path(self, parser: ASTParser) -> None:+ calls = self._calls(parser)+ assert ("Outer.Inner", "staticCall") in calls+ assert ("rows.items", "size") in calls+ # Never a receiver-less copy that would read as an own-class call.+ assert (None, "staticCall") not in calls+ assert (None, "size") not in calls+ assert (None, "build") not in calls++ def test_constructor_chaining_is_not_a_call(self, parser: ASTParser) -> None:+ # ``this(..)`` / ``super(..)`` make no call site, as in java.scm.+ source = b"public class A extends B { public A() { this(1); } public A(Integer x) { super(x); } }"+ assert _parse(parser, source, "A.cls").calls == []++ def test_soql_and_dml_are_not_calls(self, parser: ASTParser) -> None:+ targets = {t for _, t in self._calls(parser)}+ assert not targets & {"insert", "SELECT", "Account_insert"}++ def test_type_positions_are_type_refs_not_calls(self, parser: ASTParser) -> None:+ result = _parse(parser, CLASS_SOURCE)+ type_names = {t.type_name for t in result.type_refs}+ assert {"AccountSelector", "Inner", "BaseService"} <= type_names+ # Builtins are filtered whatever their case.+ assert not type_names & {"String", "List", "Integer"}+ targets = {c.target_name for c in result.calls}+ assert "Inner" not in targets and "BaseService" not in targets++ def test_lowercase_builtin_types_are_filtered(self, parser: ASTParser) -> None:+ source = b"public class Foo { list<string> names; void m(map<id, Bar> x) {} }"+ type_names = {t.type_name for t in _parse(parser, source, "Foo.cls").type_refs}+ assert type_names == {"Bar"}+++class TestApexSource:+ def test_cumulusci_tokens_are_blanked_in_place(self) -> None:+ source = b"%%%NAMESPACE%%%Util.go(); x = %%%NAMESPACE_DOT%%%Foo__c.Name;"+ prepared = prepare_source("apex", source)+ assert len(prepared) == len(source)+ assert b"%%%" not in prepared+ assert prepared.index(b"Util.go") == source.index(b"Util.go")++ def test_namespaced_file_parses(self, parser: ASTParser) -> None:+ source = b"""\+public class Seed {+ public static void run() {+ %%%NAMESPACE%%%Util.go();+ }+}+"""+ result = _parse(parser, source, "scripts/Seed.cls")+ assert {s.name for s in result.symbols} == {"Seed", "run"}+ assert ("Util", "go") in {(c.receiver_name, c.target_name) for c in result.calls}++ def test_non_ascii_keeps_names_and_lines(self, parser: ASTParser) -> None:+ source = "public class CaféService {\n /** Résumé ✓ */\n public void m() { String s = 'éé'; helper(); }\n void helper() {}\n}\n".encode()+ result = _parse(parser, source, "CaféService.cls")+ symbols = _by_name(result)+ assert "CaféService" in symbols+ assert symbols["m"].docstring == "Résumé ✓"+ assert [c.line for c in result.calls if c.target_name == "helper"] == [3]++ def test_case_variants_keep_the_declared_name(self, parser: ASTParser) -> None:+ source = b"PUBLIC CLASS MixedCase { PUBLIC STATIC VOID DoIt() { HELPER.RUN(); } }"+ result = _parse(parser, source, "MixedCase.cls")+ symbols = _by_name(result)+ assert symbols["DoIt"].visibility == "public"+ assert ("HELPER", "RUN") in {(c.receiver_name, c.target_name) for c in result.calls}diff --git a/tests/unit/ingestion/test_language_capabilities.py b/tests/unit/ingestion/test_language_capabilities.pyindex 01baf14d4..72a9d3fcc 100644--- a/tests/unit/ingestion/test_language_capabilities.py+++ b/tests/unit/ingestion/test_language_capabilities.py@@ -111,7 +111,7 @@ class TestParityGoldens:camel = REGISTRY.camel_test_res_by_extension()assert set(camel) == {".java", ".kt", ".kts", ".scala", ".cs", ".swift", ".php",- ".hs", ".lhs", ".vb", ".m", ".mm",+ ".hs", ".lhs", ".vb", ".m", ".mm", ".cls", ".trigger", ".apex",}assert camel[".java"].pattern == r"(?<=[a-z0-9])(?:Tests|Test|IT)$"assert camel[".scala"].pattern == r"(?<=[a-z0-9])(?:Suite|Spec|Test)$"@@ -262,8 +262,10 @@ class TestImportSupportTiers:def test_unknown_language_reports_none(self) -> None:assert REGISTRY.import_support_for("klingon") == "none"- def test_cobol_is_exempt_from_static_dead_code_claims(self) -> None:- assert REGISTRY.dead_code_exempt_languages() == frozenset({"cobol"})+ def test_runtime_entered_languages_are_exempt_from_static_dead_code_claims(self) -> None:+ # Apex until its platform entry points (triggers, annotations,+ # platform interfaces) are modelled.+ assert REGISTRY.dead_code_exempt_languages() == frozenset({"cobol", "apex"})class TestLanguageTagParity:diff --git a/tests/unit/ingestion/test_overload_identity.py b/tests/unit/ingestion/test_overload_identity.pyindex c966f274b..dcb6be454 100644--- a/tests/unit/ingestion/test_overload_identity.py+++ b/tests/unit/ingestion/test_overload_identity.py@@ -807,7 +807,7 @@ def test_fixture_ids_carry_a_discriminator_only_on_collision() -> None:checked += 1if symbol.id == base and "`" not in symbol.id:continue- assert symbol.language in ("java", "csharp", "cpp", "kotlin"), symbol.id+ assert symbol.language in ("java", "apex", "csharp", "cpp", "kotlin"), symbol.idassert bases.count(base) > 1 or "`" in symbol.id, symbol.idassert checked > 500diff --git a/tests/unit/ingestion/test_receiver_types.py b/tests/unit/ingestion/test_receiver_types.pyindex 769b6717d..49827613f 100644--- a/tests/unit/ingestion/test_receiver_types.py+++ b/tests/unit/ingestion/test_receiver_types.py@@ -963,6 +963,7 @@ class TestClassScope:def test_the_language_set_is_what_the_patterns_declare() -> None:"""Excluding a language means removing its shapes, not gating a caller."""assert set(RECEIVER_TYPE_LANGUAGES) == {+ "apex","cpp","csharp","dart",