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.

fix(#3825): avoid constant-output extract method helpers (#3938)

Ranjana3b2b16e5e095
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 4102e737b..2800290dd 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
@@ -106,6 +106,7 @@ from .slice_writes import (
_outs_definitely_assigned,
_stmt_assigns,
_stmts_assign,
+ _trailing_constant_output,
_unconditional_write,
_writes_var,
)
@@ -423,6 +424,8 @@ class _FunctionSlicer:
return None
if not _outs_definitely_assigned(span.nodes, returns, self.def_lines, self.lmap):
return None
+ if _trailing_constant_output(span.nodes, s, e, returns, self.def_lines, self.lmap):
+ return None
return params, returns
def _self_contained(self, blk: _Block, span: _Span, returns: tuple[str, ...]) -> bool:
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice_writes.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice_writes.py
index 31abd6d4b..e0040a268 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice_writes.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice_writes.py
@@ -98,6 +98,202 @@ def _writes_var(node: Node, var: str) -> bool:
return var in _identifiers(node)
+# Scalar literal node types across the supported grammars, read off node
+# kinds rather than text (cf. ``complexity/dispatch.py`` and the per-language
+# ``perf/dialects`` scalar sets: csharp/rust ``integer_literal``, cpp/kotlin
+# ``number_literal``, …). Deliberately scalars only: ``[]`` / ``{}`` are left
+# alone, conservatively still returned.
+_CONSTANT_LITERAL_KINDS = frozenset(
+ {
+ "true",
+ "false",
+ "none",
+ "null",
+ "nil",
+ "undefined",
+ "null_literal",
+ "boolean_literal",
+ "integer",
+ "integer_literal",
+ "float",
+ "float_literal",
+ "real_literal",
+ "floating_point_literal",
+ "number",
+ "number_literal",
+ "string",
+ "concatenated_string",
+ "string_literal",
+ "interpreted_string_literal",
+ "raw_string_literal",
+ "character_literal",
+ "rune_literal",
+ "decimal_integer_literal",
+ "hex_integer_literal",
+ "octal_integer_literal",
+ "binary_integer_literal",
+ "decimal_floating_point_literal",
+ "hex_floating_point_literal",
+ "int_literal",
+ "imaginary_literal",
+ }
+)
+# tree-sitter-kotlin spells ``true`` / ``false`` / ``null`` as bare
+# ``identifier`` nodes; matching on kind alone would accept every name.
+_LITERAL_IDENTIFIER_TEXTS = frozenset({"true", "false", "null"})
+_UNARY_KINDS = frozenset({"unary_expression", "unary_operator"})
+_PAREN_KINDS = frozenset({"parenthesized_expression"})
+_DECLARATOR_KINDS = frozenset(
+ {"variable_declarator", "init_declarator", "var_spec", "const_spec"}
+)
+
+
+def _is_literal_value(node: Node | None) -> bool:
+ """True when *node* is a scalar literal (``false``, ``0``, ``null``, ...).
+
+ Unwraps parentheses and a leading ``-`` / ``+`` (``-3`` is still a numeric
+ literal); anything else computed (calls, binary expressions, interpolated
+ template strings) is not one.
+ """
+ cur = node
+ while cur is not None and cur.type in _PAREN_KINDS and cur.named_children:
+ cur = cur.named_children[0]
+ if cur is None:
+ return False
+ if cur.type in _UNARY_KINDS:
+ operator = cur.child_by_field_name("operator")
+ op_text = (
+ (operator.text or b"").decode("utf-8", "replace").strip()
+ if operator is not None
+ else ""
+ )
+ if op_text not in ("-", "+"):
+ # ``!x`` / ``~x`` / ``not x`` compute; named children may still
+ # hold a literal operand, which must not count.
+ return False
+ operand = cur.child_by_field_name("argument") or cur.child_by_field_name("operand")
+ if operand is None:
+ named = cur.named_children
+ operand = named[-1] if named else None
+ return _is_literal_value(operand)
+ if cur.type in _CONSTANT_LITERAL_KINDS:
+ return True
+ if cur.type == "identifier":
+ text = (cur.text or b"").decode("utf-8", "replace")
+ return text in _LITERAL_IDENTIFIER_TEXTS
+ if cur.type == "template_string":
+ return not any(c.type == "template_substitution" for c in cur.children)
+ return False
+
+
+def _declarator_rhs(decl: Node) -> Node | None:
+ """Initializer on a single-name declarator, or None.
+
+ Most grammars expose a ``value`` / ``right`` field. C#'s
+ ``variable_declarator`` leaves the RHS as a field-less named child beside
+ the ``name`` (mirroring ``dataflow/dialects/csharp.py``).
+ """
+ value = decl.child_by_field_name("value") or decl.child_by_field_name("right")
+ if value is not None:
+ return value
+ name = decl.child_by_field_name("name")
+ rest = [c for c in decl.named_children if c != name]
+ return rest[0] if len(rest) == 1 else None
+
+
+def _trailing_value_node(last: Node, var: str, lmap: LanguageNodeMap) -> Node | None:
+ """The single RHS value *last* gives *var*, or None when it is not exactly
+ one plain declaration / assignment of it (multi-target declarators and
+ ``+=`` updates have no single value to read)."""
+ effective = last
+ if effective.type == "expression_statement" and len(effective.named_children) == 1:
+ effective = effective.named_children[0]
+ if effective.type in lmap.local_decl_kinds:
+ decls = [c for c in effective.named_children if _writes_var(c, var)]
+ if len(decls) != 1:
+ return None
+ writer = decls[0]
+ # C#: ``local_declaration_statement`` → ``variable_declaration`` (no
+ # value field) → ``variable_declarator`` (holds the initializer).
+ if writer.type not in _DECLARATOR_KINDS:
+ nested = [
+ c
+ for c in writer.named_children
+ if c.type in _DECLARATOR_KINDS and _writes_var(c, var)
+ ]
+ if len(nested) > 1:
+ return None
+ if len(nested) == 1:
+ writer = nested[0]
+ value = (
+ _declarator_rhs(writer)
+ if writer.type in _DECLARATOR_KINDS
+ else writer.child_by_field_name("value") or writer.child_by_field_name("right")
+ )
+ if value is None:
+ # Go's ``short_var_declaration`` carries the values on the
+ # statement itself (``left`` / ``right`` expression lists).
+ value = effective.child_by_field_name("value") or effective.child_by_field_name("right")
+ if value is not None and value.type == "expression_list" and len(value.named_children) == 1:
+ left = effective.child_by_field_name("left")
+ if left is None or len(left.named_children) == 1:
+ value = value.named_children[0]
+ return value
+ if effective.type in _DECLARATOR_KINDS:
+ if not _writes_var(effective, var):
+ return None
+ return _declarator_rhs(effective)
+ if effective.type in lmap.augmented_assign_kinds:
+ return None
+ if effective.type not in lmap.assignment_kinds:
+ return None
+ if not _writes_var(effective, var):
+ return None
+ value = effective.child_by_field_name("value") or effective.child_by_field_name("right")
+ if value is not None and value.type == "expression_list" and len(value.named_children) == 1:
+ left = effective.child_by_field_name("left")
+ if left is not None and left.type == "expression_list" and len(left.named_children) != 1:
+ return None
+ value = value.named_children[0]
+ return value
+
+
+def _trailing_constant_output(
+ span: list[Node],
+ s: int,
+ e: int,
+ returns: tuple[str, ...],
+ def_lines: dict[str, list[int]],
+ lmap: LanguageNodeMap,
+) -> bool:
+ """True when the span's single OUT is defined only by a trailing statement
+ giving it a literal (``boolean allEscape = false;``).
+
+ The helper would then only ever return that constant and the call site
+ would read ``boolean allEscape = extractedHelper(...)`` for what was
+ ``= false``. The trimmed span is itself a candidate, so callers drop this
+ one and the void helper wins; decision points moved are unchanged (the
+ trailing declaration carries none).
+
+ Conservative: a computed RHS (``boolean ok = check(x);``) and a literal
+ followed by another in-span write (``= false;`` then ``if (x) {..= true;}``)
+ both keep the return.
+ """
+ if len(returns) != 1 or not span:
+ return False
+ var = returns[0]
+ last = span[-1]
+ lo = last.start_point[0] + 1
+ hi = last.end_point[0] + 1
+ own = [d for d in def_lines.get(var, []) if s <= d <= e]
+ if not own or any(d < lo or d > hi for d in own):
+ return False
+ for other, lines in def_lines.items():
+ if other != var and any(lo <= d <= hi for d in lines):
+ return False
+ return _is_literal_value(_trailing_value_node(last, var, lmap))
+
+
def _is_conditional(node: Node, lmap: LanguageNodeMap) -> bool:
return node.type in lmap.if_kinds or (
node.type in lmap.branch_kinds and node.child_by_field_name("condition") is not None
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/stages.py b/packages/core/src/repowise/core/analysis/health/dataflow/stages.py
index 4d64a6608..36858f197 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/stages.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/stages.py
@@ -84,6 +84,7 @@ from .slice import (
_valueless_lines,
_var_lines,
)
+from .slice_writes import _trailing_constant_output
from .span import exiting_guard, is_comment, section_heads
if TYPE_CHECKING:
@@ -450,6 +451,8 @@ class _Cutter:
if self.carried:
written = {v for v in self.carried if any(s <= ln <= e for ln in self.def_lines[v])}
returns = tuple(sorted(set(returns) | written))
+ if _trailing_constant_output(span, s, e, returns, self.def_lines, self.lmap):
+ return None
params = self._with_inouts(i, j, s, params, returns)
if params is None or len(returns) > self.max_returns:
return None
diff --git a/tests/unit/health/test_extract_method_stages.py b/tests/unit/health/test_extract_method_stages.py
index d527231fc..498c88f7d 100644
--- a/tests/unit/health/test_extract_method_stages.py
+++ b/tests/unit/health/test_extract_method_stages.py
@@ -17,10 +17,15 @@ import pytest
from repowise.core.analysis.health.complexity.languages import get_language_map
from repowise.core.analysis.health.dataflow import Extraction, analyze_file
+from repowise.core.analysis.health.dataflow.slice import _unwrap_container
from repowise.core.analysis.health.dataflow.stages import (
STAGE_MAX_CCN,
STAGE_MAX_NLOC,
+ _Blocks,
_composes,
+ _Cutter,
+ _descent,
+ _FunctionFacts,
find_stages,
)
from repowise.core.analysis.health.refactoring.extract_method import ExtractMethodDetector
@@ -868,6 +873,45 @@ def _ts_section(n: int) -> str:
"""
+def test_a_stage_ending_in_a_constant_keeps_its_carried_output():
+ # The trailing-constant check must see the carried outputs merged in, not
+ # liveness alone: this loop-body stage ends in ``flag = False`` (flag is
+ # read after the loop) and also advances the loop-carried ``total`` the
+ # ``while`` header reads, so its signature is (flag, total) — a real
+ # split, not a constant-returning helper.
+ src = """
+def run(items, limit):
+ total = 0
+ n = 0
+ flag = True
+ while total < limit:
+ x = items[n]
+ if x > limit:
+ total += x
+ else:
+ total -= x
+ if total > 1000:
+ total = 1000
+ flag = False
+ n += 1
+ return flag
+"""
+ (fn,) = _functions(src)
+ lmap = get_language_map("python")
+ blocks = _Blocks(fn, lmap, None, {})
+ facts = _FunctionFacts(fn, lmap)
+ body = fn.fn_node.child_by_field_name("body")
+ looped = [(b, loops) for b, loops in _descent(_unwrap_container(body, lmap.block_kinds), blocks, lmap) if loops]
+ assert looped, "expected the cut to descend into the loop body"
+ block, loops = looped[0]
+ code, pre = blocks.code(block)
+ cutter = _Cutter(facts, lmap, None, block, code, pre, 3, loops)
+ j = next(k for k, st in enumerate(code) if "flag = False" in (st.text or b"").decode())
+ stage = cutter._stage(0, j)
+ assert stage is not None
+ assert set(stage.returns) == {"flag", "total"}
+
+
@pytest.mark.parametrize("shape", ["labelled", "do_while"])
def test_typescript_loop_bodies_are_cut(shape):
body = textwrap.indent(textwrap.dedent("".join(_ts_section(n) for n in range(8))), " ")
diff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.py
index 3d7344deb..1a9b4427e 100644
--- a/tests/unit/health/test_refactoring_extract_method.py
+++ b/tests/unit/health/test_refactoring_extract_method.py
@@ -1345,6 +1345,383 @@ def test_a_span_holding_an_import_read_after_it_is_refused():
assert found[(3, 6)] == (("a", "c"), ("t",))
+# A helper whose only output is a constant says nothing: the call site reads
+# ``boolean allEscape = extractedHelper(...)`` for what was ``= false``. The
+# span one statement shorter (same decision points, a void helper) is the plan.
+_LOOP_CONSTANT_TAIL = """
+class Loop {
+ void visitLoop(Node cond, Node body, Writer w, Scope scope, Label start, Label end) {
+ if (cond != null && !cond.isConstant()) {
+ w.mark(start);
+ }
+ if (cond != null && cond.isContinuous() == false) {
+ w.visit(cond, scope);
+ w.jumpIfZero(end);
+ }
+ Variable loop = scope.lookup("loop");
+ if (loop != null) {
+ w.writeCounter(loop.slot());
+ }
+ if (scope.isDebug() || scope.isTracing()) {
+ w.trace("loop");
+ }
+ %s
+ if (body != null) {
+ allEscape = body.allEscape();
+ if (allEscape && scope.isDebug()) {
+ return;
+ }
+ w.visit(body, scope);
+ }
+ if (!allEscape) {
+ w.jump(start);
+ }
+ w.mark(end);
+ }
+}
+"""
+
+
+def _java_constant_tail_ctx(src: str):
+ res = analyze_file("Loop.java", "java", textwrap.dedent(src).encode(), flagged_only=False)
+ if res.stats.functions_seen == 0:
+ pytest.skip("tree-sitter language pack missing for java")
+ fn = next(f for f in res.functions if f.name == "visitLoop")
+ ctx = RefactoringContext(
+ file_path="Loop.java",
+ language="java",
+ nloc=500,
+ findings=[_Finding("complex_method", fn.name, fn.start_line, 1.5)],
+ function_analyses=res.functions,
+ )
+ return res, fn, ctx
+
+
+def test_a_trailing_constant_declaration_is_left_in_the_host():
+ src = _LOOP_CONSTANT_TAIL % "boolean allEscape = false;"
+ _res, _fn, ctx = _java_constant_tail_ctx(src)
+ (s,) = [x for x in ExtractMethodDetector().detect(ctx) if x.refactoring_type == "extract_method"]
+ assert s.plan["returns"] == []
+ decl = next(i for i, line in enumerate(textwrap.dedent(src).splitlines(), 1) if "allEscape = false" in line)
+ assert s.plan["span"]["end"] == decl - 1
+ assert "void" in s.plan["new_symbol"]["signature_text"]
+ assert s.plan["new_symbol"].get("return_text") is None
+
+
+def test_no_candidate_returns_a_trailing_constant():
+ src = _LOOP_CONSTANT_TAIL % "boolean allEscape = false;"
+ res, _fn, _ctx = _java_constant_tail_ctx(src)
+ decl = next(i for i, line in enumerate(textwrap.dedent(src).splitlines(), 1) if "allEscape = false" in line)
+ lmap = get_language_map("java")
+ for fn in res.functions:
+ for c in find_extractions(fn, lmap):
+ assert not (c.returns == ("allEscape",) and c.end_line == decl)
+
+
+def test_a_computed_rhs_still_returns_the_output():
+ # ``cond`` is already an input, so the declaration adds no parameter: the
+ # span ending on it is offered, returning what the span computes.
+ src = _LOOP_CONSTANT_TAIL % "boolean allEscape = cond == null;"
+ _res, _fn, ctx = _java_constant_tail_ctx(src)
+ (s,) = [x for x in ExtractMethodDetector().detect(ctx) if x.refactoring_type == "extract_method"]
+ assert s.plan["returns"] == ["allEscape"]
+ decl = next(i for i, line in enumerate(textwrap.dedent(src).splitlines(), 1) if "allEscape = cond" in line)
+ assert s.plan["span"]["end"] == decl
+
+
+def test_a_literal_followed_by_reassignment_still_returns():
+ # The constant is not the span's only definition of the name: the
+ # conditional rewrite inside the span is what the read after observes.
+ src = """
+ class Loop {
+ void visitLoop(Node cond, Writer w, Scope scope, Label start, Label end) {
+ if (cond != null && !cond.isConstant()) {
+ w.mark(start);
+ }
+ if (cond != null && cond.isContinuous() == false) {
+ w.visit(cond, scope);
+ w.jumpIfZero(end);
+ }
+ Variable loop = scope.lookup("loop");
+ if (loop != null) {
+ w.writeCounter(loop.slot());
+ }
+ if (scope.isDebug() || scope.isTracing()) {
+ w.trace("loop");
+ }
+ boolean allEscape = false;
+ if (cond != null) {
+ allEscape = true;
+ }
+ if (!allEscape) {
+ w.jump(start);
+ }
+ w.mark(end);
+ }
+ }
+ """
+ res = analyze_file("Loop.java", "java", textwrap.dedent(src).encode(), flagged_only=False)
+ if res.stats.functions_seen == 0:
+ pytest.skip("tree-sitter language pack missing for java")
+ fn = next(f for f in res.functions if f.name == "visitLoop")
+ found = [c for c in find_extractions(fn, get_language_map("java")) if c.returns == ("allEscape",)]
+ assert found, "a literal rewritten inside the span is still returned"
+
+
+def test_a_trailing_constant_is_dropped_in_python_and_go():
+ py = textwrap.dedent(
+ """
+ def visit_loop(cond, body, w, scope, start, end):
+ if cond is not None and not cond.is_constant():
+ w.mark(start)
+ if cond is not None and cond.is_continuous() == False:
+ w.visit(cond, scope)
+ w.jump_if_zero(end)
+ loop = scope.lookup("loop")
+ if loop is not None:
+ w.write_counter(loop.slot())
+ if scope.is_debug() or scope.is_tracing():
+ w.trace("loop")
+ allEscape = False
+ if body is not None:
+ allEscape = body.all_escape()
+ w.visit(body, scope)
+ if not allEscape:
+ w.jump(start)
+ w.mark(end)
+ return allEscape
+ """
+ )
+ res = analyze_file("m.py", "python", py.encode(), flagged_only=False)
+ fn = res.functions[0]
+ decl = next(i for i, line in enumerate(py.splitlines(), 1) if "allEscape = False" in line)
+ assert not [
+ c
+ for c in find_extractions(fn, get_language_map("python"))
+ if c.returns == ("allEscape",) and c.end_line == decl
+ ]
+ go = textwrap.dedent(
+ """
+ package main
+ func visitLoop(cond Node, body Node, w Writer, scope Scope, start Label, end Label) bool {
+ if cond != nil {
+ w.Mark(start)
+ }
+ if cond != nil {
+ w.Visit(cond, scope)
+ w.JumpIfZero(end)
+ }
+ loop := scope.Lookup("loop")
+ if loop != nil {
+ w.WriteCounter(loop.Slot())
+ }
+ if scope.IsDebug() {
+ w.Trace("loop")
+ }
+ allEscape := false
+ if body != nil {
+ allEscape = body.AllEscape()
+ w.Visit(body, scope)
+ }
+ if !allEscape {
+ w.Jump(start)
+ }
+ w.Mark(end)
+ return allEscape
+ }
+ """
+ )
+ res = analyze_file("m.go", "go", go.encode(), flagged_only=False)
+ if res.stats.functions_seen == 0:
+ pytest.skip("go parse unavailable")
+ fn = res.functions[0]
+ decl = next(i for i, line in enumerate(go.splitlines(), 1) if "allEscape := false" in line)
+ assert not [
+ c
+ for c in find_extractions(fn, get_language_map("go"))
+ if c.returns == ("allEscape",) and c.end_line == decl
+ ]
+
+
+# Dialects whose grammars spell scalars outside the original four-language
+# kind set (and C#, whose initializer sits one declarator below the writer).
+# Scala / Kotlin have no def/use dialect yet, so they are covered by the
+# literal-kind probe below rather than find_extractions.
+_LOOP_CONSTANT_TAIL_DIALECTS = (
+ (
+ "csharp",
+ "cs",
+ "allEscape = false",
+ "allEscape",
+ """
+ class Loop {
+ void VisitLoop(Node cond, Node body, Writer w, Scope scope, Label start, Label end) {
+ if (cond != null && !cond.IsConstant()) {
+ w.Mark(start);
+ }
+ if (cond != null && cond.IsContinuous() == false) {
+ w.Visit(cond, scope);
+ w.JumpIfZero(end);
+ }
+ Variable loop = scope.Lookup("loop");
+ if (loop != null) {
+ w.WriteCounter(loop.Slot());
+ }
+ if (scope.IsDebug() || scope.IsTracing()) {
+ w.Trace("loop");
+ }
+ bool allEscape = false;
+ if (body != null) {
+ allEscape = body.AllEscape();
+ if (allEscape && scope.IsDebug()) {
+ return;
+ }
+ w.Visit(body, scope);
+ }
+ if (!allEscape) {
+ w.Jump(start);
+ }
+ w.Mark(end);
+ }
+ }
+ """,
+ ),
+ (
+ "rust",
+ "rs",
+ "all_escape = false",
+ "all_escape",
+ """
+ fn visit_loop(cond: Cond, body: Body, w: W, scope: Scope, start: L, end: L) {
+ if cond.is_some() {
+ w.mark(start);
+ }
+ if cond.is_continuous() == false {
+ w.visit(&cond, &scope);
+ w.jump_if_zero(end);
+ }
+ let loop_var = scope.lookup("loop");
+ if loop_var.is_some() {
+ w.write_counter(loop_var.slot());
+ }
+ if scope.is_debug() || scope.is_tracing() {
+ w.trace("loop");
+ }
+ let mut all_escape = false;
+ if body.is_some() {
+ all_escape = body.all_escape();
+ w.visit(&body, &scope);
+ }
+ if !all_escape {
+ w.jump(start);
+ }
+ w.mark(end);
+ }
+ """,
+ ),
+ (
+ "cpp",
+ "cpp",
+ "allEscape = 0",
+ "allEscape",
+ """
+ void visitLoop(Node* cond, Node* body, Writer* w, Scope* scope, Label start, Label end) {
+ if (cond != nullptr && !cond->isConstant()) {
+ w->mark(start);
+ }
+ if (cond != nullptr && cond->isContinuous() == false) {
+ w->visit(cond, scope);
+ w->jumpIfZero(end);
+ }
+ Variable* loop = scope->lookup("loop");
+ if (loop != nullptr) {
+ w->writeCounter(loop->slot());
+ }
+ if (scope->isDebug() || scope->isTracing()) {
+ w->trace("loop");
+ }
+ int allEscape = 0;
+ if (body != nullptr) {
+ allEscape = body->allEscape();
+ w->visit(body, scope);
+ }
+ if (!allEscape) {
+ w->jump(start);
+ }
+ w->mark(end);
+ }
+ """,
+ ),
+)
+
+
+ ("language", "ext", "needle", "var", "src"),
+ _LOOP_CONSTANT_TAIL_DIALECTS,
+ ids=[row[0] for row in _LOOP_CONSTANT_TAIL_DIALECTS],
+)
+def test_no_candidate_returns_a_trailing_constant_across_dialects(language, ext, needle, var, src):
+ if _get_language(language) is None:
+ pytest.skip(f"tree-sitter language pack missing for {language}")
+ body = textwrap.dedent(src)
+ res = analyze_file(f"Loop.{ext}", language, body.encode(), flagged_only=False)
+ if res.stats.functions_seen == 0 or not res.functions:
+ pytest.skip(f"parse unavailable for {language}")
+ fn = res.functions[0]
+ decl = next(i for i, line in enumerate(body.splitlines(), 1) if needle in line)
+ lmap = get_language_map(language)
+ assert not [
+ c for c in find_extractions(fn, lmap) if c.returns == (var,) and c.end_line == decl
+ ]
+
+
+ ("language", "ext", "src", "literal", "kind"),
+ [
+ ("csharp", "cs", "class C { void M() { bool x = false; } }", "false", "boolean_literal"),
+ ("rust", "rs", "fn m() { let x = false; }", "false", "boolean_literal"),
+ ("scala", "scala", "object O { def m(): Unit = { val x = false } }", "false", "boolean_literal"),
+ ("cpp", "cpp", "void m() { int x = 0; }", "0", "number_literal"),
+ ("kotlin", "kt", "fun m() { val x = false }", "false", "identifier"),
+ ],
+ ids=["csharp", "rust", "scala", "cpp", "kotlin"],
+)
+def test_trailing_constant_literal_kinds_match_vendored_grammars(language, ext, src, literal, kind):
+ # Kind / text gate the constant-tail drop uses: CI must see the spellings
+ # find_extractions cannot exercise for dialects without a def/use map.
+ from repowise.core.analysis.health.dataflow.parsing import parse_source
+ from repowise.core.analysis.health.dataflow.slice_writes import _is_literal_value
+
+ if _get_language(language) is None:
+ pytest.skip(f"tree-sitter language pack missing for {language}")
+ parsed = parse_source(f"m.{ext}", language, src.encode())
+ if parsed is None:
+ pytest.skip(f"parse unavailable for {language}")
+ root, _lmap = parsed
+ needle = literal.encode()
+ stack = [root]
+ lit = None
+ while stack:
+ node = stack.pop()
+ if node.is_named and node.type == kind and (node.text or b"") == needle:
+ lit = node
+ break
+ stack.extend(node.named_children)
+ assert lit is not None, f"{language}: expected {kind} spelling of {literal!r}"
+ assert _is_literal_value(lit)
+ if kind == "identifier":
+ # Accepting every identifier would drop helpers that return a name.
+ stack = [root]
+ name = None
+ while stack:
+ node = stack.pop()
+ if node.is_named and node.type == "identifier" and (node.text or b"") == b"x":
+ name = node
+ break
+ stack.extend(node.named_children)
+ assert name is not None and not _is_literal_value(name)
+
+
@pytest.mark.parametrize(
("prefix", "inside", "floor", "offered"),
[("import json\n", "", 0, True), ("", " import json\n", 2, False)],