Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(health): add PHP dataflow dialect and Extract Method support (#3434) (#3466)

Rishabh Mishra744dd0795bd1
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index f3d54d2fe..3d147640d 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -228,7 +228,7 @@ This table is why a language is Full and not Good.
| Dart | ✅ | ✅ | ✅ | no | no | no | ✅ |
| Object Pascal | ✅ | n/a | ✅ | n/a | n/a | no | ✅ |
| Razor | ✅ | n/a | n/a | n/a | n/a | no | ✅ |
-| PHP | ✅ | ✅ | ✅ | no | no | no | no |
+| PHP | ✅ | ✅ | ✅ | no | no | ✅ | no |
| C | ✅ | no | no | no | no | ✅ | no |
| F#, Objective-C | ✅ | ✅ | no | no | no | no | no |
| Shell | ✅ | n/a | n/a | n/a | n/a | n/a | n/a |
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
index e02c880cc..22865f12f 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -1366,6 +1366,26 @@ _PHP = LanguageNodeMap(
"nullsafe_member_call_expression",
}
),
+ assignment_kinds=frozenset({"assignment_expression", "reference_assignment_expression"}),
+ augmented_assign_kinds=frozenset({"augmented_assignment_expression"}),
+ local_decl_kinds=frozenset({"function_static_declaration", "static_variable_declaration"}),
+ if_kinds=frozenset({"if_statement"}),
+ block_kinds=frozenset({"compound_statement"}),
+ return_kinds=frozenset({"return_statement"}),
+ raise_kinds=frozenset({"throw_expression", "throw_statement"}),
+ break_kinds=frozenset({"break_statement"}),
+ continue_kinds=frozenset({"continue_statement"}),
+ yield_kinds=frozenset(
+ {
+ "yield_expression",
+ "dynamic_variable_name",
+ "global_statement",
+ "global_declaration",
+ "function_static_declaration",
+ "reference_assignment_expression",
+ "by_ref",
+ }
+ ),
)
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py b/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py
index 03c1a1335..a83a30626 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py
@@ -488,46 +488,57 @@ class _CFGBuilder:
# then-branch
then_entry = self._new()
self._edge(cur, then_entry)
- then_out = self._process_seq(
- self._body_stmts(if_node.child_by_field_name("consequence")), then_entry
- )
+ then_block = if_node.child_by_field_name("consequence") or if_node.child_by_field_name("body")
+ then_out = self._process_seq(self._body_stmts(then_block), then_entry)
if then_out is not None:
self._edge(then_out, join)
# Two grammar families for the false arm:
- # - Python's *flat* ``elif`` chain: sibling ``elif_clause`` (and a final
- # ``else_clause``) children, all converging on one join.
+ # - Python / PHP flat chain: sibling clauses (``elif_clause`` /
+ # ``else_if_clause`` and a final ``else_clause``) children, all
+ # converging on one join.
# - everything else (a plain ``else``, or the C-family's nested
# ``else if``): a single else arm reached via the ``alternative`` field
- # or an ``else_clause`` child. ``else_clause`` is shared between Python
- # and TS, so the discriminator is specifically an ``elif_clause``.
- if any(c.type == "elif_clause" for c in if_node.children):
- alts = [c for c in if_node.children if c.type in ("elif_clause", "else_clause")]
- self._build_py_else_chain(alts, cur, join)
+ # or an ``else_clause`` child.
+ if any(c.type in ("elif_clause", "else_if_clause") for c in if_node.children):
+ alts = [
+ c
+ for c in if_node.children
+ if c.type in ("elif_clause", "else_if_clause", "else_clause")
+ ]
+ self._build_flat_else_chain(alts, cur, join)
else:
self._build_c_alternative(if_node, cur, join)
return join if join.predecessors else None
- def _build_py_else_chain(self, alts: list[Node], cur: BasicBlock, join: BasicBlock) -> None:
- """Python ``elif`` / ``else`` clause chain off *cur*'s false edge."""
+ def _build_flat_else_chain(self, alts: list[Node], cur: BasicBlock, join: BasicBlock) -> None:
+ """Flat ``elif`` / ``else_if`` / ``else`` clause chain off *cur*'s false edge."""
false_src: BasicBlock | None = cur
for alt in alts:
- if alt.type == "elif_clause":
+ if alt.type in ("elif_clause", "else_if_clause"):
elif_test = self._new("branch")
self._record_head(elif_test, alt)
self._edge(false_src, elif_test)
elif_entry = self._new()
self._edge(elif_test, elif_entry)
- elif_out = self._process_seq(
- self._body_stmts(alt.child_by_field_name("consequence")), elif_entry
+ body = (
+ alt.child_by_field_name("consequence")
+ or alt.child_by_field_name("body")
+ or self._block_of(alt)
)
+ elif_out = self._process_seq(self._body_stmts(body), elif_entry)
if elif_out is not None:
self._edge(elif_out, join)
false_src = elif_test
else: # else_clause
else_entry = self._new()
self._edge(false_src, else_entry)
- else_out = self._process_seq(self._body_stmts(self._block_of(alt)), else_entry)
+ body = (
+ alt.child_by_field_name("body")
+ or alt.child_by_field_name("consequence")
+ or self._block_of(alt)
+ )
+ else_out = self._process_seq(self._body_stmts(body), else_entry)
if else_out is not None:
self._edge(else_out, join)
false_src = None
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.py
index 8ec96915b..bd559c29c 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
@@ -18,6 +18,7 @@ from . import cpp as _cpp
from . import csharp as _csharp
from . import go as _go
from . import java as _java
+from . import php as _php
from . import python as _python
from . import rust as _rust
from . import ts_js as _ts_js
@@ -51,6 +52,7 @@ _REGISTER: tuple[tuple[str, BaseDefUseDialect], ...] = (
# A C parse tree carries no C++-only node (``for_range_loop``, lambdas,
# ``co_await``), so the C++ dialect reads it whole.
("c", _cpp.DIALECT),
+ ("php", _php.DIALECT),
)
for _tag, _dialect in _REGISTER:
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/php.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/php.py
new file mode 100644
index 000000000..5b9500113
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/php.py
@@ -0,0 +1,519 @@
+"""PHP ``DefUseDialect``.
+
+Classifies each identifier in a statement as a write (def) or a read (use).
+PHP's write sites are:
+- Plain assignment: ``$x = ...`` (``assignment_expression``)
+- Compound assignments: ``$x += ...``, ``$x ??= ...``, ``$x .= ...``
+ (``augmented_assignment_expression`` -- read-modify-write)
+- Update expressions: ``$x++`` / ``--$x`` (``update_expression`` -- read-modify-write)
+- Foreach binders: ``foreach ($xs as $k => $v)`` (both ``$k`` and ``$v`` are defs;
+ ``$xs`` is a use; ``foreach ($xs as &$v)`` is a by-reference alias)
+- Destructuring: ``list($a, $b) = ...`` / ``[$a, $b] = ...`` / ``['k' => $v] = ...``
+ (all bound targets are defs)
+- Static variables: ``static $s = 0;`` (``function_static_declaration``)
+
+Property and array targets (``$this->f = ...``, ``$a[$i] = ...``, ``$a[] = ...``)
+bind no local, so their bases stay reads. ``$this`` is the receiver, never a local
+parameter or return.
+
+Delegate-style variable calls (``$fn($x)``) treat ``$fn`` as a variable read.
+Closures capture by value (``use ($x)``) or reference (``use (&$x)``).
+By-reference names (reference assignment, ``&`` parameter, ``use (&$x)``) trigger
+span refusal when written, guaranteeing precision against aliasing.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from .base import BaseDefUseDialect, Occurrence, StatementDefUse
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
+
+ from ...complexity.languages import LanguageNodeMap
+
+# Write-site / structural node kinds
+_ASSIGN_KINDS = frozenset({"assignment_expression"})
+_REF_ASSIGN_KINDS = frozenset({"reference_assignment_expression"})
+_AUG_KINDS = frozenset({"augmented_assignment_expression"})
+_UPDATE_KINDS = frozenset({"update_expression"})
+_STATIC_DECL_KINDS = frozenset({"function_static_declaration", "static_variable_declaration"})
+_FOREACH = "foreach_statement"
+_FUNCTION_CALL = "function_call_expression"
+_MEMBER_CALL = "member_call_expression"
+_SCOPED_CALL = "scoped_call_expression"
+_NULLSAFE_MEMBER_CALL = "nullsafe_member_call_expression"
+
+# Member / property access node kinds
+_MEMBER_ACCESS = frozenset(
+ {"member_access_expression", "nullsafe_member_access_expression", "member_call_expression"}
+)
+_SUBSCRIPT_ACCESS = frozenset({"subscript_expression"})
+
+# Built-in functions that mutate an argument in-place by reference
+_BYREF_INOUT_BUILTINS = frozenset(
+ {
+ "sort",
+ "rsort",
+ "asort",
+ "arsort",
+ "ksort",
+ "krsort",
+ "usort",
+ "uasort",
+ "uksort",
+ "natsort",
+ "natcasesort",
+ "shuffle",
+ "array_push",
+ "array_pop",
+ "array_shift",
+ "array_unshift",
+ "array_splice",
+ "reset",
+ "end",
+ "next",
+ "prev",
+ }
+)
+_BYREF_OUT_BUILTINS = frozenset({"preg_match", "preg_match_all"})
+
+# Nested scopes whose identifiers belong to a different function
+_SCOPE_BOUNDARIES = frozenset(
+ {
+ "anonymous_function",
+ "arrow_function",
+ "class_declaration",
+ "interface_declaration",
+ "trait_declaration",
+ "enum_declaration",
+ "anonymous_class",
+ }
+)
+
+
+class PhpDefUseDialect(BaseDefUseDialect):
+ language = "php"
+ member_access_kinds = frozenset(
+ {
+ "member_access_expression",
+ "nullsafe_member_access_expression",
+ "member_call_expression",
+ "nullsafe_member_call_expression",
+ }
+ )
+ keyword_kinds = frozenset()
+ identifier_kinds = frozenset({"variable_name"})
+
+ def _is_scope_boundary(self, node: Node) -> bool:
+ return node.type in _SCOPE_BOUNDARIES
+
+ def _occ(self, node: Node) -> Occurrence:
+ raw = (node.text or b"").decode("utf-8", "replace")
+ name = raw[1:] if raw.startswith("$") else raw
+ return Occurrence(
+ name=name,
+ line=node.start_point[0] + 1,
+ column=node.start_point[1],
+ )
+
+ def _is_this(self, node: Node | None) -> bool:
+ return node is not None and (node.text or b"") == b"$this"
+
+ def collect_reads(self, node: Node | None, out: list[Occurrence]) -> None:
+ """Collect variable reads under *node*."""
+ if node is None:
+ return
+ t = node.type
+ if t in self.identifier_kinds:
+ if not self._is_this(node):
+ out.append(self._occ(node))
+ return
+ if t in self.member_access_kinds:
+ # $obj->prop or $obj->method(): receiver is a variable read
+ receiver = node.child_by_field_name("object") or (
+ node.named_children[0] if node.named_children else None
+ )
+ if receiver is not None and not self._is_this(receiver):
+ self.collect_reads(receiver, out)
+ if t in (_MEMBER_CALL, _NULLSAFE_MEMBER_CALL):
+ args = node.child_by_field_name("arguments") or (
+ node.named_children[-1] if len(node.named_children) > 1 else None
+ )
+ if args is not None:
+ self.collect_reads(args, out)
+ return
+ if t in _SCOPED_CALL:
+ # Foo::bar($x): Foo and bar are class/method names, not local variables
+ args = node.child_by_field_name("arguments") or (
+ node.named_children[-1] if node.named_children else None
+ )
+ if args is not None:
+ self.collect_reads(args, out)
+ return
+ if t == _FUNCTION_CALL:
+ fn = node.child_by_field_name("function") or (
+ node.named_children[0] if node.named_children else None
+ )
+ # Delegate-style call: $fn($x) - function is a variable_name!
+ if fn is not None and fn.type in self.identifier_kinds:
+ self.collect_reads(fn, out)
+ args = node.child_by_field_name("arguments") or (
+ node.named_children[-1] if len(node.named_children) > 1 else None
+ )
+ if args is not None:
+ self.collect_reads(args, out)
+ return
+ if t == "anonymous_function":
+ # use ($x, &$y) clause
+ self._collect_use_clause_reads(node, out)
+ return
+ if self._is_scope_boundary(node):
+ return
+ for child in node.named_children:
+ self.collect_reads(child, out)
+
+ def _collect_use_clause_reads(self, fn_node: Node, out: list[Occurrence]) -> None:
+ """Collect captured reads from anonymous_function_use_clause."""
+ for c in fn_node.children:
+ if c.type == "anonymous_function_use_clause":
+ for child in c.named_children:
+ if child.type == "by_ref":
+ var = (
+ child.child_by_field_name("variable")
+ or (child.named_children[0] if child.named_children else None)
+ )
+ if var is not None and var.type in self.identifier_kinds and not self._is_this(var):
+ out.append(self._occ(var))
+ elif child.type in self.identifier_kinds and not self._is_this(child):
+ out.append(self._occ(child))
+ break
+
+ # -- public contract ------------------------------------------------------
+
+ def statement_def_use(
+ self, node: Node, lmap: LanguageNodeMap, *, head_only: bool
+ ) -> StatementDefUse:
+ defs: list[Occurrence] = []
+ uses: list[Occurrence] = []
+ if head_only:
+ self._head(node, lmap, defs, uses)
+ else:
+ self._process(node, defs, uses)
+ if node.type in lmap.return_kinds:
+ for p in self._byref_param_names(node):
+ uses.append(Occurrence(name=p, line=node.start_point[0] + 1))
+ return StatementDefUse(defs=tuple(defs), uses=tuple(uses))
+
+ def _byref_param_names(self, node: Node) -> set[str]:
+ cur: Node | None = node
+ while cur is not None and cur.type not in ("function_definition", "method_declaration"):
+ cur = cur.parent
+ if cur is None:
+ return set()
+ params = cur.child_by_field_name("parameters")
+ if params is None:
+ return set()
+ byref: set[str] = set()
+ for p in params.named_children:
+ if any(c.type == "reference_modifier" for c in p.children):
+ name_node = self._binder_identifier(p)
+ if name_node is not None:
+ raw = (name_node.text or b"").decode("utf-8", "replace")
+ byref.add(raw[1:] if raw.startswith("$") else raw)
+ return byref
+
+ def _closure_bound_names(self, node: Node) -> set[str]:
+ """Names a nested scope binds as its own parameters."""
+ bound = {occ.name for occ in self.parameter_defs(node)}
+ stack = [node.child_by_field_name("parameters"), node.child_by_field_name("parameter")]
+ while stack:
+ cur = stack.pop()
+ if cur is None:
+ continue
+ if cur.type in self.identifier_kinds and cur.text:
+ raw = cur.text.decode("utf-8", "replace")
+ bound.add(raw[1:] if raw.startswith("$") else raw)
+ stack.extend(cur.named_children)
+ return bound
+
+ def parameter_defs(self, fn_node: Node) -> tuple[Occurrence, ...]:
+ """Names bound by the signature."""
+ params_node = fn_node.child_by_field_name("parameters")
+ if params_node is None:
+ return ()
+ out: list[Occurrence] = []
+ for child in params_node.named_children:
+ name_node = self._binder_identifier(child)
+ if name_node is not None and not self._is_this(name_node):
+ out.append(self._occ(name_node))
+ return tuple(out)
+
+ def _binder_identifier(self, node: Node) -> Node | None:
+ if node.type in self.identifier_kinds:
+ return node
+ name_node = node.child_by_field_name("name")
+ if name_node is not None and name_node.type in self.identifier_kinds:
+ return name_node
+ for child in node.children:
+ if child.type in self.identifier_kinds:
+ return child
+ if child.is_named:
+ sub = self._binder_identifier(child)
+ if sub is not None:
+ return sub
+ return None
+
+ # -- head (loop clause / if condition) ------------------------------------
+
+ def _head(
+ self, node: Node, lmap: LanguageNodeMap, defs: list[Occurrence], uses: list[Occurrence]
+ ) -> None:
+ t = node.type
+ if t == _FOREACH:
+ self._foreach_head(node, defs, uses)
+ elif t in lmap.loop_kinds:
+ # for / while / do
+ for c in node.named_children:
+ if c.type != "compound_statement":
+ self._process(c, defs, uses)
+ elif t in lmap.branch_kinds:
+ # if / else_if
+ for c in node.named_children:
+ if c.type != "compound_statement" and c.type != "else_clause":
+ self.collect_reads(c, uses)
+ else:
+ self._process(node, defs, uses)
+
+ def _foreach_head(self, node: Node, defs: list[Occurrence], uses: list[Occurrence]) -> None:
+ """Handle foreach ($xs as $k => $v) / foreach ($xs as &$v)."""
+ seen_as = False
+ for c in node.children:
+ if c.type == "as":
+ seen_as = True
+ continue
+ if c.type == "(" or c.type == ")" or c.type == "compound_statement" or c.type == "colon":
+ continue
+ if not seen_as:
+ # Expression being iterated
+ if c.is_named:
+ self.collect_reads(c, uses)
+ else:
+ # Binder side
+ if c.is_named:
+ self._foreach_binder(c, defs, uses)
+
+ def _foreach_binder(self, node: Node, defs: list[Occurrence], uses: list[Occurrence]) -> None:
+ if node.type == "pair":
+ # $k => $v
+ children = [c for c in node.named_children]
+ if len(children) >= 2:
+ key, val = children[0], children[1]
+ self._targets(key, defs, uses)
+ self._foreach_binder(val, defs, uses)
+ return
+ if node.type == "by_ref":
+ # &$v: read-modify-write alias of array
+ inner = node.child_by_field_name("variable") or (
+ node.named_children[0] if node.named_children else None
+ )
+ if inner is not None:
+ self._targets(inner, defs, uses)
+ self.collect_reads(inner, uses)
+ # By-reference aliasing: refuse span
+ defs.append(Occurrence(name="__byref_alias__", line=inner.start_point[0] + 1))
+ return
+ self._targets(node, defs, uses)
+
+ # -- statement / expression processing ------------------------------------
+
+ def _process(self, node: Node | None, defs: list[Occurrence], uses: list[Occurrence]) -> None:
+ if node is None:
+ return
+ t = node.type
+ if t in _ASSIGN_KINDS:
+ left = node.child_by_field_name("left")
+ right = node.child_by_field_name("right")
+ self._targets(left, defs, uses)
+ self._process(right, defs, uses)
+ return
+ if t in _REF_ASSIGN_KINDS:
+ # $a = &$b: reference assignment
+ left = node.child_by_field_name("left")
+ right = node.child_by_field_name("right")
+ self._targets(left, defs, uses)
+ if right is not None:
+ self._targets(right, defs, uses)
+ self.collect_reads(right, uses)
+ # Reference assignment aliases both names
+ defs.append(Occurrence(name="__byref_alias__", line=node.start_point[0] + 1))
+ return
+ if t in _AUG_KINDS:
+ # $x += 1, $x .= "a", $x ??= 2: read-modify-write
+ left = node.child_by_field_name("left")
+ right = node.child_by_field_name("right")
+ self._targets(left, defs, uses)
+ self.collect_reads(left, uses)
+ self._process(right, defs, uses)
+ return
+ if t in _UPDATE_KINDS:
+ # $x++ / --$x: read-modify-write
+ has_update = any(
+ c.type in ("++", "--") or c.text in (b"++", b"--") for c in node.children
+ )
+ if has_update:
+ arg = node.child_by_field_name("argument") or (
+ node.named_children[0] if node.named_children else None
+ )
+ if arg is not None:
+ self._targets(arg, defs, uses)
+ self.collect_reads(arg, uses)
+ return
+ if t in _STATIC_DECL_KINDS:
+ # static $s = 0;
+ for child in node.named_children:
+ if child.type == "static_variable_declaration":
+ name = child.child_by_field_name("name") or (
+ child.named_children[0] if child.named_children else None
+ )
+ self._targets(name, defs, uses)
+ val = child.child_by_field_name("value") or (
+ child.named_children[1] if len(child.named_children) > 1 else None
+ )
+ self._process(val, defs, uses)
+ else:
+ self._process(child, defs, uses)
+ return
+ if t == _FOREACH:
+ self._foreach_head(node, defs, uses)
+ body = node.child_by_field_name("body")
+ if body is not None:
+ self._process(body, defs, uses)
+ return
+ if t == _FUNCTION_CALL:
+ fn = node.child_by_field_name("function") or (
+ node.named_children[0] if node.named_children else None
+ )
+ # Calling compact() or extract() makes scope unmodelled
+ fn_text = (fn.text or b"").decode("utf-8", "replace") if fn else ""
+ if fn_text in ("compact", "extract"):
+ defs.append(Occurrence(name="__byref_alias__", line=node.start_point[0] + 1))
+ # Delegate call
+ if fn is not None and fn.type in self.identifier_kinds:
+ self.collect_reads(fn, uses)
+ args = node.child_by_field_name("arguments") or (
+ node.named_children[-1] if len(node.named_children) > 1 else None
+ )
+ if args is not None:
+ if fn_text in _BYREF_INOUT_BUILTINS:
+ self._process_byref_inout_call(args, defs, uses)
+ elif fn_text in _BYREF_OUT_BUILTINS:
+ self._process_byref_out_call(args, defs, uses)
+ else:
+ self._process(args, defs, uses)
+ return
+ if t in self.member_access_kinds:
+ receiver = node.child_by_field_name("object") or (
+ node.named_children[0] if node.named_children else None
+ )
+ if receiver is not None and not self._is_this(receiver):
+ self.collect_reads(receiver, uses)
+ if t in (_MEMBER_CALL, _NULLSAFE_MEMBER_CALL):
+ args = node.child_by_field_name("arguments") or (
+ node.named_children[-1] if len(node.named_children) > 1 else None
+ )
+ if args is not None:
+ self._process(args, defs, uses)
+ return
+ if t in self.identifier_kinds:
+ if not self._is_this(node):
+ uses.append(self._occ(node))
+ return
+ if t == "anonymous_function":
+ self._collect_use_clause_reads(node, uses)
+ return
+ if self._is_scope_boundary(node):
+ return
+ for child in node.named_children:
+ self._process(child, defs, uses)
+
+ # -- write-target extraction ----------------------------------------------
+
+ def _targets(self, node: Node | None, defs: list[Occurrence], uses: list[Occurrence]) -> None:
+ if node is None:
+ return
+ t = node.type
+ if t in self.identifier_kinds:
+ if not self._is_this(node):
+ defs.append(self._occ(node))
+ return
+ if t in _MEMBER_ACCESS:
+ # $this->f = ... or $obj->f = ... binds no local; receiver is a read
+ self.collect_reads(node, uses)
+ return
+ if t in _SUBSCRIPT_ACCESS:
+ # PHP arrays are values: $out[] = ... or $out['k'] = ... mutates the local array.
+ root = node
+ while root is not None and root.type in _SUBSCRIPT_ACCESS:
+ root = root.named_children[0] if root.named_children else None
+ if root is not None and root.type in self.identifier_kinds and not self._is_this(root):
+ defs.append(self._occ(root))
+ self.collect_reads(node, uses)
+ return
+ if t == "list_literal" or t == "array_creation_expression":
+ # list($a, $b) = ... or [$a, $b] = ... or ['k' => $v] = ...
+ for child in node.named_children:
+ if child.type == "pair":
+ # ['k' => $v]
+ val = child.named_children[-1] if child.named_children else None
+ self._targets(val, defs, uses)
+ elif child.type == "array_element_initializer":
+ for sub in child.named_children:
+ self._targets(sub, defs, uses)
+ else:
+ self._targets(child, defs, uses)
+ return
+ if t == "by_ref":
+ var = node.child_by_field_name("variable") or (
+ node.named_children[0] if node.named_children else None
+ )
+ if var is not None:
+ self._targets(var, defs, uses)
+ self.collect_reads(var, uses)
+ defs.append(Occurrence(name="__byref_alias__", line=node.start_point[0] + 1))
+ return
+ for child in node.named_children:
+ self._targets(child, defs, uses)
+
+ def _arg_nodes(self, args_node: Node) -> list[Node]:
+ return [c for c in args_node.named_children if c.type == "argument" or c.is_named]
+
+ def _process_byref_inout_call(
+ self, args_node: Node, defs: list[Occurrence], uses: list[Occurrence]
+ ) -> None:
+ """First argument is modified in-place (def + read). Remaining arguments are reads."""
+ arg_list = self._arg_nodes(args_node)
+ if not arg_list:
+ return
+ arg0 = arg_list[0]
+ expr0 = arg0.named_children[0] if arg0.type == "argument" and arg0.named_children else arg0
+ self._targets(expr0, defs, uses)
+ self.collect_reads(expr0, uses)
+ for a in arg_list[1:]:
+ self._process(a, defs, uses)
+
+ def _process_byref_out_call(
+ self, args_node: Node, defs: list[Occurrence], uses: list[Occurrence]
+ ) -> None:
+ """Third argument (index 2) is written to (def). Other arguments are reads."""
+ arg_list = self._arg_nodes(args_node)
+ for idx, a in enumerate(arg_list):
+ if idx == 2:
+ expr = a.named_children[0] if a.type == "argument" and a.named_children else a
+ self._targets(expr, defs, uses)
+ else:
+ self._process(a, defs, uses)
+
+
+DIALECT = PhpDefUseDialect()
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
index 2800290dd..9700534d3 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
@@ -409,6 +409,12 @@ class _FunctionSlicer:
s, e = span.start, span.end
if any(import_line < s <= use_line <= e for import_line, use_line in self.import_reads):
return None
+ byref_alias_lines = self.def_lines.get("__byref_alias__")
+ if byref_alias_lines:
+ b_lo = bisect_left(byref_alias_lines, s)
+ b_hi = bisect_right(byref_alias_lines, e)
+ if b_lo < b_hi:
+ return None
if self.reads is None:
self.reads = _reads_observing(self.analysis, self.def_lines)
params, returns = _infer_in_out(
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice_nodes.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice_nodes.py
index 56b510046..7e9635a6e 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice_nodes.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice_nodes.py
@@ -112,6 +112,11 @@ def _identifiers(node: Node) -> set[str]:
text = cur.text
if text:
out.add(text.decode("utf-8", "replace"))
+ elif not cur.children and cur.type == "name":
+ text = cur.text
+ if text:
+ s = text.decode("utf-8", "replace")
+ out.add(s[1:] if s.startswith("$") else s)
stack.extend(cur.children)
return out
diff --git a/tests/unit/health/test_dataflow_langs.py b/tests/unit/health/test_dataflow_langs.py
index 6b2c87474..bb8ab4119 100644
--- a/tests/unit/health/test_dataflow_langs.py
+++ b/tests/unit/health/test_dataflow_langs.py
@@ -1824,6 +1824,462 @@ def test_c_extraction_never_spans_a_goto_label():
assert not (e.start_line <= label_line <= e.end_line)
+# == PHP =========================================================================
+
+# Every PHP write shape in one function: plain assignment, compound assign,
+# update (++/--), static declaration, foreach binders (key => value), list
+# and array destructuring -- plus the target shapes that bind NO local (properties,
+# array elements, method calls, static member calls).
+_PHP_SHAPES = """<?php
+function processShapes(array $input, int $base, $cfg) {
+ $acc = $base;
+ $a = 1;
+ $b = 2;
+ $errors = 0;
+ $errors += 1;
+ $errors .= "suffix";
+ $val ??= 2;
+ $acc++;
+ --$acc;
+ static $cache = 0;
+ foreach ($input as $k => $item) {
+ $acc += $item;
+ }
+ list($x, $y) = [$a, $b];
+ [$u, $v] = [$x, $y];
+ ["key" => $z] = ["key" => $u];
+ $cfg->count = $acc;
+ $obj->field = $acc;
+ $arr[$a] = $b;
+ $lam = function($elem) use ($base) { return $elem + $base; };
+ return $acc;
+}
+"""
+
+
+def test_php_def_use_classification():
+ fn = _first("php", _PHP_SHAPES)
+ defs = _def_names(fn)
+ assert {"input", "base", "cfg"} <= defs # parameters seeded as entry defs
+ assert {
+ "acc",
+ "a",
+ "b",
+ "errors",
+ "val",
+ "cache",
+ "k",
+ "item",
+ "x",
+ "y",
+ "u",
+ "v",
+ "z",
+ "lam",
+ } <= defs
+ assert "count" not in defs
+ assert "field" not in defs
+
+ uses = _use_names(fn)
+ assert {"base", "acc", "input", "a", "b", "cfg", "obj", "arr", "item", "x", "y", "u"} <= uses
+ assert "array" not in uses
+ assert "processShapes" not in uses
+
+
+def test_php_reads_a_member_callee_receiver_but_not_the_method():
+ fn = _first(
+ "php",
+ """<?php
+ function run($db, $id) {
+ $n = 0;
+ $n += $db->execute($id);
+ $n += helper($id);
+ return $n;
+ }
+ """,
+ )
+ uses = _use_names(fn)
+ assert "db" in uses # the receiver is a real read
+ assert "execute" not in uses # the method name is not a variable
+ assert "helper" not in uses # global function name is not a variable read
+
+
+def test_php_reads_member_call_and_nullsafe_call_arguments_without_method_names():
+ fn = _first(
+ "php",
+ """<?php
+ function run($db, $id, $item) {
+ $n = 0;
+ $n += $db->execute($id);
+ $n += $db?->executeOther($item);
+ return $n;
+ }
+ """,
+ )
+ uses = _use_names(fn)
+ assert "db" in uses
+ assert "id" in uses
+ assert "item" in uses
+ assert "execute" not in uses
+ assert "executeOther" not in uses
+
+
+
+def test_php_delegate_call_is_a_variable_read():
+ fn = _first(
+ "php",
+ """<?php
+ function executeDelegate($fn, $arg) {
+ $n = 0;
+ $n += $fn($arg);
+ return $n;
+ }
+ """,
+ )
+ uses = _use_names(fn)
+ assert "fn" in uses # delegate variable is a read
+ assert "arg" in uses
+
+
+def test_php_lambda_body_is_a_separate_scope():
+ fn = _first(
+ "php",
+ """<?php
+ function run($items, $base) {
+ $total = $base;
+ $lam = function($x) use ($total) {
+ $inner = $x * 2;
+ return $inner + $total;
+ };
+ return $total;
+ }
+ """,
+ )
+ defs = _def_names(fn)
+ assert "inner" not in defs # scoped inside the closure
+ assert "x" not in defs # closure parameter
+ captured = {u.name for u in fn.def_use.captured.reads}
+ assert "total" in captured
+ assert "x" not in captured
+
+
+def test_php_extract_method_fires():
+ fn = _first(
+ "php",
+ """<?php
+ function process($records, $threshold) {
+ $results = [];
+ $errors = 0;
+ foreach ($records as $r) {
+ if ($r === null) {
+ $errors += 1;
+ continue;
+ }
+ $results[] = $r;
+ }
+ $total = 0;
+ $count = 0;
+ foreach ($results as $v) {
+ if ($v > $threshold) {
+ $total += $v;
+ $count += 1;
+ } else {
+ $total -= $v;
+ }
+ }
+ $average = $count ? $total / $count : 0;
+ return $average;
+ }
+ """,
+ )
+ lmap = get_language_map("php")
+ assert lmap is not None
+ extractions = find_extractions(fn, lmap)
+ assert extractions
+ best = extractions[0]
+ assert "average" in best.returns
+ assert "results" in best.params
+ assert "threshold" in best.params
+ assert len(best.returns) <= 1
+ assert best.ccn_removed >= 1
+ assert best.slice_nloc >= 6
+ # Deterministic ordering: re-running yields identical candidates
+ assert [(e.start_line, e.end_line) for e in find_extractions(fn, lmap)] == [
+ (e.start_line, e.end_line) for e in extractions
+ ]
+
+
+def test_php_flagged_only_gate_skips_small_functions():
+ _require("php")
+ src = b"""<?php
+ function small($a, $b) {
+ if ($a > $b) {
+ return $a;
+ }
+ return $b;
+ }
+ """
+ res = analyze_file("small.php", "php", src, flagged_only=True)
+ assert res.stats.functions_seen == 1
+ assert len(res.functions) == 0 # not flagged (low complexity)
+
+
+ "stmt",
+ [
+ "yield $v;",
+ "$$v = 1;",
+ "global $cfg;",
+ "static $s = 0;",
+ "$alias = &$total;",
+ ],
+)
+def test_php_spans_holding_disallowed_constructs_are_refused(stmt: str):
+ code = f"""<?php
+ function process($records, $threshold) {{
+ $results = [];
+ $errors = 0;
+ foreach ($records as $r) {{
+ if ($r === null) {{
+ $errors += 1;
+ continue;
+ }}
+ $results[] = $r;
+ }}
+ $total = 0;
+ $count = 0;
+ {stmt}
+ foreach ($results as $v) {{
+ if ($v > $threshold) {{
+ $total += $v;
+ $count += 1;
+ }} else {{
+ $total -= $v;
+ }}
+ }}
+ $average = $count ? $total / $count : 0;
+ return $average;
+ }}
+ """
+ fn = _first("php", code)
+ lmap = get_language_map("php")
+ assert lmap is not None
+ spans = find_extractions(fn, lmap)
+ # The statement at line 14 should not be included in any offered extraction span
+ assert not any(e.start_line <= 14 <= e.end_line for e in spans)
+
+
+def test_php_byref_parameter_mutation_refuses_when_returning_another():
+ code_byref = """<?php
+ function process(array &$out, $records, $threshold) {
+ $results = [];
+ $errors = 0;
+ foreach ($records as $r) {
+ if ($r === null) {
+ $errors += 1;
+ continue;
+ }
+ $results[] = $r;
+ }
+ $total = 0;
+ $count = 0;
+ foreach ($results as $v) {
+ if ($v > $threshold) {
+ $total += $v;
+ $count += 1;
+ $out = [$v];
+ } else {
+ $total -= $v;
+ }
+ }
+ $average = $count ? $total / $count : 0;
+ return $average;
+ }
+ """
+ code_byval = code_byref.replace("&$out", "$out")
+ lmap = get_language_map("php")
+ assert lmap is not None
+
+ fn_byval = _first("php", code_byval)
+ assert len(find_extractions(fn_byval, lmap)) > 0
+
+ fn_byref = _first("php", code_byref)
+ assert len(find_extractions(fn_byref, lmap)) == 0
+
+
+def test_php_byref_foreach_is_refused():
+ code = """<?php
+ function process($records, $threshold) {
+ $results = [];
+ $errors = 0;
+ foreach ($records as $r) {
+ if ($r === null) {
+ $errors += 1;
+ continue;
+ }
+ $results[] = $r;
+ }
+ $total = 0;
+ $count = 0;
+ foreach ($results as &$v) {
+ if ($v > $threshold) {
+ $total += $v;
+ $count += 1;
+ } else {
+ $total -= $v;
+ }
+ }
+ $average = $count ? $total / $count : 0;
+ return $average;
+ }
+ """
+ fn = _first("php", code)
+ lmap = get_language_map("php")
+ assert lmap is not None
+ # By-reference foreach makes the loop disqualified from extraction
+ assert len(find_extractions(fn, lmap)) == 0
+
+
+def test_php_subscript_writes_are_defs():
+ code = """<?php
+ function f($items, $limit) {
+ $out = [];
+ $n = count($items);
+ if ($n > $limit) {
+ $out[] = $items[0];
+ $n = $n - 1;
+ }
+ $total = $n + 1;
+ echo $total;
+ return $out;
+ }
+ """
+ fn = _first("php", code)
+ lmap = get_language_map("php")
+ assert lmap is not None
+ spans = find_extractions(fn, lmap)
+ # No offered span passes $out in without returning it
+ assert not any(
+ e.start_line <= 6 <= e.end_line and "out" in e.params and "out" not in e.returns
+ for e in spans
+ )
+ # Span 4-8 defines both $n and $out with both live-out -> multiple returns -> refused
+ assert not any(e.start_line == 4 and e.end_line == 8 for e in spans)
+
+
+def test_php_byref_builtins_mutate_arguments():
+ # sort($out) modifies $out in-place
+ code_sort = """<?php
+ function g($items, $limit) {
+ $out = [];
+ $n = count($items);
+ if ($n > $limit) {
+ sort($out);
+ $n = $n - 1;
+ }
+ $total = $n + 1;
+ echo $total;
+ return $out;
+ }
+ """
+ fn_sort = _first("php", code_sort)
+ lmap = get_language_map("php")
+ assert lmap is not None
+ spans = find_extractions(fn_sort, lmap)
+ assert not any(
+ e.start_line <= 6 <= e.end_line and "out" in e.params and "out" not in e.returns
+ for e in spans
+ )
+ assert not any(e.start_line == 4 and e.end_line == 8 for e in spans)
+
+ # preg_match writes the matches array (arg 2)
+ code_preg = """<?php
+ function h($re, $s) {
+ $m = [];
+ if (strlen($s) > 0) {
+ preg_match($re, $s, $m);
+ }
+ return $m;
+ }
+ """
+ fn_preg = _first("php", code_preg)
+ assert "m" in _def_names(fn_preg)
+
+
+def test_php_elseif_chain_cfg_and_defs():
+ code = """<?php
+ function test_branches($a, $b, $c) {
+ if ($a) {
+ $m = 1;
+ } elseif ($b) {
+ $m = 2;
+ } elseif ($c) {
+ $m = 3;
+ } else {
+ $m = 4;
+ }
+ return $m;
+ }
+ """
+ fn = _first("php", code)
+ defs = [(d.var, d.line) for d in fn.def_use.definitions]
+ # Defs from all arms (line 4, 6, 8, 10) must reach the CFG
+ m_lines = {line for var, line in defs if var == "m"}
+ assert m_lines == {4, 6, 8, 10}
+
+
[email protected]("fn_name", ["compact", "extract"])
+def test_php_compact_and_extract_refuse_spans(fn_name: str):
+ code = f"""<?php
+ function process($records, $threshold) {{
+ $results = [];
+ $errors = 0;
+ foreach ($records as $r) {{
+ if ($r === null) {{
+ $errors += 1;
+ continue;
+ }}
+ $results[] = $r;
+ }}
+ $total = 0;
+ $count = 0;
+ {fn_name}($records);
+ foreach ($results as $v) {{
+ if ($v > $threshold) {{
+ $total += $v;
+ $count += 1;
+ }} else {{
+ $total -= $v;
+ }}
+ }}
+ $average = $count ? $total / $count : 0;
+ return $average;
+ }}
+ """
+ fn = _first("php", code)
+ lmap = get_language_map("php")
+ assert lmap is not None
+ spans = find_extractions(fn, lmap)
+ assert not any(e.start_line <= 14 <= e.end_line for e in spans)
+
+
+def test_identifiers_preserves_dollar_in_ts_js():
+ from tree_sitter import Parser
+
+ from repowise.core.analysis.health.dataflow.slice import _identifiers
+ from repowise.core.ingestion.parser import _get_language
+
+ parser_ts = Parser(_get_language("typescript"))
+ tree_ts = parser_ts.parse(b"let $items = 1;")
+ names_ts = _identifiers(tree_ts.root_node)
+ assert "$items" in names_ts
+
+ parser_php = Parser(_get_language("php"))
+ tree_php = parser_php.parse(b"<?php $items = 1;")
+ names_php = _identifiers(tree_php.root_node)
+ assert "items" in names_php and "$items" not in names_php
+
+
# ---------------------------------------------------------------------------
# Nested scopes that bind a name in the enclosing scope (and the ones that do not)
# ---------------------------------------------------------------------------
@@ -2406,6 +2862,18 @@ def test_ts_closure_parameter_is_not_a_read_of_the_outer_name():
{"total", "k", "rows"},
{"v", "w"},
),
+ (
+ "php",
+ """<?php
+ function f($rows, $k) {
+ $total = 1;
+ $fn = function($v) use ($total, $k) { return $v + $total + $k; };
+ return array_map($fn, $rows);
+ }
+ """,
+ {"total", "k"},
+ {"v"},
+ ),
],
)
def test_closure_reads_are_captured_per_language(language, src, captured, not_captured):