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): Extract Method for Apex (#4425)
Raghav Chamadiyaee744e7d01df
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.mdindex c807f2902..5af0ccfa9 100644--- a/docs/architecture/language-support.md+++ b/docs/architecture/language-support.md@@ -1003,6 +1003,13 @@ literal-bound loops) and on calls that run once, such as a lazily filled cache.Ceiling: `while` loops, `Database.executeBatch` and `System.schedule` are notreported, and untested complexity needs measured coverage or a test the graph sees.+Extract Method reads Apex as Java plus its own rules: names are+case-insensitive, inline SOQL reads only its `:bind` expressions, and+`switch on ... when` arms and `System.runAs` blocks are understood. Helpers are+written as Apex methods, static when the host method is. A `break` or+`continue` inside a `when` arm is modelled conservatively, as a read of the+loop's names at the switch.+Each flow (`.flow-meta.xml`, or a legacy `.flow` in a `flows/` directory) isone symbol named by its API name, linked to the Apex invocable actions,subflows, screen components and Apex-defined types it names. Apexdiff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex a2a0cf6c2..be2ef5225 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -252,6 +252,7 @@ This table is why a language is Full and not Good.- Dart, F# and Objective-C report class size, method count and CCN (supportingdetectors like God Class), but do not compute cohesion metrics (LCOM4).- An unmapped language produces no findings, never guessed ones.+- Apex has Extract Method: helpers are written as Apex methods, static where the host is.- The two test-quality markers (mock saturation, assertion-free test) areadvisory and never deduct from a score.diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.pyindex e3fb3414e..954fb2438 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py@@ -647,6 +647,17 @@ _APEX = LanguageNodeMap(call_kinds=frozenset({"method_invocation", "object_creation_expression", "query_expression", "dml_expression"}),+ # Dataflow (Extract Method): Java's statement shapes.+ assignment_kinds=frozenset({"assignment_expression"}),+ local_decl_kinds=frozenset({"local_variable_declaration"}),+ if_kinds=frozenset({"if_statement"}),+ block_kinds=frozenset({"block"}),+ return_kinds=frozenset({"return_statement"}),+ raise_kinds=frozenset({"throw_statement"}),+ break_kinds=frozenset({"break_statement"}),+ continue_kinds=frozenset({"continue_statement"}),+ # ``System.runAs(u) { }`` always runs its block once, like Python's ``with``.+ with_kinds=frozenset({"run_as_statement"}),)_RUST = LanguageNodeMap(diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py b/packages/core/src/repowise/core/analysis/health/dataflow/cfg.pyindex a83a30626..3e75a7506 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py@@ -618,17 +618,15 @@ class _CFGBuilder:"""Process a context-manager head and recurse into its body.A with-body always executes. If every path in the body terminates,- statements following the with-statement cannot fall through.+ statements following the with-statement cannot fall through. Apex's+ ``System.runAs(u) { }`` labels no ``body``: its block child is one."""self._record_head(cur, with_node)body_entry = self._new()self._edge(cur, body_entry)- body_out = self._process_seq(- self._body_stmts(with_node.child_by_field_name("body")),- body_entry,- )+ body_out = self._process_seq(self._body_stmts(self._block_of(with_node)), body_entry)if body_out is None:return Nonediff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.pyindex bd559c29c..9b4494419 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.py@@ -14,6 +14,7 @@ def/use pass is silent for it (no dialect = no signal), the safe default.from __future__ import annotations+from . import apex as _apexfrom . import cpp as _cppfrom . import csharp as _csharpfrom . import go as _go@@ -45,6 +46,7 @@ _REGISTER: tuple[tuple[str, BaseDefUseDialect], ...] = (("javascript", _ts_js.DIALECT),("jsx", _ts_js.DIALECT),("java", _java.DIALECT),+ ("apex", _apex.DIALECT),("rust", _rust.DIALECT),("cpp", _cpp.DIALECT),("csharp", _csharp.DIALECT),diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/apex.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/apex.pynew file mode 100644index 000000000..e34dcaa50--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/apex.py@@ -0,0 +1,421 @@+"""Apex ``DefUseDialect``.++Apex's statement grammar is Java's (tree-sitter-sfapex keeps Java's node and+field names), so this extends the Java dialect for what Apex adds:++- Identifiers are case-insensitive: ``toInsert`` and ``toinsert`` name one+ local. Every occurrence takes the spelling of the name's declaration in its+ method (:func:`_spellings`), so def/use and liveness compare one name, and a+ plan writes the name as it was declared. Two declarations spelled+ differently fold to the lowercase form, which no declared type matches, so+ their types are left as placeholders rather than guessed.+- Inline SOQL / SOSL (``[SELECT Id FROM Account WHERE Name = :n]``) reads only+ its ``:n`` bind expressions; field and object names are schema, not locals.+- ``new Account(Name = 'x')`` sets a field of the record: the ``Name =`` pair+ writes no local (Apex allows name=value pairs only in an SObject constructor).+- ``switch on x { when Account a { } }`` binds ``a`` for its arm; ``when``+ values are literals or enum constants, never variable reads. A ``break`` or+ ``continue`` in an arm leaves the enclosing loop (an arm never falls through),+ but the CFG keeps the switch whole, so the state at that point reaching the+ loop's exit or next iteration is modelled as a read, at the switch, of every+ name the loop mentions.+- ``System.runAs(u) { }`` is a ``with``-like block (``with_kinds``): its head+ reads ``u``.+- ``catch (DmlException e)`` declares ``e`` with a ``formal_parameter``.+- A ``static`` method has no instance, but a bare name in it can still be a+ static field, so its receiver is implicit with no name: such writes are never+ taken for locals, and its helper is written static.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from .base import (+ HandlerHead,+ Occurrence,+ Receiver,+ StatementDefUse,+ echoes,+ may_defs,+ node_text,+)+from .java import JavaDeclaredTypes, JavaDefUseDialect++if TYPE_CHECKING:+ from tree_sitter import Node++ from ...complexity.languages import LanguageNodeMap++_QUERY = "query_expression"+_BIND = "bound_apex_expression"+_OBJECT_CREATION = "object_creation_expression"+_SWITCH = "switch_expression"+_SWITCH_LABEL = "switch_label"+_WHEN_TYPE = "when_sobject_type" # ``when Account a``+_RUN_AS = "run_as_statement"+_CATCH = "catch_clause"+_LOOPS = frozenset({"for_statement", "enhanced_for_statement", "while_statement", "do_statement"})+_JUMPS = frozenset({"break_statement", "continue_statement"})+# What an identifier's spelling is resolved in: a method, constructor,+# property accessor or trigger body (anonymous scripts keep their spelling).+_SPELLING_SCOPES = frozenset(+ {"method_declaration", "constructor_declaration", "accessor_declaration", "trigger_declaration"}+)+_METHODS = frozenset({"method_declaration", "constructor_declaration"})+# Declarations whose ``name`` field binds a local.+_NAMED_BINDERS = frozenset({"formal_parameter", "variable_declarator", "enhanced_for_statement"})+_STOP = frozenset({"class_body"})+# Nodes whose own declarations end with them.+_BLOCK_SCOPES = frozenset({"block", *_LOOPS, _CATCH, "switch_rule"})+_DYNAMIC_QUERIES = frozenset(+ {+ ("database", "query"),+ ("database", "countquery"),+ ("database", "getquerylocator"),+ ("system.database", "query"),+ ("system.database", "countquery"),+ ("system.database", "getquerylocator"),+ ("search", "query"),+ ("system.search", "query"),+ }+)++# Spelling maps by method text. A pure function of the text, so a shared,+# bounded dict is safe across files and threads (a lost race only recomputes).+_SPELLING_CACHE: dict[bytes, dict[str, str]] = {}+_SPELLING_CACHE_MAX = 256+# The last scope asked about and its map: identifiers arrive method by method,+# so this skips re-reading the method's text per identifier. Holding the node+# keeps its tree alive, so ``==`` cannot match a node of a freed tree.+_LAST_SCOPE: list[tuple[Node, dict[str, str]]] = []+++def _spelling_scope(node: Node) -> Node | None:+ cur = node.parent+ while cur is not None:+ if cur.type in _SPELLING_SCOPES:+ return cur+ if cur.type in _STOP:+ return None+ cur = cur.parent+ return None+++def _binder_name(node: Node) -> Node | None:+ if node.type in _NAMED_BINDERS:+ return node.child_by_field_name("name")+ if node.type == _WHEN_TYPE:+ return next((c for c in node.named_children if c.type == "identifier"), None)+ return None+++def _spellings(scope: Node) -> dict[str, str]:+ """Per lowercased local name, the spelling to use for it in *scope*."""+ last = _LAST_SCOPE[-1] if _LAST_SCOPE else None+ if last is not None and last[0] == scope:+ return last[1]+ key = scope.text or b""+ cached = _SPELLING_CACHE.get(key)+ if cached is not None:+ _LAST_SCOPE[:] = [(scope, cached)]+ return cached+ declared: dict[str, set[str]] = {}+ stack = [scope]+ while stack:+ cur = stack.pop()+ name = _binder_name(cur)+ if name is not None and name.type == "identifier":+ text = node_text(name)+ declared.setdefault(text.lower(), set()).add(text)+ stack.extend(cur.named_children)+ out = {low: next(iter(sp)) if len(sp) == 1 else low for low, sp in declared.items()}+ if len(_SPELLING_CACHE) >= _SPELLING_CACHE_MAX:+ _SPELLING_CACHE.clear()+ _SPELLING_CACHE[key] = out+ _LAST_SCOPE[:] = [(scope, out)]+ return out+++def _is_local(node: Node) -> bool:+ """Whether identifier *node* names a local or parameter of its method."""+ scope = _spelling_scope(node)+ return scope is not None and node_text(node).lower() in _spellings(scope)+++def _canonical(node: Node) -> str:+ """*node*'s identifier text in its declared spelling (see module docs)."""+ text = node_text(node)+ scope = _spelling_scope(node)+ if scope is None:+ return text+ return _spellings(scope).get(text.lower(), text)+++class ApexDeclaredTypes(JavaDeclaredTypes):+ """Java's declarations, plus the type a ``when Account a`` arm binds."""++ def of(self, name: Node) -> str | None:+ holder = name.parent+ if holder is not None and holder.type == _WHEN_TYPE:+ typ = next((c for c in holder.named_children if c.type != "identifier"), None)+ return node_text(typ) if typ is not None else None+ return super().of(name)+++class ApexDefUseDialect(JavaDefUseDialect):+ language = "apex"+ declared_types = ApexDeclaredTypes(+ frozenset({"formal_parameter", "local_variable_declaration", "enhanced_for_statement"}),+ frozenset({"variable_declarator"}),+ )++ def _occ(self, node: Node) -> Occurrence:+ occ = super()._occ(node)+ name = _canonical(node)+ return occ if name == occ.name else Occurrence(name, occ.line, occ.column)++ # -- exception handlers ---------------------------------------------------++ def handler_head(self, handler: Node) -> HandlerHead:+ """``catch (DmlException e)`` names one type and binds ``e``."""+ param = _catch_param(handler)+ if param is None:+ return (), None+ typ = param.child_by_field_name("type")+ name = param.child_by_field_name("name")+ types = (node_text(typ),) if typ is not None else ()+ return types, _canonical(name) if name is not None else None++ def handler_def_use(self, handler: Node) -> StatementDefUse:+ param = _catch_param(handler)+ name = param.child_by_field_name("name") if param is not None else None+ if param is None or name is None:+ return StatementDefUse(defs=(), uses=())+ defs = [self._occ(name)]+ self._declare(defs, 0, param)+ return StatementDefUse(defs=tuple(defs), uses=())++ # -- receiver -------------------------------------------------------------++ def _own_receiver(self, fn_node: Node, lmap: LanguageNodeMap) -> Receiver | None:+ # A trigger declares no methods, so its plans carry no helper text; a+ # property (``accessor_list``) has no ``body`` and is never sliced.+ if fn_node.type not in _METHODS:+ return None+ if _is_static(fn_node):+ return self._receiver(frozenset(), implicit=True)+ return self._receiver(lmap.self_identifiers, implicit=True)++ # -- reads ----------------------------------------------------------------++ def collect_reads(self, node: Node | None, out: list[Occurrence]) -> None:+ if node is not None and node.type == _QUERY:+ for bind in _binds(node):+ self.collect_reads(bind, out)+ return+ if node is not None and node.type == _OBJECT_CREATION:+ self._creation(node, out, out, reads_only=True)+ return+ if node is not None and _dynamic_query(node):+ out.extend(self._scope_reads(node))+ super().collect_reads(node, out)++ # -- heads and statements -------------------------------------------------++ def _head(+ self, node: Node, lmap: LanguageNodeMap, defs: list[Occurrence], uses: list[Occurrence]+ ) -> None:+ if node.type == _RUN_AS:+ self._process(node.child_by_field_name("user"), defs, uses)+ return+ super()._head(node, lmap, defs, uses)++ def _process(self, node: Node | None, defs: list[Occurrence], uses: list[Occurrence]) -> None:+ if node is None:+ return+ t = node.type+ if t == _QUERY:+ for bind in _binds(node):+ self._process(bind, defs, uses)+ return+ if t == _OBJECT_CREATION:+ self._creation(node, defs, uses, reads_only=False)+ return+ if t == _SWITCH_LABEL: # ``when 1, RED``: literals and enum constants+ for child in node.named_children:+ if child.type == _WHEN_TYPE:+ self._process(child, defs, uses)+ return+ if t == _WHEN_TYPE: # ``when Account a`` declares ``a`` for the arm+ name = _binder_name(node)+ if name is not None:+ start = len(defs)+ defs.append(self._occ(name))+ self._declare(defs, start, node)+ return+ if t == _CATCH: # a handler inside a switch arm, walked whole+ sdu = self.handler_def_use(node)+ defs.extend(sdu.defs)+ self._process(node.child_by_field_name("body"), defs, uses)+ return+ if t == _RUN_AS: # inside a switch arm, walked whole+ for child in node.named_children:+ self._process(child, defs, uses)+ return+ if _dynamic_query(node):+ uses.extend(self._scope_reads(node))+ super()._process(node, defs, uses)+ if t == _SWITCH and _leaves_loop(node):+ uses.extend(self._loop_state(node))++ def _creation(+ self, node: Node, defs: list[Occurrence], uses: list[Occurrence], *, reads_only: bool+ ) -> None:+ """``new T(args)``: a ``Field = value`` argument sets a field of an+ SObject. Should the name also be a local of the method, the pair is+ kept as a write that may happen (a may-def and its echo), which can+ only refuse or widen a span, never hide a write."""+ for child in node.named_children:+ if child.type == "argument_list":+ for arg in child.named_children:+ value = self._pair_value(arg, defs, uses, reads_only=reads_only)+ self._walk(value, defs, uses, reads_only=reads_only)+ elif child.type != "class_body": # an anonymous class body is its own scope+ self._walk(child, defs, uses, reads_only=reads_only)++ def _pair_value(+ self, arg: Node, defs: list[Occurrence], uses: list[Occurrence], *, reads_only: bool+ ) -> Node | None:+ """The part of constructor argument *arg* to walk: a pair's value+ (recording the may-def when its name is a local), else *arg*."""+ target = arg.child_by_field_name("left") if arg.type == "assignment_expression" else None+ if target is None or target.type != "identifier":+ return arg+ if not reads_only and _is_local(target):+ occ = [self._occ(target)]+ defs.extend(may_defs(occ))+ uses.extend(echoes(occ))+ return arg.child_by_field_name("right")++ def _walk(+ self, node: Node | None, defs: list[Occurrence], uses: list[Occurrence], *, reads_only: bool+ ) -> None:+ if reads_only:+ self.collect_reads(node, uses)+ else:+ self._process(node, defs, uses)++ def _scope_reads(self, call: Node) -> list[Occurrence]:+ """A read at *call* of every local and parameter in scope there: a+ ``Database.query(q)`` string binds ``:name`` by name in the calling+ scope, so whatever holds the call must hold those names too."""+ line, column = call.start_point[0] + 1, call.start_point[1]+ names: set[str] = set()+ child, cur = call, call.parent+ while cur is not None and cur.type not in _STOP:+ # What *cur* binds before the call; a finished nested block is out of scope.+ stack = [cur]+ while stack:+ node = stack.pop()+ # A declarator the call initializes is not declared yet.+ name = None if node.id == cur.id and _binds_after(cur, child) else _binder_name(node)+ if name is not None and name.type == "identifier":+ names.add(_canonical(name))+ for c in node.named_children:+ if node.id == cur.id and c.start_byte >= child.start_byte:+ break+ if c.type not in _BLOCK_SCOPES:+ stack.append(c)+ if cur.type in _SPELLING_SCOPES:+ break+ child, cur = cur, cur.parent+ return [Occurrence(n, line, column) for n in sorted(names)]++ def _loop_state(self, switch: Node) -> list[Occurrence]:+ """A read at *switch* of every name its enclosing loop mentions: a+ ``break`` / ``continue`` in an arm carries the state there to the+ loop's exit or next iteration, which the CFG does not draw."""+ loop = switch.parent+ while loop is not None and loop.type not in _LOOPS:+ if loop.type in _SPELLING_SCOPES:+ return []+ loop = loop.parent+ if loop is None:+ return []+ line, column = switch.start_point[0] + 1, switch.start_point[1]+ seen: dict[str, Occurrence] = {}+ stack = [loop]+ while stack:+ cur = stack.pop()+ if cur.type in self.identifier_kinds:+ name = _canonical(cur)+ seen.setdefault(name, Occurrence(name, line, column))+ stack.extend(cur.named_children)+ return [seen[n] for n in sorted(seen)]+++def _dynamic_query(node: Node) -> bool:+ """``Database.query(q)`` and kin: SOQL / SOSL text whose ``:name`` binds+ resolve against the calling scope's locals (``queryWithBinds`` takes them+ in a map, so it is not one)."""+ if node.type != "method_invocation":+ return False+ obj, name = node.child_by_field_name("object"), node.child_by_field_name("name")+ if obj is None or name is None:+ return False+ owner = node_text(obj).lower().replace(" ", "")+ return (owner, node_text(name).lower()) in _DYNAMIC_QUERIES+++def _binds_after(holder: Node, child: Node) -> bool:+ """Whether *holder*'s own name is not yet bound in *child*: a declarator's+ initializer, an enhanced ``for``'s iterable."""+ if holder.type == "variable_declarator":+ return True+ value = holder.child_by_field_name("value") if holder.type == "enhanced_for_statement" else None+ return value is not None and value.id == child.id+++def _catch_param(handler: Node) -> Node | None:+ return next((c for c in handler.named_children if c.type == "formal_parameter"), None)+++def _is_static(holder: Node) -> bool:+ modifiers = next((c for c in holder.named_children if c.type == "modifiers"), None)+ if modifiers is None:+ return False+ return any(+ m.type == "modifier" and any(k.type == "static" for k in m.named_children)+ for m in modifiers.named_children+ )+++def _binds(query: Node) -> list[Node]:+ """The ``:expr`` bind expressions of an inline SOQL / SOSL query."""+ out: list[Node] = []+ stack = [query]+ while stack:+ cur = stack.pop()+ if cur.type == _BIND:+ out.extend(cur.named_children)+ continue+ stack.extend(reversed(cur.named_children))+ return out+++def _leaves_loop(switch: Node) -> bool:+ """Whether an arm of *switch* holds a ``break`` / ``continue`` that is not+ inside a loop of its own (so it leaves the loop around the switch)."""+ stack = list(switch.named_children)+ while stack:+ cur = stack.pop()+ if cur.type in _JUMPS:+ return True+ if cur.type in _LOOPS or cur.type in _SPELLING_SCOPES or cur.type in _STOP:+ continue+ stack.extend(cur.named_children)+ return False+++DIALECT = ApexDefUseDialect()diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice.pyindex 4e1746dc7..dd338612d 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py@@ -350,6 +350,8 @@ class _FunctionSlicer:slice_nloc = pre.code[j + 1] - pre.code[i]if not _MIN_SLICE_NLOC <= slice_nloc < self.max_slice_nloc:continue+ if _shares_a_line(self.fn_node, stmts[i], stmts[j]):+ continuefound = self._extraction(blk, i, j, decisions, slice_nloc, refused)if found is not None:out.append(found)@@ -462,6 +464,26 @@ class _FunctionSlicer:)+def _shares_a_line(fn_node: Node, first: Node, last: Node) -> bool:+ """Whether the line *first* starts on holds code before it, or the line+ *last* ends on holds code after it: a sibling (``} // done``), the header+ or brace of a block written compactly (``if (x) { a = 1;``), any byte that+ is not whitespace. A plan names whole lines, so lifting those lines would+ carry code that is not in the span."""+ rows = (fn_node.text or b"").split(b"\n")+ top, left = fn_node.start_point++ def row(at: tuple[int, int]) -> tuple[bytes, int]:+ line = rows[at[0] - top] if 0 <= at[0] - top < len(rows) else b""+ return line, at[1] - (left if at[0] == top else 0)++ head, col = row(first.start_point)+ if head[:col].strip():+ return True+ tail, col = row(last.end_point)+ return bool(tail[col:].strip())++def _scoped_resource_indexes(stmts: list[Node], lmap: LanguageNodeMap) -> list[int]:"""Positions in *stmts* of declarations whose resource the block disposesat its end (``scoped_resource_decl_kinds``)."""diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.pyindex 4ec86ca51..fc59f5779 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py@@ -641,7 +641,9 @@ def _symbol_fields(extraction: Extraction, receiver: Receiver | None) -> dict[sthazard = _receiver_hazard(receiver, uses, assigns)kind: str | None = Noneif receiver is not None and hazard != "receiver_unbound":- kind = "method" if receiver.implicit or uses else "function"+ # An implicit receiver with no name (an Apex static method) has no+ # instance: its bare names are static fields, and its helper is static.+ kind = "method" if receiver.names and (receiver.implicit or uses) else "function"name = min(receiver.names) if kind == "method" and receiver is not None else Nonefields: dict[str, Any] = {"new_symbol": {@@ -742,7 +744,12 @@ def _undeclared_outputs_note(analysis: FunctionAnalysis, extraction: Extraction)if not extraction.returns:return []inside = range(extraction.start_line, extraction.end_line + 1)- declared = [(d.var, d.line in inside) for d in analysis.def_use.definitions if d.declared_at is not None]+ # ``declares`` also marks a declarator spanning lines, where ``declared_at`` is None.+ declared = [+ (d.var, d.line in inside)+ for d in analysis.def_use.definitions+ if d.declared_at is not None or d.declares+ ]names = [rfor r in extraction.returnsdiff --git a/packages/core/src/repowise/core/analysis/health/refactoring/helper_naming.py b/packages/core/src/repowise/core/analysis/health/refactoring/helper_naming.pyindex 030186a52..2ab119df6 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/helper_naming.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/helper_naming.py@@ -29,6 +29,7 @@ if TYPE_CHECKING:NAME_CONVENTION: dict[str, str] = {"go": "camelCase","java": "camelCase",+ "apex": "camelCase","typescript": "camelCase","tsx": "camelCase","javascript": "camelCase",diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/render.py b/packages/core/src/repowise/core/analysis/health/refactoring/render.pyindex 923163486..1901b06fe 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/render.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/render.py@@ -57,12 +57,13 @@ _FAMILY: dict[str, str] = {"vue": "js","go": "go","java": "java",+ "apex": "apex","rust": "rust","cpp": "cpp","c": "cpp",}#: Languages whose signatures need every type written.-_TYPED = frozenset({"go", "java", "rust", "cpp"})+_TYPED = frozenset({"go", "java", "apex", "rust", "cpp"})#: Rust types that copy rather than move when passed by value.#: Outputs one call of a staged plan's helper can bind, per language with a#: staged renderer: a Python tuple, one TS / JS value.@@ -343,6 +344,11 @@ def _java_call(s: HelperShape) -> str:return _declared_call(s, f"{_name(s)}({_args(s)})", "var")+def _apex_call(s: HelperShape) -> str:+ """Java's call; Apex has no ``var``, so an unknown type is a placeholder."""+ return _declared_call(s, f"{_name(s)}({_args(s)})", TYPE_PLACEHOLDER)++def _declared_call(s: HelperShape, expr: str, inferred: str) -> str:"""``T x = expr;`` for an output the span declared (*inferred* when itstype is unknown), ``x = expr;`` for one declared before it."""@@ -436,6 +442,8 @@ _RENDERERS = {"js": (lambda s: _ts_sig(s, False), _ts_call),"go": (_go_sig, _go_call),"java": (_java_sig, _java_call),+ # Apex writes a helper as Java does (``private [static] T name(T a) {``).+ "apex": (_java_sig, _apex_call),"rust": (_rust_sig, _rust_call),"cpp": (_cpp_sig, _cpp_call),}diff --git a/tests/unit/health/test_dataflow_apex.py b/tests/unit/health/test_dataflow_apex.pynew file mode 100644index 000000000..be730c8de--- /dev/null+++ b/tests/unit/health/test_dataflow_apex.py@@ -0,0 +1,549 @@+"""Apex dataflow: def/use, CFG and Extract Method, in the Java tests' pattern.++Apex shares Java's statement grammar, so the Java dialect is reused; these+tests pin what Apex adds: case-insensitive names, inline SOQL binds, SObject+field pairs, ``switch on ... when`` arms, ``System.runAs`` blocks, static+methods whose bare names are static fields, and the helper written as Apex.+"""++from __future__ import annotations++import textwrap+from dataclasses import dataclass++import pytest++from repowise.core.analysis.health.complexity.languages import get_language_map+from repowise.core.analysis.health.dataflow import (+ analyze_file,+ find_extractions,+ get_defuse_dialect,+)+from repowise.core.analysis.health.refactoring import extract_method as em+from repowise.core.analysis.health.refactoring.extract_method import ExtractMethodDetector+from repowise.core.analysis.health.refactoring.models import RefactoringContext+++def _analyses(src: str):+ from repowise.core.ingestion.parser import _get_language++ if _get_language("apex") is None:+ pytest.skip("tree-sitter language pack missing for apex")+ res = analyze_file("m.cls", "apex", textwrap.dedent(src).encode(), flagged_only=False)+ return res.functions+++def _first(src: str):+ fns = _analyses(src)+ assert fns, "no function analysed"+ return fns[0]+++def _defs(fn) -> set[str]:+ return {d.var for d in fn.def_use.definitions}+++def _uses(fn) -> set[str]:+ return {u.name for b in fn.def_use.blocks.values() for u in b.uses if not u.echo}+++def _extractions(fn):+ lmap = get_language_map("apex")+ return find_extractions(fn, lmap, get_defuse_dialect("apex").receiver(fn.fn_node, lmap))+++def _line(src: str, marker: str) -> int:+ return next(i for i, ln in enumerate(textwrap.dedent(src).splitlines(), 1) if marker in ln)+++@dataclass+class _Finding:+ biomarker_type: str+ function_name: str+ line_start: int+ health_impact: float+++def _plans(src: str):+ fns = _analyses(src)+ ctx = RefactoringContext(+ file_path="m.cls",+ language="apex",+ nloc=100,+ findings=[_Finding("complex_method", f.name, f.start_line, 1.5) for f in fns],+ function_analyses=fns,+ )+ return {s.target_symbol: s.plan for s in ExtractMethodDetector().detect(ctx)}+++_SHAPES = """+public class Demo {+ Integer shapes(List<Account> accts, Integer base, String nm) {+ Integer total = 0, a = 1;+ total += base;+ a++;+ this.count = total;+ accts[0] = null;+ for (Integer i = 0; i < base; i++) { total += i; }+ for (Account acc : [SELECT Id FROM Account WHERE Name = :nm LIMIT :base]) {+ insert new Contact(LastName = acc.Name, AccountId = acc.Id);+ }+ try {+ update accts;+ } catch (DmlException e) {+ total = e.getNumDml();+ } finally {+ a = 0;+ }+ return total + a;+ }+}+"""+++def test_apex_def_use_classification():+ fn = _first(_SHAPES)+ defs = _defs(fn)+ assert {"total", "a", "i", "acc", "e", "accts", "base", "nm"} <= defs+ # Field and list targets, and SObject constructor pairs, bind no local.+ assert not {"count", "LastName", "AccountId"} & defs+ uses = _uses(fn)+ # Only the ``:nm`` / ``:base`` binds of the query are variable reads.+ assert {"nm", "base", "acc", "accts", "e", "total", "a"} <= uses+ assert not {"Id", "Name", "Account", "LastName", "getNumDml"} & uses+++def test_apex_names_fold_to_the_declared_spelling():+ fn = _first(+ """+ public class Demo {+ void f(Integer n) {+ List<Account> toInsert = new List<Account>();+ TOINSERT.add(new Account());+ insert toinsert;+ N = n + 1;+ }+ }+ """+ )+ assert {"toInsert", "n"} <= _defs(fn)+ assert not {"TOINSERT", "toinsert", "N"} & (_defs(fn) | _uses(fn))+++def test_apex_two_spellings_of_one_name_fold_to_lowercase():+ fn = _first(+ """+ public class Demo {+ void f(Boolean b) {+ if (b) { Integer Acc = 1; System.debug(acc); }+ else { Integer ACC = 2; System.debug(Acc); }+ }+ }+ """+ )+ assert "acc" in _defs(fn) and "acc" in _uses(fn)+ assert not {"Acc", "ACC"} & (_defs(fn) | _uses(fn))+++def test_apex_control_flow_builds_branches_loops_and_handlers():+ fn = _first(+ """+ public class Demo {+ Integer f(Integer x, List<Integer> xs) {+ Integer y = 0;+ if (x == 1) { y = 1; } else if (x == 2) { y = 2; } else { y = 3; }+ for (Integer v : xs) { y += v; }+ while (y > 100) { y -= 10; }+ do { y++; } while (y < 5);+ try { y = 1 / x; } catch (MathException e) { y = 0; } finally { x = 0; }+ return y;+ }+ }+ """+ )+ kinds = [b.kind for b in fn.cfg.blocks]+ assert kinds.count("branch") == 2+ assert kinds.count("loop_header") == 3+ assert kinds.count("handler") == 1+ assert len(fn.cfg.back_edges()) == 3+ assert fn.cfg.exit_id in fn.cfg.reachable_ids()+++def test_apex_run_as_block_is_built_and_its_user_read():+ src = """+ public class Demo {+ static void f(User u, Integer n) {+ Integer x = 0;+ System.runAs(u) {+ if (n > 0) { return; }+ x = 1;+ }+ System.debug(x);+ }+ }+ """+ fn = _first(src)+ assert "u" in _uses(fn)+ # The ``return`` inside the block is a real edge to the exit.+ block = next(+ b for b in fn.cfg.blocks if any(s.kind == "return_statement" for s in b.statements)+ )+ assert fn.cfg.exit_id in block.successors+++def test_apex_when_binds_its_arm_variable_and_reads_no_label():+ fn = _first(+ """+ public class Demo {+ Integer f(SObject rec, Season s) {+ Integer y = 0;+ switch on rec {+ when Account acct { y = acct.NumberOfEmployees; }+ when null { y = -1; }+ when else { y = 2; }+ }+ switch on s {+ when WINTER, SUMMER { y++; }+ }+ return y;+ }+ }+ """+ )+ acct = next(d for d in fn.def_use.definitions if d.var == "acct")+ assert acct.declares and not acct.may+ assert not {"WINTER", "SUMMER"} & _uses(fn)+ # Arm writes are may-defs, as in Java.+ assert any(d.var == "y" and d.may for d in fn.def_use.definitions)+++def test_apex_when_binder_has_its_declared_type():+ fn = _first(+ """+ public class Demo {+ void f(SObject rec) {+ switch on rec { when Account acct { System.debug(acct); } }+ }+ }+ """+ )+ d = next(d for d in fn.def_use.definitions if d.var == "acct")+ row = d.line - 1+ node = fn.fn_node.descendant_for_point_range((row, d.column), (row, d.column + len(d.var)))+ assert get_defuse_dialect("apex").declared_types.of(node) == "Account"+++# A long method whose compute-average tail is a clean extraction.+_PROCESS = """+public class Demo {+ private static Integer runs = 0;+ {static}Integer process(List<Integer> records, Integer threshold) {+ Integer errors = 0;+ List<Integer> results = new List<Integer>();+ for (Integer r : records) {+ if (r < 0) {+ errors++;+ continue;+ }+ results.add(r);+ }+ runs = runs + 1;+ Integer total = 0;+ Integer count = 0;+ for (Integer v : results) {+ if (v > threshold) {+ total += v;+ COUNT++;+ } else {+ total -= v;+ }+ }+ Integer average = 0;+ if (count > 0) {+ average = total / count;+ }+ return average + errors;+ }+}+"""++[email protected]("static", ["", "static "])+def test_apex_extract_method_fires(static):+ best = _extractions(_first(_PROCESS.replace("{static}", static)))[0]+ assert best.returns == ("average",)+ # ``runs`` is a static field written by bare name: never a parameter.+ assert best.params == ("results", "threshold")+ assert best.ccn_removed >= 1+++def test_apex_extractions_are_deterministic():+ fn = _first(_PROCESS.replace("{static}", ""))++ def serialize():+ return [(e.start_line, e.end_line, e.params, e.returns) for e in _extractions(fn)]++ first = serialize()+ for _ in range(3):+ assert serialize() == first+++def test_apex_static_host_gets_a_static_helper():+ plan = _plans(_PROCESS.replace("{static}", "public static "))["process"]+ sym = plan["new_symbol"]+ assert sym["kind"] == "function"+ assert sym["signature_text"] == (+ "private static Integer extractedHelper(List<Integer> results, Integer threshold) {"+ )+ assert plan["call_site"]["new_text"] == "Integer average = extractedHelper(results, threshold);"+ assert sym["return_text"] == "return average;"+++def test_apex_instance_host_gets_an_instance_helper():+ plan = _plans(_PROCESS.replace("{static}", "public "))["process"]+ assert plan["new_symbol"]["kind"] == "method"+ assert plan["new_symbol"]["signature_text"].startswith("private Integer extractedHelper(")+++def test_apex_unknown_output_type_is_a_placeholder_not_var():+ from repowise.core.analysis.health.refactoring.render import HelperShape, Slot, render++ shape = HelperShape(+ language="apex",+ name="loadTotals",+ kind="function",+ is_async=False,+ params=(Slot("items", "List<Account>"),),+ returns=(Slot("total", None),),+ out_declared=True,+ )+ assert render(shape)[:2] == (+ "private static <type> loadTotals(List<Account> items) {",+ "<type> total = loadTotals(items);",+ )+++_JUMPS = """+public class Demo {+ Integer f(List<Integer> xs, Integer limit) {+ Integer total = 0;+ for (Integer x : xs) {+ if (x > limit) {+ total += x;+ total += 1;+ }+ switch on x {+ when 0 { {jump} }+ when else { total -= 1; }+ }+ total = total * 2;+ total = total + 1;+ }+ return total;+ }+}+"""++[email protected]("jump", ["break;", "continue;", "return total;"])+def test_apex_extraction_never_spans_a_jump(jump):+ src = _JUMPS.replace("{jump}", jump)+ fn = _first(src)+ arm = _line(src, jump)+ assert all(not e.start_line <= arm <= e.end_line for e in _extractions(fn))+++# ``best`` is taken in and conditionally rewritten by the span over the ``if``+# pair; the rewrite below the switch hides that write from the CFG.+_ARM_EXIT = """+public class Demo {+ Integer f(List<Integer> xs, Integer best) {+ for (Integer x : xs) {+ if (x > 5) {+ best = x;+ }+ if (best > 100) {+ System.debug(best);+ }+ switch on x {+ when 0 { {jump} }+ }+ best = 0;+ }+ return best;+ }+}+"""++[email protected]("jump", ["break;", "continue;"])+def test_apex_arm_jump_keeps_the_state_before_the_switch_live(jump):+ # ``break`` / ``continue`` in a ``when`` arm leave the loop with ``best``+ # as the span left it, skipping ``best = 0``. A helper taking ``best`` must+ # hand it back, or the write is lost on that path.+ src = _ARM_EXIT.replace("{jump}", jump)+ fn = _first(src)+ start = _line(src, "if (x > 5)")+ offered = [e for e in _extractions(fn) if e.start_line == start]+ assert all("best" in e.returns for e in offered if "best" in e.params)+++def test_apex_dynamic_query_reads_every_local_in_scope():+ # ``Database.query`` resolves ``:ids`` / ``:stage`` by name where it runs,+ # so a helper holding the call must take them, and a span declaring one+ # ahead of the call must hand it back.+ src = """+ public class Demo {+ List<SObject> f(Set<Id> ids, Boolean wide) {+ String stage = 'Open';+ if (wide) { Integer unused = 1; }+ String q = 'SELECT Id FROM Opportunity WHERE Id IN :ids AND StageName = :stage';+ for (Integer k = 0; k < 2; k++) {+ List<SObject> rows = Database.query(q);+ }+ return Database.query(q);+ }+ }+ """+ fn = _first(src)+ call = _line(src, "List<SObject> rows = Database.query(q);")+ read = {u.name for b in fn.def_use.blocks.values() for u in b.uses if u.line == call}+ assert {"ids", "wide", "stage", "q", "k"} <= read+ assert not {"unused", "rows"} & read+++def test_apex_span_never_cuts_a_shared_line():+ src = """+ public class Demo {+ Integer f(List<Integer> xs, Integer limit) {+ Integer total = 0;+ for (Integer x : xs) {+ total += x;+ } // xs+ Integer extra = 0;+ if (limit > 0) {+ extra = limit * 2;+ } else {+ extra = 1;+ }+ Integer result = total + extra;+ System.debug(result);+ return result;+ }+ }+ """+ fn = _first(src)+ shared = _line(src, "} // xs")+ assert all(e.start_line != shared for e in _extractions(fn))+++def test_output_declared_over_several_lines_needs_no_declare_note():+ from repowise.core.analysis.health.dataflow import Extraction+ from repowise.core.analysis.health.refactoring.extract_method import _undeclared_outputs_note++ src = """+ public class Demo {+ void f(List<Account> xs) {+ if (xs.isEmpty()) { Account a = null; System.debug(a); }+ Account a = new Account(+ Name = 'x'+ );+ System.debug(a);+ }+ }+ """+ fn = _first(src)+ start = _line(src, "Account a = new Account(")+ span = Extraction(start, start + 2, (), ("a",), slice_nloc=3, ccn_removed=1)+ assert _undeclared_outputs_note(fn, span) == []+++def test_apex_constructor_pair_naming_a_local_is_a_may_def():+ fn = _first(+ """+ public class Demo {+ void f(Integer n) {+ Foo f = new Foo(n = 5);+ Account acc = new Account(Name = 'x');+ System.debug(n);+ }+ }+ """+ )+ n_defs = [d for d in fn.def_use.definitions if d.var == "n" and d.line > 3]+ assert n_defs and all(d.may for d in n_defs)+ assert "Name" not in _defs(fn)+++def test_apex_dynamic_query_iterable_does_not_read_its_own_loop_variable():+ src = """+ public class Demo {+ void f(String q) {+ for (Account a : Database.query(q)) {+ System.debug(a);+ }+ }+ }+ """+ fn = _first(src)+ header = _line(src, "Database.query(q)")+ read = {u.name for b in fn.def_use.blocks.values() for u in b.uses if u.line == header}+ assert "q" in read and "a" not in read+++def test_apex_trigger_plan_has_no_helper_text_and_property_is_not_sliced():+ from repowise.core.ingestion.parser import _get_language++ if _get_language("apex") is None:+ pytest.skip("tree-sitter language pack missing for apex")+ lines = ["trigger T on Account (before insert) {", " Integer seen = 0;"]+ for k in range(6):+ lines += [f" if (Trigger.new.size() > {k}) {{", f" seen += {k};", " }"]+ lines += [" System.debug(seen);", " System.debug(seen);", "}"]+ res = analyze_file("T.trigger", "apex", "\n".join(lines).encode(), flagged_only=False)+ (fn,) = res.functions+ assert get_defuse_dialect("apex").receiver(fn.fn_node, get_language_map("apex")) is None+ x = _extractions(fn)[0]+ symbol = em._symbol_fields(x, None)+ assert symbol["new_symbol"]["kind"] is None+ fields = em._render_fields(fn, x, get_defuse_dialect("apex"), "apex", "h", symbol, async_host=True)+ assert fields["new_symbol"]["signature_text"] is None and fields["call_site"] is None+ prop = _analyses(+ """+ public class Demo {+ public Integer total {+ get { if (cache == null) { cache = 0; } return cache; }+ }+ }+ """+ )+ assert all(not _extractions(f) for f in prop)+++_COMPACT = """+public class Demo {+ Integer f(List<Integer> xs, Integer limit) {+ Integer total = 0;+ Integer extra = 0;+ for (Integer x : xs) {+ total += x;+ }+ if (limit > 0) { extra = limit * 2;+ if (extra > 9) {+ extra = 9;+ }+ total += extra;+ total += 1; }+ return total;+ }+}+"""+++def test_apex_span_never_shares_a_line_with_a_compact_block_brace():+ # The ``if`` header opens the block on the first statement's line and the+ # closing brace sits on the last one's: lifting those lines takes them too.+ src = _COMPACT+ fn = _first(src)+ header, brace = _line(src, "if (limit > 0) {"), _line(src, "total += 1; }")+ assert all(e.start_line != header and e.end_line != brace for e in _extractions(fn))diff --git a/tests/unit/health/test_dataflow_langs.py b/tests/unit/health/test_dataflow_langs.pyindex 58985f31d..b9edb86dd 100644--- a/tests/unit/health/test_dataflow_langs.py+++ b/tests/unit/health/test_dataflow_langs.py@@ -679,6 +679,35 @@ def test_java_extract_method_fires():assert best.slice_nloc >= 6+def test_java_span_never_shares_a_line_with_a_compact_block_brace():+ # A block opened on its header's line and closed on its last statement's+ # line: a span over its statements would lift the header and the brace.+ src = """+ class Demo {+ int f(int[] xs, int limit) {+ int total = 0;+ int extra = 0;+ for (int x : xs) {+ total += x;+ }+ if (limit > 0) { extra = limit * 2;+ if (extra > 9) {+ extra = 9;+ }+ total += extra;+ total += 1; }+ return total;+ }+ }+ """+ lmap = get_language_map("java")+ lines = textwrap.dedent(src).splitlines()+ header = next(i for i, ln in enumerate(lines, 1) if "if (limit > 0) {" in ln)+ brace = next(i for i, ln in enumerate(lines, 1) if "total += 1; }" in ln)+ for e in find_extractions(_first("java", src), lmap):+ assert e.start_line != header and e.end_line != brace++def test_java_extractions_are_deterministic():lmap = get_language_map("java")fn = _first("java", _JAVA_PROCESS)