Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(health): stop string_concat_in_loop firing on += onto the loop's own element (#4769)
Raghav Chamadiya4354f40a9e46
diff --git a/docs/layers/PERFORMANCE.md b/docs/layers/PERFORMANCE.mdindex 9e1c7cdb7..ad5061151 100644--- a/docs/layers/PERFORMANCE.md+++ b/docs/layers/PERFORMANCE.md@@ -27,6 +27,8 @@ A few shapes are deliberately quiet:- A loop that appends to one string several times is one `string_concat_in_loop`finding that lists every append line. TypeScript and JavaScript never get thisfinding, because JavaScript engines make repeated `+=` linear.+- A `+=` onto the name the loop header binds each pass (`for p in ps: p += "/32"`)+ is not flagged, because each pass grows a different string.- A TypeScript or JavaScript `includes` check against a short `const` table ofliterals that the file never changes is not flagged, because a table of fixedsize costs the same at any scale.diff --git a/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py b/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.pyindex c084bdffb..c91aeb075 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py@@ -330,6 +330,19 @@ def _loop_bound_names(loop: Node) -> set[bytes]:return set().union(*(_bound_in(p) for p in parts), *(_identifiers(c) for c in unfielded))+def _loop_element_names(loop: Node) -> set[bytes]:+ """The names a for-each header rebinds each pass. A counted loop's init is+ left out: ``for (String s = ""; ...; )`` carries ``s`` across passes."""+ parts = [loop, *(c for c in loop.children if c.type == "range_clause")]+ nodes = [part.child_by_field_name(field) for part in parts for field in _ELEMENT_FIELDS]+ nodes += [+ c+ for i, c in enumerate(loop.children)+ if c.type == "variable_declaration" and loop.field_name_for_child(i) is None+ ]+ return set().union(*(_identifiers(node) for node in nodes if node is not None))++def _block_bound_names(block: Node) -> set[bytes]:"""The parameters a block loop's lambda binds; Kotlin's implicit ``it`` when it declares none."""node = block@@ -467,6 +480,32 @@ def _concat_target(node: Node) -> str:return _subject_text(left if left is not None else next(iter(node.named_children), None))+def _plain_target_name(node: Node) -> bytes | None:+ """The bare name an assignment writes (Go wraps it in an ``expression_list``)."""+ left = node.child_by_field_name("left")+ if left is not None and left.type == "expression_list" and left.named_child_count == 1:+ left = left.named_children[0]+ return left.text if left is not None and left.type == "identifier" and left.text else None+++def _grows_loop_variable(node: Node, loop_kinds: frozenset[str], fn_kinds: frozenset[str]) -> bool:+ """*node* is ``x += ...`` onto a name the nearest loop's header binds.++ The header rebinds it each pass, so nothing accumulates across passes. Only+ the nearest loop counts: an outer loop's element grown in an inner loop+ still accumulates across the inner passes.+ """+ name = _plain_target_name(node)+ if name is None:+ return False+ cur = node.parent+ while cur is not None and cur.type not in fn_kinds:+ if cur.type in loop_kinds and cur.is_named:+ return name in _loop_element_names(cur)+ cur = cur.parent+ return False++def _quotable(callee: str) -> bool:return bool(callee) and not callee.startswith("(") and len(callee) <= _SINK_CALL_MAX@@ -1116,20 +1155,25 @@ class _PerfWalk:if cur.loop_depth < 1:returnif self.do_string_concat and dialect.is_string_concat(node):- self.hits.append(- PerfHit(- "string_concat_in_loop",- node.start_point[0] + 1,- nxt.func,- "",- func_start=nxt.start,- loop=self.loop_facts(node, sink=False),- subject=_concat_target(node),- )- )+ self._on_string_concat(node, nxt)elif self.do_loop_stmt_marker:self._on_loop_statement(node, nxt)+ def _on_string_concat(self, node: Node, nxt: _Frame) -> None:+ if _grows_loop_variable(node, self.loop_kinds, self.fn_kinds):+ return+ self.hits.append(+ PerfHit(+ "string_concat_in_loop",+ node.start_point[0] + 1,+ nxt.func,+ "",+ func_start=nxt.start,+ loop=self.loop_facts(node, sink=False),+ subject=_concat_target(node),+ )+ )+def _on_loop_statement(self, node: Node, nxt: _Frame) -> None:sm = self.dialect.loop_stmt_marker(node, self.list_names)if sm == "lock_in_loop" and self._lock_not_hoistable(node, None, nxt):diff --git a/tests/unit/health/test_perf_dialects.py b/tests/unit/health/test_perf_dialects.pyindex 3bd979bbb..5abf999c9 100644--- a/tests/unit/health/test_perf_dialects.py+++ b/tests/unit/health/test_perf_dialects.py@@ -632,6 +632,57 @@ def test_python_string_concat_reset_per_iteration_not_flagged():assert ("string_concat_in_loop", "") in _hits("python", accum)+# ``+=`` onto a name the loop header rebinds each pass never accumulates. An+# outer loop's element grown in an inner loop still accumulates across the+# inner passes, so it stays flagged like an outer accumulator.+_LOOP_VAR_CONCAT = {+ "go": (+ 'package p\nfunc f(ps []string){ for _, p := range ps { p += "/32"; use(p) } }\n',+ 'package p\nfunc f(ps []string){ for _, p := range ps { for range ps { p += "/" } } }\n',+ 'package p\nfunc f(ps []string){ out := ""; for _, p := range ps { out += "," } }\n',+ ),+ "python": (+ "def f(items):\n for ch in items:\n ch += 'x'\n use(ch)\n",+ "def f(rows):\n for k, v in rows:\n for c in v:\n k += '.'\n",+ "def f(items):\n out = ''\n for ch in items:\n out += 'x'\n",+ ),+ "java": (+ 'class A { void f(List<String> ps) { for (String p : ps) { p += "/32"; use(p); } } }\n',+ 'class A { void f(List<String> ps) { for (String p : ps) { for (String q : ps) { p += "/"; } } } }\n',+ 'class A { void f(List<String> ps) { String o = ""; for (String p : ps) { o += ","; } } }\n',+ ),+}++[email protected]("lang", sorted(_LOOP_VAR_CONCAT))+def test_string_concat_onto_loop_variable_not_flagged(lang):+ own, outer, accumulator = _LOOP_VAR_CONCAT[lang]+ assert not any(k == "string_concat_in_loop" for k, _ in _hits(lang, own))+ assert ("string_concat_in_loop", "") in _hits(lang, outer)+ assert ("string_concat_in_loop", "") in _hits(lang, accumulator)+++ ("lang", "src", "flagged"),+ [+ # Every name a destructuring header binds is rebound each pass.+ ("python", "def f(rows):\n for k, v in rows:\n v += 'x'\n use(v)\n", False),+ ("go", 'package p\nfunc f(ps []string){ for i, v := range ps { v += "x"; use(i, v) } }\n', False),+ # A counted loop's init and a non-name target carry across passes.+ ("go", 'package p\nfunc f(n int){ for s := ""; len(s) < n; { s += "x" } }\n', True),+ ("python", "def f(self, items):\n for ch in items:\n self.ch += 'x'\n", True),+ ],+)+def test_string_concat_loop_header_shapes(lang, src, flagged):+ assert (("string_concat_in_loop", "") in _hits(lang, src)) is flagged+++def test_string_concat_onto_counted_loop_init_still_flagged():+ """A counted loop's init carries the string across passes."""+ src = 'class A { void f(int n) { for (String s = ""; s.length() < n; ) { s += "x"; } } }\n'+ assert ("string_concat_in_loop", "") in _hits("java", src)++@pytest.mark.parametrize("lang", ["typescript", "javascript"])@pytest.mark.parametrize("src",