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): dataflow def/use dialects for Java and Rust (#686)

Raghav Chamadiyae975699ca74e
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.md
index c18f45279..5ffe91fe7 100644
--- a/docs/LANGUAGE_SUPPORT.md
+++ b/docs/LANGUAGE_SUPPORT.md
@@ -515,14 +515,17 @@ dialect emits no Extract Method suggestions. Coverage rolls out in value order
| Python | Y | Y | assignment, augmented, walrus, tuple-unpack, `for` / `with`-as / comprehension targets |
| Go | Y | Y | `:=` / `var`, `=` vs `+=` (operator-sniffed), `x++`, `range` binders, selector / index targets; method `receiver` seeded as a param |
| TypeScript / JavaScript | Y | Y | `let` / `const` / `var`, `=` / `+=`, `++`, array / object destructuring, `for...of` / `for...in` binders, member / subscript targets |
-| Java / Rust | --- | --- | next (high-yield tail) |
+| Java | Y | Y | declarations (multi-declarator), `=` vs `+=` (operator-sniffed), `x++`, enhanced-`for` binders, try-with-resources bindings, field / array targets; `switch`-arm writes are conservative may-defs |
+| Rust | Y | Y | `let` with destructuring patterns (tuple / slice / struct / ref), `=` vs `+=` (distinct node kinds), `for` / `if let` / `while let` binders, field / index / deref targets, `self` receiver seeded as a param; `?` counts as an early exit (no span containing one is offered); `match`-arm writes are conservative may-defs; a block's tail expression is never extracted over |
| Kotlin / C++ / C# | --- | --- | later |
Validated on real code (flagged-only, the production path): Go fires on
`gorilla/mux` (e.g. `setMatch` sheds ccn 15); TS/JS fires across the hosted
-Next.js frontend. The flagged-only gate held in both runs (Go 8 / 108
-functions, TS 212 / 1172), keeping the per-file cost in the low single-digit
-milliseconds.
+Next.js frontend; Java fires on `google/gson` (e.g. `JsonTreeReader.getPath`
+sheds ccn 7); Rust fires on `sharkdp/fd` (e.g. `FormatTemplate::parse` sheds
+ccn 6). The flagged-only gate held in every run (Go 8 / 108 functions,
+TS 212 / 1172, Java 53 / 1082, Rust 8 / 217), keeping the per-file cost in the
+low single-digit milliseconds.
#### Performance-signal coverage
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 93220b904..b323bc79e 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -186,6 +186,17 @@ class LanguageNodeMap:
raise_kinds: frozenset[str] = frozenset()
break_kinds: frozenset[str] = frozenset()
continue_kinds: frozenset[str] = frozenset()
+ # * ``statement_wrapper_kinds`` -- statement node(s) that merely wrap the
+ # node the CFG builder should classify, as their last named child.
+ # Expression-oriented grammars need this: tree-sitter-rust parses every
+ # statement-position control-flow expression (``for`` / ``if`` /
+ # ``return`` / ``break``) inside an ``expression_statement``, so without
+ # unwrapping the builder would see one opaque statement and produce a
+ # straight-line CFG. A nonempty set is therefore also the slicer's
+ # expression-oriented-language marker: it then refuses spans ending on a
+ # block's tail expression (the implicit value an extraction would
+ # silently drop), so only truly expression-oriented grammars may map it.
+ statement_wrapper_kinds: frozenset[str] = frozenset()
_PY = LanguageNodeMap(
@@ -334,6 +345,19 @@ _JAVA = LanguageNodeMap(
# The perf pass needs both forms: ``repo.find()`` (method_invocation) and
# ``new FileInputStream()`` (object_creation_expression).
call_kinds=frozenset({"method_invocation", "object_creation_expression"}),
+ # ``x = ...`` and ``x += ...`` are both ``assignment_expression`` (the
+ # dialect tells them apart by the operator token, as in Go), so the
+ # augmented set stays empty. ``int x = 1, y = 2;`` is a
+ # ``local_variable_declaration`` nesting one ``variable_declarator`` per
+ # bound name.
+ 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"}),
)
_RUST = LanguageNodeMap(
@@ -365,6 +389,28 @@ _RUST = LanguageNodeMap(
# ``function_modifiers`` child — so ``async_function_kinds`` stays empty and
# ``RustPerfDialect.is_async_fn`` sniffs the modifier instead.
call_kinds=frozenset({"call_expression"}),
+ # ``x = ...`` is an ``assignment_expression``; ``x += ...`` a dedicated
+ # ``compound_assignment_expr``. ``let`` (with any pattern) is the fresh-
+ # binding form. ``if_let_expression`` / ``while_let_expression`` only exist
+ # in older tree-sitter-rust grammars (current ones parse ``if let`` as an
+ # ``if_expression`` with a ``let_condition``); listing them is harmless.
+ assignment_kinds=frozenset({"assignment_expression"}),
+ augmented_assign_kinds=frozenset({"compound_assignment_expr"}),
+ local_decl_kinds=frozenset({"let_declaration"}),
+ if_kinds=frozenset({"if_expression", "if_let_expression"}),
+ block_kinds=frozenset({"block"}),
+ return_kinds=frozenset({"return_expression"}),
+ # ``?`` (``try_expression``) propagates an error out of the function -- an
+ # early exit the CFG treats as a terminator and the Extract Method slicer
+ # treats as a jump, so no span containing one is ever offered.
+ raise_kinds=frozenset({"try_expression"}),
+ break_kinds=frozenset({"break_expression"}),
+ continue_kinds=frozenset({"continue_expression"}),
+ # Rust parses every statement-position control-flow expression inside an
+ # ``expression_statement``; the CFG builder unwraps it to classify the real
+ # node, and the slicer uses this as the expression-oriented marker for
+ # tail-expression suppression.
+ statement_wrapper_kinds=frozenset({"expression_statement"}),
)
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 f8905cf7f..8dcdf7194 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py
@@ -284,6 +284,10 @@ class _CFGBuilder:
"""
assert self.exit_block is not None
for st in stmts:
+ # Expression-oriented grammars (Rust) wrap statement-position
+ # control flow in a carrier node; classify the real statement.
+ if st.type in self.lmap.statement_wrapper_kinds and st.named_child_count:
+ st = st.named_children[-1]
if cur is None:
# Statements after a terminator: dead code with no predecessor.
# Captured in an ``unreachable`` block so the statement is not
@@ -342,9 +346,7 @@ class _CFGBuilder:
self._build_c_alternative(if_node, cur, join)
return join
- def _build_py_else_chain(
- self, alts: list[Node], cur: BasicBlock, join: BasicBlock
- ) -> 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."""
false_src: BasicBlock | None = cur
for alt in alts:
@@ -421,6 +423,11 @@ class _CFGBuilder:
return after
def _build_try(self, try_node: Node, cur: BasicBlock) -> BasicBlock:
+ # try-with-resources (Java) binds locals in its resource clause; record
+ # a head so the def/use dialect sees those bindings. A plain ``try``
+ # has no ``resources`` field and records nothing (unchanged).
+ if try_node.child_by_field_name("resources") is not None:
+ self._record_head(cur, try_node)
join = self._new("join")
# ``finally`` is the convergence point everything funnels through; with
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 31639bc40..d7b8db4ef 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
@@ -15,7 +15,9 @@ def/use pass is silent for it (no dialect = no signal), the safe default.
from __future__ import annotations
from . import go as _go
+from . import java as _java
from . import python as _python
+from . import rust as _rust
from . import ts_js as _ts_js
from .base import (
DEFUSE_DIALECTS,
@@ -35,6 +37,8 @@ _REGISTER: tuple[tuple[str, BaseDefUseDialect], ...] = (
("tsx", _ts_js.DIALECT),
("javascript", _ts_js.DIALECT),
("jsx", _ts_js.DIALECT),
+ ("java", _java.DIALECT),
+ ("rust", _rust.DIALECT),
)
for _tag, _dialect in _REGISTER:
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py
new file mode 100644
index 000000000..4cae89d91
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py
@@ -0,0 +1,218 @@
+"""Java ``DefUseDialect``.
+
+Classifies each identifier in a statement as a write (def) or a read (use).
+Java's write sites are: ``local_variable_declaration`` (each nested
+``variable_declarator`` binds one name), plain and compound assignments (both
+are an ``assignment_expression`` -- told apart by the operator token, ``=`` vs
+``+=``, as in Go), update expressions (``x++`` / ``--x``, read-modify-write),
+the binder of an enhanced ``for`` (``for (T v : xs)``), the C-style ``for``
+initializer, and the resource clause of try-with-resources. Field targets
+(``obj.f = ...`` / ``this.f = ...``) and array targets (``arr[i] = ...``) bind
+no *local*, so their base identifiers are reads -- the precision-first choice
+that keeps reaching definitions sound for the locals they actually track.
+
+A ``method_invocation``'s ``name`` is the called method, not a variable, so
+the walk processes only its ``object`` and ``arguments``; the same for a
+``method_reference``'s method side. A ``switch`` stays a single CFG statement
+(no per-arm blocks), so a write inside an arm is only a *may*-def: it is
+recorded as both a def and a use, which keeps the promotion pass's must-def
+reasoning conservative (an uncertain write can only ever refuse a promotion,
+never license one).
+"""
+
+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 (kept in lockstep with the Java
+# ``LanguageNodeMap``; declared here so the traversal needs no lmap threading).
+_ASSIGN_KINDS = frozenset({"assignment_expression"})
+_UPDATE_KINDS = frozenset({"update_expression"}) # ``x++`` / ``--x``
+_DECL_KINDS = frozenset({"local_variable_declaration"})
+_DECLARATOR = "variable_declarator"
+_RESOURCE = "resource" # ``try (var res = open())``
+_ENHANCED_FOR = "enhanced_for_statement"
+_METHOD_INVOCATION = "method_invocation"
+_METHOD_REFERENCE = "method_reference" # ``Integer::parseInt``
+# Field (``obj.f``) and array (``arr[i]``) targets bind no local.
+_FIELD_ACCESS = "field_access"
+_ARRAY_ACCESS = "array_access"
+# A ``switch`` is one CFG statement; writes inside its arms are may-defs.
+_CONDITIONAL_KINDS = frozenset({"switch_expression", "switch_statement"})
+# Nested scopes whose identifiers belong to a different function. A
+# ``class_body`` covers anonymous-class methods inside an expression.
+_SCOPE_BOUNDARIES = frozenset({"lambda_expression", "class_body"})
+
+
+class JavaDefUseDialect(BaseDefUseDialect):
+ language = "java"
+ member_access_kinds = frozenset({"field_access"})
+ keyword_kinds = frozenset() # Java has no keyword arguments.
+
+ def _is_scope_boundary(self, node: Node) -> bool:
+ return node.type in _SCOPE_BOUNDARIES
+
+ def collect_reads(self, node: Node | None, out: list[Occurrence]) -> None:
+ """Like the base collector, but a ``method_invocation`` / ``method_reference``
+ contributes only its receiver and arguments -- never the method name."""
+ if node is not None and node.type == _METHOD_INVOCATION:
+ self.collect_reads(node.child_by_field_name("object"), out)
+ self.collect_reads(node.child_by_field_name("arguments"), out)
+ return
+ if node is not None and node.type == _METHOD_REFERENCE:
+ first = node.named_children[0] if node.named_children else None
+ if first is not None and first.type in self.identifier_kinds:
+ out.append(self._occ(first))
+ return
+ super().collect_reads(node, out)
+
+ # -- 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)
+ return StatementDefUse(defs=tuple(defs), uses=tuple(uses))
+
+ def parameter_defs(self, fn_node: Node) -> tuple[Occurrence, ...]:
+ """Names bound by the signature. A ``formal_parameter`` names its
+ binder in the ``name`` field; a varargs ``spread_parameter`` nests it
+ in a ``variable_declarator`` -- both are found by the same probe (the
+ type side is ``type_identifier`` nodes, never a bare ``identifier``)."""
+ 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:
+ out.append(self._occ(name_node))
+ return tuple(out)
+
+ def _binder_identifier(self, node: Node) -> Node | None:
+ named = node.child_by_field_name("name")
+ if named is not None and named.type in self.identifier_kinds:
+ return named
+ for child in node.named_children:
+ found = self._binder_identifier(child)
+ if found is not None:
+ return found
+ return None
+
+ # -- head (loop clause / if condition / try resources) --------------------
+
+ def _head(
+ self, node: Node, lmap: LanguageNodeMap, defs: list[Occurrence], uses: list[Occurrence]
+ ) -> None:
+ t = node.type
+ if t == _ENHANCED_FOR: # ``for (T v : xs)``
+ self._targets(node.child_by_field_name("name"), defs, uses)
+ self._process(node.child_by_field_name("value"), defs, uses)
+ elif t in lmap.loop_kinds: # for: init/cond/update; while / do: cond
+ self._process(node.child_by_field_name("init"), defs, uses)
+ self._process(node.child_by_field_name("condition"), defs, uses)
+ self._process(node.child_by_field_name("update"), defs, uses)
+ elif t in lmap.branch_kinds:
+ self._process(node.child_by_field_name("condition"), defs, uses)
+ elif t in lmap.try_kinds: # try-with-resources: the resource bindings
+ resources = node.child_by_field_name("resources")
+ if resources is not None:
+ for res in resources.named_children:
+ if res.type == _RESOURCE:
+ self._targets(res.child_by_field_name("name"), defs, uses)
+ self._process(res.child_by_field_name("value"), defs, uses)
+ else:
+ self._process(node, defs, uses)
+
+ # -- the unified expression / statement walk ------------------------------
+
+ 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")
+ self._targets(left, defs, uses)
+ op = node.child_by_field_name("operator")
+ if op is not None and op.text not in (b"=", None): # compound: read too
+ self.collect_reads(left, uses)
+ self._process(node.child_by_field_name("right"), defs, uses)
+ return
+ if t in _UPDATE_KINDS: # ``x++`` / ``--x`` -- read-modify-write
+ for child in node.named_children:
+ self._targets(child, defs, uses)
+ self.collect_reads(child, uses)
+ return
+ if t in _DECL_KINDS:
+ for declarator in node.named_children:
+ if declarator.type != _DECLARATOR:
+ continue
+ self._targets(declarator.child_by_field_name("name"), defs, uses)
+ self._process(declarator.child_by_field_name("value"), defs, uses)
+ return
+ if t == _METHOD_INVOCATION: # the ``name`` is a method, not a variable
+ self._process(node.child_by_field_name("object"), defs, uses)
+ self._process(node.child_by_field_name("arguments"), defs, uses)
+ return
+ if t == _METHOD_REFERENCE: # ``recv::method`` -- only the receiver reads
+ first = node.named_children[0] if node.named_children else None
+ if first is not None and first.type in self.identifier_kinds:
+ uses.append(self._occ(first))
+ return
+ if t in _CONDITIONAL_KINDS:
+ self._process_may_def(node, defs, uses)
+ return
+ if t in self.member_access_kinds:
+ self.collect_reads(node, uses) # receiver is a read; field name is not
+ return
+ if t in self.identifier_kinds:
+ uses.append(self._occ(node))
+ return
+ if self._is_scope_boundary(node):
+ return
+ for child in node.named_children:
+ self._process(child, defs, uses)
+
+ def _process_may_def(self, node: Node, defs: list[Occurrence], uses: list[Occurrence]) -> None:
+ """Process *node* whose writes execute only on some path (a switch arm).
+
+ Each def found within is recorded as a def AND a use: the may-def keeps
+ the variable in every "written in this region" set while its paired use
+ stays upward-exposed, so a downstream must-def proof can only get more
+ conservative, never less.
+ """
+ inner_defs: list[Occurrence] = []
+ for child in node.named_children: # not the node itself: no re-dispatch
+ self._process(child, inner_defs, uses)
+ defs.extend(inner_defs)
+ uses.extend(inner_defs)
+
+ # -- 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:
+ defs.append(self._occ(node))
+ return
+ if t in (_FIELD_ACCESS, _ARRAY_ACCESS): # ``obj.f = ...`` / ``a[i] = ...``
+ self.collect_reads(node, uses)
+ return
+ for child in node.named_children:
+ self._targets(child, defs, uses)
+
+
+DIALECT = JavaDefUseDialect()
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.py
new file mode 100644
index 000000000..d6b1fe156
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.py
@@ -0,0 +1,266 @@
+"""Rust ``DefUseDialect``.
+
+Classifies each identifier in a statement as a write (def) or a read (use).
+Rust's write sites are: ``let`` declarations (whose pattern may destructure --
+tuple, slice, struct, ``&``-reference, ``ref`` / ``mut`` binders), plain
+assignments (``assignment_expression``), compound assignments
+(``compound_assignment_expr``, read-modify-write), the binder of a ``for``
+pattern, and the pattern of a ``let_condition`` (``if let`` / ``while let``).
+Place-expression targets -- field (``self.f = ...``), index (``arr[i] = ...``),
+and deref (``*ptr = ...``) -- bind no *local*, so their base identifiers are
+reads. A ``self_parameter`` is seeded like a Go receiver so a span reading
+``self`` infers it as an IN.
+
+Two conservatisms keep the promotion pass's must-def reasoning sound on
+expression-oriented grammar the CFG does not open up:
+
+* a ``match`` (and any control-flow expression met in *expression* position)
+ stays a single CFG statement, so a write inside it executes only on some
+ path -- it is recorded as both a def and a use (a may-def), which can only
+ ever refuse a promotion, never license one;
+* a ``let_condition`` binder only binds when the pattern matches, so it is a
+ may-def too (unlike a ``for`` binder, which binds on every body entry).
+
+Macro bodies (``format!(...)``) are walked as token trees, so identifiers
+inside them still register as reads; a macro that *binds* a local is invisible,
+which errs toward extra refusals, never a wrong proof. Statement-position
+control flow arrives here already unwrapped from its ``expression_statement``
+carrier by the CFG builder (``statement_wrapper_kinds``).
+"""
+
+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 (kept in lockstep with the Rust
+# ``LanguageNodeMap``; declared here so the traversal needs no lmap threading).
+_ASSIGN_KINDS = frozenset({"assignment_expression"})
+_AUG_KINDS = frozenset({"compound_assignment_expr"})
+_LET_DECL = "let_declaration"
+_LET_CONDITION = "let_condition" # ``if let PAT = expr`` / ``while let ...``
+# Pattern containers whose identifier leaves are binders (defs).
+_PATTERN_CONTAINERS = frozenset(
+ {
+ "tuple_pattern",
+ "slice_pattern",
+ "or_pattern",
+ "reference_pattern",
+ "mut_pattern",
+ "captured_pattern",
+ "ref_pattern",
+ "match_pattern",
+ "parenthesized_pattern",
+ }
+)
+# Patterns that carry a *type* side to skip (``Some(v)`` / ``Point { x }`` --
+# the type is a plain ``identifier`` node in tuple-struct position, so a naive
+# descent would mint a phantom def for ``Some``).
+_TYPED_PATTERNS = frozenset({"tuple_struct_pattern", "struct_pattern"})
+_FIELD_PATTERN = "field_pattern"
+# Shorthand struct-pattern binder leaf (``Point { x, y }``).
+_SHORTHAND_BINDER = "shorthand_field_identifier"
+# Place-expression targets that bind no local: field / index / deref.
+_PLACE_TARGETS = frozenset({"field_expression", "index_expression", "unary_expression"})
+# Control-flow expressions met in expression position (or as the mega-statement
+# a ``match`` stays): their writes are may-defs.
+_CONDITIONAL_KINDS = frozenset(
+ {
+ "match_expression",
+ "if_expression",
+ "if_let_expression",
+ "while_expression",
+ "while_let_expression",
+ "for_expression",
+ "loop_expression",
+ }
+)
+# A ``scoped_identifier`` (``Vec::new`` / ``Color::Red``) is a path, never a
+# local variable; its component identifiers are skipped wholesale.
+_SCOPED_IDENTIFIER = "scoped_identifier"
+# Nested scopes whose identifiers belong to a different function; an
+# ``async_block`` captures like a closure and runs later.
+_SCOPE_BOUNDARIES = frozenset({"closure_expression", "function_item", "async_block"})
+
+
+class RustDefUseDialect(BaseDefUseDialect):
+ language = "rust"
+ member_access_kinds = frozenset({"field_expression"})
+ keyword_kinds = frozenset() # struct-literal field names are not reads.
+ # ``self`` is its own node type in tree-sitter-rust, not an ``identifier``;
+ # without it here every ``self.field`` read would drop its receiver (Go and
+ # Python receivers are plain identifiers, so only Rust needs the addition).
+ identifier_kinds = frozenset({"identifier", "self"})
+
+ def _is_scope_boundary(self, node: Node) -> bool:
+ return node.type in _SCOPE_BOUNDARIES
+
+ def collect_reads(self, node: Node | None, out: list[Occurrence]) -> None:
+ """Like the base collector, but a path (``Vec::new``) reads nothing."""
+ if node is not None and node.type == _SCOPED_IDENTIFIER:
+ return
+ super().collect_reads(node, out)
+
+ # -- 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)
+ return StatementDefUse(defs=tuple(defs), uses=tuple(uses))
+
+ def parameter_defs(self, fn_node: Node) -> tuple[Occurrence, ...]:
+ """Names bound by the signature: each ``parameter``'s pattern (which
+ may destructure) plus a ``self_parameter``, seeded like a Go receiver."""
+ params_node = fn_node.child_by_field_name("parameters")
+ if params_node is None:
+ return ()
+ out: list[Occurrence] = []
+ sink: list[Occurrence] = []
+ for child in params_node.named_children:
+ if child.type == "self_parameter":
+ for sub in child.children:
+ if sub.type == "self":
+ out.append(self._occ(sub))
+ break
+ continue
+ self._targets(child.child_by_field_name("pattern"), out, sink)
+ return tuple(out)
+
+ # -- head (loop clause / if condition) ------------------------------------
+
+ def _head(
+ self, node: Node, lmap: LanguageNodeMap, defs: list[Occurrence], uses: list[Occurrence]
+ ) -> None:
+ t = node.type
+ if t in lmap.loop_kinds:
+ pattern = node.child_by_field_name("pattern")
+ if pattern is not None: # ``for PAT in expr`` -- binds every entry
+ self._targets(pattern, defs, uses)
+ self._process(node.child_by_field_name("value"), defs, uses)
+ else: # ``while cond`` / ``while let`` / bare ``loop`` (no head)
+ self._condition(node.child_by_field_name("condition"), defs, uses)
+ elif t in lmap.branch_kinds:
+ self._condition(node.child_by_field_name("condition"), defs, uses)
+ else:
+ self._process(node, defs, uses)
+
+ def _condition(self, node: Node | None, defs: list[Occurrence], uses: list[Occurrence]) -> None:
+ """An ``if`` / ``while`` condition; a ``let_condition`` binds its
+ pattern only when it matches, so those binders are may-defs."""
+ if node is None:
+ return
+ if node.type == _LET_CONDITION:
+ binders: list[Occurrence] = []
+ self._targets(node.child_by_field_name("pattern"), binders, uses)
+ defs.extend(binders)
+ uses.extend(binders)
+ self._process(node.child_by_field_name("value"), defs, uses)
+ else:
+ self._process(node, defs, uses)
+
+ # -- the unified expression / statement walk ------------------------------
+
+ 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:
+ self._targets(node.child_by_field_name("left"), defs, uses)
+ self._process(node.child_by_field_name("right"), defs, uses)
+ return
+ if t in _AUG_KINDS:
+ left = node.child_by_field_name("left")
+ self._targets(left, defs, uses) # write
+ self.collect_reads(left, uses) # ...and read (read-modify-write)
+ self._process(node.child_by_field_name("right"), defs, uses)
+ return
+ if t == _LET_DECL:
+ self._targets(node.child_by_field_name("pattern"), defs, uses)
+ self._process(node.child_by_field_name("value"), defs, uses)
+ # ``let ... else { diverge }``: the arm runs only on mismatch, so
+ # anything it writes is a may-def.
+ alternative = node.child_by_field_name("alternative")
+ if alternative is not None:
+ self._process_may_def(alternative, defs, uses)
+ return
+ if t in _CONDITIONAL_KINDS:
+ self._process_may_def(node, defs, uses)
+ return
+ if t == _LET_CONDITION:
+ self._condition(node, defs, uses)
+ return
+ if t == _SCOPED_IDENTIFIER: # a path, never a local read
+ return
+ if t in self.member_access_kinds:
+ self.collect_reads(node, uses) # receiver is a read; field name is not
+ return
+ if t in self.identifier_kinds:
+ uses.append(self._occ(node))
+ return
+ if self._is_scope_boundary(node):
+ return
+ for child in node.named_children:
+ self._process(child, defs, uses)
+
+ def _process_may_def(self, node: Node, defs: list[Occurrence], uses: list[Occurrence]) -> None:
+ """Process *node* whose writes execute only on some path (a match arm,
+ an expression-position ``if`` / loop, a ``let-else`` arm).
+
+ Each def found within is recorded as a def AND a use, so a downstream
+ must-def proof can only get more conservative, never less.
+ """
+ inner_defs: list[Occurrence] = []
+ for child in node.named_children: # not the node itself: no re-dispatch
+ self._process(child, inner_defs, uses)
+ defs.extend(inner_defs)
+ uses.extend(inner_defs)
+
+ # -- write-target extraction (assignment LHS + binding patterns) ----------
+
+ 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 or t == _SHORTHAND_BINDER:
+ defs.append(self._occ(node))
+ return
+ if t in _PATTERN_CONTAINERS:
+ for child in node.named_children:
+ self._targets(child, defs, uses)
+ return
+ if t in _TYPED_PATTERNS: # skip the type side (``Some`` / ``Point``)
+ type_node = node.child_by_field_name("type")
+ for child in node.named_children:
+ if type_node is not None and child.id == type_node.id:
+ continue
+ self._targets(child, defs, uses)
+ return
+ if t == _FIELD_PATTERN: # ``x: pat`` descends; shorthand ``x`` binds
+ pattern = node.child_by_field_name("pattern")
+ if pattern is not None:
+ self._targets(pattern, defs, uses)
+ else:
+ name = node.child_by_field_name("name")
+ if name is not None:
+ self._targets(name, defs, uses)
+ return
+ if t in _PLACE_TARGETS: # ``obj.f`` / ``a[i]`` / ``*p``: bases are reads
+ self.collect_reads(node, uses)
+ return
+ for child in node.named_children:
+ self._targets(child, defs, uses)
+
+
+DIALECT = RustDefUseDialect()
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 5f4738a83..f473c4e51 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
@@ -94,6 +94,15 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[
)
jump_kinds = lmap.return_kinds | lmap.raise_kinds | lmap.break_kinds | lmap.continue_kinds
scope_kinds = lmap.function_kinds | lmap.lambda_kinds
+ # Expression-oriented grammars (nonempty ``statement_wrapper_kinds``): a
+ # block's last child that is not a statement is its tail expression -- the
+ # block's implicit value. A span ending on one would silently drop that
+ # value when lifted into a helper, so such spans are refused outright.
+ tail_stmt_kinds = (
+ lmap.statement_wrapper_kinds | lmap.local_decl_kinds
+ if lmap.statement_wrapper_kinds
+ else None
+ )
out: list[Extraction] = []
evaluated = 0
@@ -112,6 +121,12 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[
# Never extract the whole function body (that is not a split).
if is_body and length == n:
continue
+ if (
+ tail_stmt_kinds is not None
+ and j == n - 1
+ and stmts[j].type not in tail_stmt_kinds
+ ):
+ continue
span = stmts[i : j + 1]
decisions, has_jump = _span_metrics(span, decision_kinds, jump_kinds, scope_kinds)
if has_jump or decisions < _MIN_CCN_REMOVED:
diff --git a/tests/unit/health/test_dataflow_langs.py b/tests/unit/health/test_dataflow_langs.py
index 2e72ada91..659a84bb9 100644
--- a/tests/unit/health/test_dataflow_langs.py
+++ b/tests/unit/health/test_dataflow_langs.py
@@ -1,9 +1,9 @@
"""Dataflow def/use + CFG + Extract Method coverage for the ported languages.
-Covers the Go and TS/JS ``DefUseDialect``s and the language-agnostic CFG /
-slicer once the Python-specific grammar was lifted onto ``LanguageNodeMap``.
-Best-effort like the other dataflow tests: each language skips when its
-tree-sitter pack is missing rather than failing.
+Covers the Go, TS/JS, Java, and Rust ``DefUseDialect``s and the language-
+agnostic CFG / slicer once the Python-specific grammar was lifted onto
+``LanguageNodeMap``. Best-effort like the other dataflow tests: each language
+skips when its tree-sitter pack is missing rather than failing.
"""
from __future__ import annotations
@@ -12,12 +12,15 @@ import textwrap
import pytest
+from repowise.core.analysis.health.complexity.ast_utils import _collect_function_nodes
from repowise.core.analysis.health.complexity.languages import get_language_map
from repowise.core.analysis.health.dataflow import (
analyze_file,
+ analyze_function,
build_cfgs_for_file,
find_extractions,
)
+from repowise.core.analysis.health.perf.promotion import _loop_iterations_independent
def _require(language: str) -> None:
@@ -403,3 +406,592 @@ def test_ts_flagged_only_gate_skips_small_functions():
assert result.stats.functions_seen == 2
assert result.stats.functions_built == 1
assert [fc.name for fc in result.functions] == ["big"]
+
+
+# == the loop-carried-dependence proof, cross-language ==========================
+
+
+def _independent(language: str, src: str, marker: str) -> bool:
+ """Run the promotion proof at *marker*'s line in *src*'s first function."""
+ _require(language)
+ from tree_sitter import Parser
+
+ from repowise.core.ingestion.parser import _get_language
+
+ body = textwrap.dedent(src)
+ lmap = get_language_map(language)
+ parser = Parser(_get_language(language))
+ tree = parser.parse(body.encode())
+ nodes = _collect_function_nodes(tree.root_node, lmap)
+ assert nodes, "no function node parsed"
+ analyzed = analyze_function(nodes[0], language, lmap)
+ assert analyzed is not None, "analysis returned None"
+ cfg, def_use, reaching = analyzed
+ line = next(i for i, ln in enumerate(body.splitlines(), start=1) if marker in ln)
+ return _loop_iterations_independent(cfg, def_use, reaching, line)
+
+
+# == Java =======================================================================
+
+# Every Java write shape in one method: multi-declarator decl, ``=`` vs ``+=``
+# (operator-sniffed), ``x++`` / ``--x``, field / array targets (not locals),
+# an enhanced-for binder, a C-style for initializer, and try-with-resources.
+_JAVA_SHAPES = """
+class Demo {
+ int shapes(int[] input, int base, String... rest) {
+ int total = 0;
+ int a = 1, b = 2;
+ total += base;
+ a++;
+ --b;
+ this.field = total;
+ seen[a] = b;
+ for (int i = 0; i < input.length; i++) {
+ total += input[i];
+ }
+ for (int v : input) {
+ total -= v;
+ }
+ try (var res = open()) {
+ total = res.hashCode();
+ } catch (RuntimeException e) {
+ total = 0;
+ }
+ return total + a + b;
+ }
+}
+"""
+
+
+def test_java_def_use_classification():
+ fn = _first("java", _JAVA_SHAPES)
+ defs = _def_names(fn)
+ # Declarations, for-init, enhanced-for binder, and try resources are locals.
+ assert {"total", "a", "b", "i", "v", "res"} <= defs
+ assert {"input", "base", "rest"} <= defs # parameters (varargs included)
+ # Field (``this.field = ...``) and array (``seen[a] = ...``) targets bind
+ # no local: their bases are reads, never defs.
+ assert "field" not in defs
+ assert "seen" not in defs
+ uses = _use_names(fn)
+ assert {"base", "input", "seen", "a", "b", "total", "res"} <= uses
+ # Method names are never variable reads.
+ assert "hashCode" not in uses
+ assert "open" not in uses
+
+
+def test_java_compound_assign_reads_target():
+ fn = _first(
+ "java",
+ """
+ class Demo {
+ int f(int x) {
+ int acc = 0;
+ acc += x;
+ return acc;
+ }
+ }
+ """,
+ )
+ # ``acc += x`` is both a write and a read of ``acc``.
+ assert "acc" in _def_names(fn)
+ assert "acc" in _use_names(fn)
+
+
+def test_java_for_and_while_heads():
+ fn = _first(
+ "java",
+ """
+ class Demo {
+ int loops(int n) {
+ int sum = 0;
+ for (int j = 0; j < n; j++) {
+ sum += j;
+ }
+ while (sum < 100) {
+ sum *= 2;
+ }
+ return sum;
+ }
+ }
+ """,
+ )
+ assert "j" in _def_names(fn) # bound by the C-style for initializer
+ headers = [b for b in fn.cfg.blocks if b.kind == "loop_header"]
+ assert len(headers) == 2
+ assert fn.cfg.back_edges()
+
+
+def test_java_else_if_chain_branches():
+ fn = _first(
+ "java",
+ """
+ class Demo {
+ int grade(int x) {
+ int y = 0;
+ if (x == 1) {
+ y = 1;
+ } else if (x == 2) {
+ y = 2;
+ } else if (x == 3) {
+ y = 3;
+ } else {
+ y = 4;
+ }
+ return y;
+ }
+ }
+ """,
+ )
+ branches = [b for b in fn.cfg.blocks if b.kind == "branch"]
+ assert len(branches) == 3
+ assert fn.cfg.exit_id in fn.cfg.reachable_ids()
+
+
+def test_java_switch_arm_writes_are_may_defs():
+ # A ``switch`` stays one CFG statement, so an arm's write is conditional:
+ # it must register as BOTH a def and a use (the may-def convention that
+ # keeps the promotion proof conservative).
+ fn = _first(
+ "java",
+ """
+ class Demo {
+ int f(int x) {
+ int y = 0;
+ switch (x) {
+ case 1:
+ y = 10;
+ break;
+ default:
+ y = 20;
+ }
+ return y;
+ }
+ }
+ """,
+ )
+ decl_line = min(d.line for d in fn.def_use.definitions if d.var == "y")
+ switch_defs = [d for d in fn.def_use.definitions if d.var == "y" and d.line > decl_line]
+ assert switch_defs, "expected the arm writes to register as defs"
+ use_lines = {u.line for b in fn.def_use.blocks.values() for u in b.uses if u.name == "y"}
+ assert {d.line for d in switch_defs} <= use_lines # ...and as paired uses
+
+
+# A long Java method whose compute-average tail is a clean extraction.
+_JAVA_PROCESS = """
+class Demo {
+ int process(int[] records, int threshold) {
+ int errors = 0;
+ java.util.List<Integer> results = new java.util.ArrayList<>();
+ for (int r : records) {
+ if (r < 0) {
+ errors++;
+ continue;
+ }
+ results.add(r);
+ }
+ int total = 0;
+ int count = 0;
+ for (int v : results) {
+ if (v > threshold) {
+ total += v;
+ count++;
+ } else {
+ total -= v;
+ }
+ }
+ int average = 0;
+ if (count > 0) {
+ average = total / count;
+ }
+ return average + errors;
+ }
+}
+"""
+
+
+def test_java_extract_method_fires():
+ lmap = get_language_map("java")
+ extractions = find_extractions(_first("java", _JAVA_PROCESS), lmap)
+ assert extractions, "expected at least one Java extraction"
+ best = extractions[0]
+ assert "average" in best.returns
+ assert "results" in best.params and "threshold" in best.params
+ assert len(best.returns) <= 1
+ assert best.ccn_removed >= 1
+ assert best.slice_nloc >= 6
+
+
+def test_java_extractions_are_deterministic():
+ lmap = get_language_map("java")
+ fn = _first("java", _JAVA_PROCESS)
+
+ def serialize():
+ return [
+ (e.start_line, e.end_line, e.params, e.returns, e.ccn_removed)
+ for e in find_extractions(fn, lmap)
+ ]
+
+ first = serialize()
+ for _ in range(3):
+ assert serialize() == first
+
+
+def test_java_flagged_only_gate_skips_small_functions():
+ _require("java")
+ lines = ["class Demo {", " int big(int x) {", " int y = 0;"]
+ for i in range(12):
+ lines += [f" if (x == {i}) {{", f" y = {i};", " }"]
+ lines += [" return y;", " }", " int tiny() {", " return 1;", " }", "}"]
+ result = build_cfgs_for_file("m.java", "java", "\n".join(lines).encode())
+ if result.stats.functions_seen == 0:
+ pytest.skip("tree-sitter language pack missing for java")
+ assert result.stats.functions_seen == 2
+ assert result.stats.functions_built == 1
+ assert [fc.name for fc in result.functions] == ["big"]
+
+
+def test_java_append_loop_is_independent():
+ assert _independent(
+ "java",
+ """
+ class Demo {
+ void f(int[] items) {
+ for (int item : items) {
+ int r = fetch(item); // HIT
+ store(r);
+ }
+ }
+ }
+ """,
+ "HIT",
+ )
+
+
+def test_java_accumulator_is_carried():
+ assert not _independent(
+ "java",
+ """
+ class Demo {
+ int f(int[] items) {
+ int acc = 0;
+ for (int item : items) {
+ acc = acc + fetch(item); // HIT
+ }
+ return acc;
+ }
+ }
+ """,
+ "HIT",
+ )
+
+
+def test_java_switch_conditional_write_refuses_promotion():
+ # ``flag`` is written only on one switch arm, so it may carry across
+ # iterations; the may-def convention must keep this refused.
+ assert not _independent(
+ "java",
+ """
+ class Demo {
+ void f(int[] items) {
+ int flag = 0;
+ for (int item : items) {
+ switch (item) {
+ case 1:
+ flag = 1;
+ break;
+ default:
+ break;
+ }
+ int r = fetch(flag); // HIT
+ store(r);
+ }
+ }
+ }
+ """,
+ "HIT",
+ )
+
+
+# == Rust =======================================================================
+
+# Every Rust write shape in one function: ``let`` (plain / mut / tuple / struct
+# / slice patterns), ``=`` vs ``+=`` (distinct node kinds), field / index /
+# deref targets (not locals), a ``for`` binder, and paths (``Vec::new``).
+_RUST_SHAPES = """
+struct S { count: i64 }
+
+impl S {
+ fn shapes(&mut self, input: &[i64], base: i64) -> i64 {
+ let total = 0;
+ let mut acc = base;
+ let (a, b) = (1, 2);
+ let Wrapper { x, y } = wrapper;
+ let [head, tail] = pair;
+ acc += a;
+ acc = acc * 2;
+ self.count += 1;
+ arr[0] = acc;
+ obj.field = b;
+ *ptr = x;
+ let v = Vec::new();
+ for item in input {
+ acc += item + y + head + tail + total;
+ }
+ acc
+ }
+}
+"""
+
+
+def test_rust_def_use_classification():
+ fn = _first("rust", _RUST_SHAPES)
+ defs = _def_names(fn)
+ # ``let`` binders across pattern shapes, plus the for binder, are locals.
+ assert {"total", "acc", "a", "b", "x", "y", "head", "tail", "v", "item"} <= defs
+ assert {"input", "base", "self"} <= defs # params + the self receiver
+ # Field / index / deref targets bind no local: bases are reads, never defs.
+ assert "count" not in defs
+ assert "arr" not in defs
+ assert "obj" not in defs
+ assert "ptr" not in defs
+ # The tuple-struct/struct pattern *type* side is not a binder.
+ assert "Wrapper" not in defs
+ uses = _use_names(fn)
+ assert {"base", "acc", "self", "arr", "obj", "ptr", "item", "wrapper"} <= uses
+ # Path components (``Vec::new``) are never variable reads.
+ assert "Vec" not in uses
+ assert "new" not in uses
+
+
+def test_rust_while_let_binder_is_a_may_def():
+ fn = _first(
+ "rust",
+ """
+ fn drain(iter: &mut I) -> i64 {
+ let mut n = 0;
+ while let Some(item) = iter.next() {
+ n += item;
+ }
+ n
+ }
+ """,
+ )
+ # The pattern binds ``item`` only when it matches: def AND paired use.
+ assert "item" in _def_names(fn)
+ assert "item" in _use_names(fn)
+ assert [b for b in fn.cfg.blocks if b.kind == "loop_header"]
+
+
+def test_rust_else_if_chain_branches():
+ fn = _first(
+ "rust",
+ """
+ fn grade(x: i64) -> i64 {
+ let mut y = 0;
+ if x == 1 {
+ y = 1;
+ } else if x == 2 {
+ y = 2;
+ } else if x == 3 {
+ y = 3;
+ } else {
+ y = 4;
+ }
+ y
+ }
+ """,
+ )
+ branches = [b for b in fn.cfg.blocks if b.kind == "branch"]
+ assert len(branches) == 3
+ assert fn.cfg.exit_id in fn.cfg.reachable_ids()
+
+
+def test_rust_statement_position_control_flow_is_unwrapped():
+ # Rust parses statement-position loops / returns inside an
+ # ``expression_statement``; the CFG builder must classify the real node.
+ fn = _first(
+ "rust",
+ """
+ fn f(items: &[i64], x: i64) -> i64 {
+ let mut total = 0;
+ for it in items {
+ if *it > x {
+ total += it;
+ } else {
+ total -= it;
+ }
+ if *it == 0 {
+ continue;
+ }
+ }
+ return total;
+ }
+ """,
+ )
+ assert [b for b in fn.cfg.blocks if b.kind == "loop_header"]
+ assert len([b for b in fn.cfg.blocks if b.kind == "branch"]) == 2
+ assert fn.cfg.back_edges()
+
+
+# A long Rust function whose compute-average tail is a clean extraction.
+_RUST_PROCESS = """
+fn process(records: &[i64], threshold: i64) -> (i64, i64) {
+ let mut results = Vec::new();
+ let mut errors = 0;
+ for r in records {
+ if *r < 0 {
+ errors += 1;
+ continue;
+ }
+ results.push(*r);
+ }
+ let mut total = 0;
+ let mut count = 0;
+ for v in &results {
+ if *v > threshold {
+ total += v;
+ count += 1;
+ } else {
+ total -= v;
+ }
+ }
+ let mut average = 0;
+ if count > 0 {
+ average = total / count;
+ }
+ (average, errors)
+}
+"""
+
+
+def test_rust_extract_method_fires():
+ lmap = get_language_map("rust")
+ extractions = find_extractions(_first("rust", _RUST_PROCESS), lmap)
+ assert extractions, "expected at least one Rust extraction"
+ best = extractions[0]
+ assert "average" in best.returns
+ assert "results" in best.params and "threshold" in best.params
+ assert len(best.returns) <= 1
+ assert best.ccn_removed >= 1
+ assert best.slice_nloc >= 6
+
+
+def test_rust_extractions_never_cover_the_tail_expression():
+ # The final ``(average, errors)`` tail is the function's value; a span
+ # ending on it would silently drop that value, so none is ever offered.
+ fn = _first("rust", _RUST_PROCESS)
+ lmap = get_language_map("rust")
+ tail_line = fn.end_line - 1 # the tuple expression before the closing brace
+ for e in find_extractions(fn, lmap):
+ assert e.end_line < tail_line
+
+
+def test_rust_extractions_are_deterministic():
+ lmap = get_language_map("rust")
+ fn = _first("rust", _RUST_PROCESS)
+
+ def serialize():
+ return [
+ (e.start_line, e.end_line, e.params, e.returns, e.ccn_removed)
+ for e in find_extractions(fn, lmap)
+ ]
+
+ first = serialize()
+ for _ in range(3):
+ assert serialize() == first
+
+
+def test_rust_question_mark_span_has_no_extraction():
+ # ``?`` propagates an error out of the function -- an early exit that makes
+ # any span containing it unsafe to lift; every candidate here carries one.
+ lmap = get_language_map("rust")
+ src = """
+ fn load(paths: &[String], threshold: i64) -> Result<i64, E> {
+ let mut total = 0;
+ let mut count = 0;
+ for p in paths {
+ let data = read(p)?;
+ if data.len() > threshold {
+ total += parse(&data)?;
+ count += 1;
+ }
+ }
+ let mut average = 0;
+ if count > 0 {
+ average = total / count;
+ check(average)?;
+ }
+ Ok(average)
+ }
+ """
+ assert find_extractions(_first("rust", src), lmap) == []
+
+
+def test_rust_flagged_only_gate_skips_small_functions():
+ _require("rust")
+ lines = ["fn big(x: i64) -> i64 {", " let mut y = 0;"]
+ for i in range(12):
+ lines += [f" if x == {i} {{", f" y = {i};", " }"]
+ lines += [" y", "}", "", "fn tiny() -> i64 {", " 1", "}", ""]
+ result = build_cfgs_for_file("m.rs", "rust", "\n".join(lines).encode())
+ if result.stats.functions_seen == 0:
+ pytest.skip("tree-sitter language pack missing for rust")
+ assert result.stats.functions_seen == 2
+ assert result.stats.functions_built == 1
+ assert [fc.name for fc in result.functions] == ["big"]
+
+
+def test_rust_push_loop_is_independent():
+ assert _independent(
+ "rust",
+ """
+ fn f(items: &[i64]) -> Vec<i64> {
+ let mut out = Vec::new();
+ for item in items {
+ let r = fetch(item); // HIT
+ out.push(r);
+ }
+ out
+ }
+ """,
+ "HIT",
+ )
+
+
+def test_rust_accumulator_is_carried():
+ assert not _independent(
+ "rust",
+ """
+ fn f(items: &[i64]) -> i64 {
+ let mut acc = 0;
+ for item in items {
+ acc = acc + fetch(item); // HIT
+ }
+ acc
+ }
+ """,
+ "HIT",
+ )
+
+
+def test_rust_match_conditional_write_refuses_promotion():
+ # ``flag`` is written only on one match arm (a may-def inside the mega-
+ # statement), so it may carry across iterations: must stay refused.
+ assert not _independent(
+ "rust",
+ """
+ fn f(items: &[i64]) {
+ let mut flag = 0;
+ for item in items {
+ match item {
+ 1 => flag = 1,
+ _ => {}
+ }
+ let r = fetch(flag); // HIT
+ store(r);
+ }
+ }
+ """,
+ "HIT",
+ )
diff --git a/tests/unit/health/test_perf_promotion_engine.py b/tests/unit/health/test_perf_promotion_engine.py
index 56be8f9d9..09d016974 100644
--- a/tests/unit/health/test_perf_promotion_engine.py
+++ b/tests/unit/health/test_perf_promotion_engine.py
@@ -41,9 +41,11 @@ def _write(tmp_path: Path, name: str, src: str) -> str:
return str(p)
-def _walked_entry(tmp_path: Path, name: str, src: str, hits: list[PerfHit]):
+def _walked_entry(
+ tmp_path: Path, name: str, src: str, hits: list[PerfHit], language: str = "python"
+):
abs_path = _write(tmp_path, name, src)
- pf = _ParsedFile(_FileInfo(path=name, abs_path=abs_path, language="python"))
+ pf = _ParsedFile(_FileInfo(path=name, abs_path=abs_path, language=language))
fcx = FileComplexity(functions=[], classes=[], perf_hits=hits)
return pf, fcx
@@ -149,6 +151,74 @@ def test_budget_no_dataflow_without_advisory_hit(tmp_path: Path, monkeypatch):
assert e2[1].perf_hits[0].promoted is False
+def test_rust_independent_await_loop_is_promoted(tmp_path: Path):
+ # The promotion pass activates for a language the moment its def/use
+ # dialect exists. A ``?`` on the awaited value is an early *exit*, not a
+ # data carry -- the same contract as a Python ``await`` that may raise.
+ src = """
+ async fn f(items: &[Item]) -> Result<Vec<R>, E> {
+ let mut out = Vec::new();
+ for item in items {
+ let r = fetch(item.id).await?; // HIT
+ out.push(r);
+ }
+ Ok(out)
+ }
+ """
+ line = _line_of(src, "HIT")
+ hits = [PerfHit(kind="serial_await_in_loop", line=line, function="f", detail="network")]
+ pf, fcx = _walked_entry(tmp_path, "indep.rs", src, hits, language="rust")
+
+ apply_perf_promotions([(pf, fcx)])
+
+ if fcx.perf_hits[0].promoted is False: # pack missing -> silence, not a wrong answer
+ pytest.skip("tree-sitter language pack missing for rust")
+ assert fcx.perf_hits[0].promoted is True
+
+
+def test_rust_carried_cursor_is_not_promoted(tmp_path: Path):
+ src = """
+ async fn f(items: &[Item]) -> Cursor {
+ let mut cursor = start();
+ for item in items {
+ let page = fetch(cursor).await; // HIT
+ cursor = page.next;
+ }
+ cursor
+ }
+ """
+ line = _line_of(src, "HIT")
+ hits = [PerfHit(kind="serial_await_in_loop", line=line, function="f", detail="network")]
+ pf, fcx = _walked_entry(tmp_path, "carried.rs", src, hits, language="rust")
+
+ apply_perf_promotions([(pf, fcx)])
+
+ assert fcx.perf_hits[0].promoted is False
+
+
+def test_java_independent_nested_loop_is_promoted(tmp_path: Path):
+ src = """
+ class Demo {
+ void f(int[] items, int[] others) {
+ for (int a : items) {
+ for (int b : others) {
+ emit(a, b); // HIT
+ }
+ }
+ }
+ }
+ """
+ line = _line_of(src, "HIT")
+ hits = [PerfHit(kind="nested_loop_quadratic", line=line, function="f", detail="scan")]
+ pf, fcx = _walked_entry(tmp_path, "indep.java", src, hits, language="java")
+
+ apply_perf_promotions([(pf, fcx)])
+
+ if fcx.perf_hits[0].promoted is False:
+ pytest.skip("tree-sitter language pack missing for java")
+ assert fcx.perf_hits[0].promoted is True
+
+
def test_unsupported_language_degrades_to_silence(tmp_path: Path):
# A language with no def/use dialect leaves the hit advisory, never raises.
abs_path = _write(tmp_path, "a.rb", "def f; end\n")