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(perf): drop perf rows that are the recommended idiom or stated intent (#3611)

Raghav Chamadiya47b50dfa4b3d
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.md
index 5425773be..e181fc045 100644
--- a/docs/layers/CODE_HEALTH.md
+++ b/docs/layers/CODE_HEALTH.md
@@ -97,7 +97,8 @@ duplicated code when part of it is a copy.
Left out, and counted with a reason:
-- test files, tooling, generated and vendored code, docs and examples
+- test files, tooling (including Dart's `tool/` scripts), generated and vendored code,
+ docs and examples
- files whose only findings come from git history
- changes that would recover under half a point, and items with no concrete first
edit
diff --git a/docs/layers/PERFORMANCE.md b/docs/layers/PERFORMANCE.md
index 9dd8034ea..bac87665a 100644
--- a/docs/layers/PERFORMANCE.md
+++ b/docs/layers/PERFORMANCE.md
@@ -22,6 +22,17 @@ Performance risk is one of the three signals in [Code Health](CODE_HEALTH.md).
That is 21 performance detectors plus `sql_cartesian_join`. They move only the
performance signal, never the defect score.
+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 this
+finding, because JavaScript engines make repeated `+=` linear.
+
+A TypeScript or JavaScript `includes` check against a short `const` table of
+literals that the file never changes is not flagged, because a table of fixed
+size costs the same at any scale.
+
+An awaited call on a line that an ESLint `no-await-in-loop` suppression covers is
+not reported at all: the comment states that the sequential await is intended.
+
The loop and the I/O call do not have to be in the same function. Repowise
follows the resolved call graph up to three hops and attaches the
caller-to-sink path. Per-function linters cannot see that case.
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/string_concat_in_loop.py b/packages/core/src/repowise/core/analysis/health/biomarkers/string_concat_in_loop.py
index 9f0815875..8d6021ebc 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/string_concat_in_loop.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/string_concat_in_loop.py
@@ -10,10 +10,14 @@ a string literal / template (``s += "..."`` / ``s += f"{x}"`` / ``s += "a" + b``
never an opaque ``s += chunk`` that could be numeric. This detector lifts the
pre-collected hits into findings, except in test files: a test or benchmark that
builds its expected text or input data with ``+=`` is not code anyone speeds up.
+
+One loop's appends to one named string are one edit, so they are one finding:
+it sits on the first append and lists every appended line in ``details["lines"]``.
"""
from __future__ import annotations
+from ..complexity import PerfHit
from ..coverage import is_test_file
from ..models import Severity
from .base import BiomarkerResult, FileContext
@@ -26,24 +30,34 @@ class StringConcatInLoopDetector:
category = "performance"
def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
- out: list[BiomarkerResult] = []
if is_test_file(ctx.file_path):
- return out
- for hit in ctx.perf_hits:
- if hit.kind != _KIND:
- continue
- out.append(
- BiomarkerResult(
- biomarker_type=self.name,
- severity=Severity.LOW,
- function_name=hit.function,
- line_start=hit.line,
- line_end=hit.line,
- details=hit.loop_facts(),
- reason="string built by += in a loop; use a buffer / join for linear cost",
- )
- )
- return out
+ return []
+ groups: dict[tuple[str | None, int, int, str | int], list[PerfHit]] = {}
+ for index, hit in enumerate(ctx.perf_hits):
+ if hit.kind == _KIND:
+ # A target with no quotable name (``buf[i] +=``) is not shown to
+ # be the same string as another one, so it keeps its own row.
+ target = hit.subject or index
+ key = (hit.function, hit.func_start, hit.loop_line or hit.line, target)
+ groups.setdefault(key, []).append(hit)
+ return [self._finding(sorted(hits, key=lambda h: h.line)) for hits in groups.values()]
+
+ def _finding(self, hits: list[PerfHit]) -> BiomarkerResult:
+ first = hits[0]
+ details = first.loop_facts()
+ if len(hits) > 1:
+ details["lines"] = [hit.line for hit in hits]
+ return BiomarkerResult(
+ biomarker_type=self.name,
+ severity=Severity.LOW,
+ function_name=first.function,
+ line_start=first.line,
+ # The first line only: a row with no enclosing symbol is identified
+ # by its absolute lines, and the merged lines are in ``lines``.
+ line_end=first.line,
+ details=details,
+ reason="string built by += in a loop; use a buffer / join for linear cost",
+ )
BIOMARKER = StringConcatInLoopDetector()
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.py
index 6bcf8682e..be9742acc 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
@@ -542,6 +542,13 @@ def _collect_perf_hits(
do_loop_facts = do_chunked or do_magnitude or do_batch or do_bound
do_in_place = _overrides(dialect, "runs_in_place")
+ # An awaited call on a line whose lint suppression says awaiting in this loop
+ # is intended (a retry or a stream read) is not a per-iteration finding.
+ awaits_allowed = (
+ dialect.awaits_in_loop_allowed(root.text or b"")
+ if _overrides(dialect, "awaits_in_loop_allowed")
+ else frozenset()
+ )
def probe(call: Node) -> str | None:
return dialect.call_sink_kind(
@@ -770,7 +777,9 @@ def _collect_perf_hits(
# speaks for it.
pass
elif kind is not None:
- if loop_depth >= 1:
+ if loop_depth >= 1 and chain_awaited and line in awaits_allowed:
+ pass
+ elif loop_depth >= 1:
# The loop's key may feed any link, so the chain's facts are
# read off its outermost call, which holds them all.
facts = loop_facts(chain_top, sink=True, per_call=True)
@@ -865,7 +874,7 @@ def _collect_perf_hits(
subject=root_name if marker == _MEMBERSHIP else "",
)
)
- elif method:
+ elif method and not (awaited and line in awaits_allowed):
# A loop-nested call to a non-sink helper: a candidate
# entry for cross-function reachability (PR4). Keep the
# first line we see the helper called at, for the finding.
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py
index 584ff21d8..b104d1dab 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py
@@ -673,98 +673,6 @@ class BasePerfDialect:
stack.extend(n.children)
return False
- def accumulates_across_iterations(
- self, node: Node, name: bytes, loop_kinds: frozenset[str]
- ) -> bool:
- """True when the ``+=`` at *node* can grow *name* across iterations of
- an enclosing loop in its own function.
-
- The loops are walked from the innermost out. One whose body re-binds
- *name* (:meth:`binds_name`) bounds the growth to a single pass, so
- neither it nor any loop outside it is accumulating. An append directly
- followed by ``return`` / ``throw`` runs once per call, and one followed
- by a ``break`` once per run of the innermost loop: the interrupted-message
- and fallback shapes (``msg += "[interrupted]"; break``). With no loop
- found inside the function the walker's own loop verdict stands.
- """
- exit_kind = self._exit_after(node, loop_kinds)
- if exit_kind not in (None, "break_statement"):
- return False
- loops = self._enclosing_loops(node, loop_kinds)
- if not loops:
- return True
- for depth, loop in enumerate(loops):
- if self._rebinds(loop, node, name, loop_kinds):
- return False
- if depth or exit_kind is None:
- return True
- return False
-
- def _enclosing_loops(self, node: Node, loop_kinds: frozenset[str]) -> list[Node]:
- """The loops around *node* inside its own function, innermost first."""
- loops: list[Node] = []
- cur = node.parent
- while cur is not None and cur.type not in self.scope_kinds:
- if cur.type in loop_kinds:
- loops.append(cur)
- cur = cur.parent
- return loops
-
- def _rebinds(self, loop: Node, append: Node, name: bytes, loop_kinds: frozenset[str]) -> bool:
- """*loop*'s body re-binds *name* whenever *append* runs.
-
- A binding under a branch or a nested loop that does not also hold the
- append (``if (first) s = "head"``) may not run, so it is no reset.
- """
- body = self.loop_body(loop) or loop
- return any(
- self.binds_name(n, name) and self._runs_with(n, append, body, loop_kinds)
- for n in self._walk(body, self.scope_kinds)
- )
-
- def _runs_with(self, node: Node, append: Node, body: Node, loop_kinds: frozenset[str]) -> bool:
- """*node* runs on every pass that runs *append*: climbing from *node*, a
- block holding *append* is reached before any branch or nested loop."""
- cur = node.parent
- while cur is not None and cur != body:
- if cur.type in self.branch_kinds or cur.type in loop_kinds:
- return False
- if self._within(cur, append):
- return True
- cur = cur.parent
- return True
-
- def _exit_after(self, node: Node, loop_kinds: frozenset[str]) -> str | None:
- """The kind of exit statement later in the block of the statement holding
- *node*, or ``None``; a ``break`` that only leaves a ``switch`` is none."""
- parent = node.parent
- stmt = parent if parent is not None and parent.type == "expression_statement" else node
- exit_stmt = self._next_exit(stmt)
- if exit_stmt is None or exit_stmt.type == "continue_statement":
- return None
- if exit_stmt.type == "break_statement" and self._in_switch(stmt, loop_kinds):
- return None
- return exit_stmt.type
-
- def _next_exit(self, stmt: Node) -> Node | None:
- """The first exit statement after *stmt* in its block, unless a statement
- in between can ``continue`` the loop instead."""
- sib = stmt.next_named_sibling
- while sib is not None and sib.type not in self.exit_kinds:
- if any(n.type == "continue_statement" for n in self._walk(sib, self.scope_kinds)):
- return None
- sib = sib.next_named_sibling
- return sib
-
- def _in_switch(self, stmt: Node, loop_kinds: frozenset[str]) -> bool:
- """A ``switch`` sits between *stmt* and its nearest loop."""
- cur = stmt.parent
- while cur is not None and cur.type not in loop_kinds:
- if cur.type in self.switch_kinds:
- return True
- cur = cur.parent
- return False
-
def _rhs_is_stringish(self, node: Node) -> bool:
"""True if an augmented-assignment's RHS is provably string-typed.
@@ -868,6 +776,11 @@ class BasePerfDialect:
"""
return frozenset()
+ def awaits_in_loop_allowed(self, source: bytes) -> frozenset[int]:
+ """1-indexed lines where the source states that awaiting inside a loop is
+ intended (a lint suppression naming that rule). Default: none."""
+ return frozenset()
+
def async_blocking_member(self, node: Node) -> str | None:
"""The offending name if *node* is a non-call member read that blocks
the event loop inside an async function (C# ``task.Result``), else
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js.py
index 26f4d7473..5aeede7ec 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js.py
@@ -70,14 +70,6 @@ TS_SINK_METHODS: frozenset[str] = (
)
)
-_TS_STRING_KINDS: frozenset[str] = frozenset({"string", "template_string"})
-_TS_AUG_ASSIGN_KINDS: frozenset[str] = frozenset({"augmented_assignment_expression"})
-# The walker's TS/JS loop kinds (``complexity.languages``), which cannot be
-# imported here without a cycle through the complexity package.
-_TS_LOOP_KINDS: frozenset[str] = frozenset(
- {"for_statement", "for_in_statement", "for_of_statement", "while_statement", "do_statement"}
-)
-
# A function/lambda scope: the boundary for the reaching-assignment walk and the
# "not a loop exit" skip for break/return/throw inside a nested closure (a
# callback's own ``return`` doesn't exit the loop).
@@ -97,6 +89,48 @@ _PRISMA_BULK_FORMS: dict[str, str] = {
_LIMITER_NAME_RE = re.compile(r"(?i)(sem|semaphore|limiter|limit|mutex)$")
_LIMITER_METHODS: frozenset[str] = frozenset({"runExclusive", "schedule"})
+# ESLint's rule for an ``await`` inside a loop, and its directive comments:
+# ``// eslint-disable-next-line no-await-in-loop -- why`` and friends.
+_AWAIT_IN_LOOP_RULE = "no-await-in-loop"
+_ESLINT_DIRECTIVE_RE = re.compile(
+ rb"(?://|/\*)[ \t]*eslint-(disable-next-line|disable-line|disable|enable)\b([^\r\n]*)"
+)
+
+
+def _directive_rules(tail: bytes) -> set[str]:
+ """Rule names a directive lists, its ``-- reason`` and comment end dropped."""
+ text = tail.decode("utf-8", "replace").split("*/")[0].split("--")[0]
+ return {rule.strip() for rule in text.split(",") if rule.strip()}
+
+
+def _eslint_allowed_lines(source: bytes, rule: str) -> frozenset[int]:
+ """1-indexed lines an ESLint directive naming *rule* switches it off on.
+
+ A directive with no rule list switches off every rule; it says nothing about
+ this one in particular, so it does not count.
+ """
+ lines: set[int] = set()
+ opened: int | None = None
+ for match in _ESLINT_DIRECTIVE_RE.finditer(source):
+ kind = match.group(1)
+ rules = _directive_rules(match.group(2))
+ line = source.count(b"\n", 0, match.start()) + 1
+ if kind == b"enable":
+ if opened is not None and (not rules or rule in rules):
+ lines.update(range(opened, line + 1))
+ opened = None
+ elif rule not in rules:
+ continue
+ elif kind == b"disable-next-line":
+ lines.add(line + 1)
+ elif kind == b"disable-line":
+ lines.add(line)
+ elif opened is None:
+ opened = line
+ if opened is not None:
+ lines.update(range(opened, source.count(b"\n") + 2))
+ return frozenset(lines)
+
_ASSIGNMENT_FIELDS: dict[str, tuple[str, str]] = {
"variable_declarator": ("name", "value"),
"assignment_expression": ("left", "right"),
@@ -288,23 +322,14 @@ def _sole_where_pair(call: Node) -> tuple[Node, Node] | None:
return (key, value) if key is not None and value is not None else None
-def _assigned_value(node: Node, name: bytes) -> Node | None:
- """The value *node* binds to the bare identifier *name*, if it is such a binding."""
- fields = _ASSIGNMENT_FIELDS.get(node.type)
- if fields is None:
- return None
- target, value = (node.child_by_field_name(field) for field in fields)
- if target is None or target.type != "identifier" or target.text != name:
- return None
- return value
-
-
class TsJsPerfDialect(TsJsMarkerHooks, IterableSources):
language = "typescript"
markers = frozenset(
{
"io_in_loop",
- "string_concat_in_loop",
+ # No ``string_concat_in_loop``: every major JS engine (V8, SpiderMonkey,
+ # JavaScriptCore) concatenates through ropes, so ``s += x`` in a loop
+ # is linear and is the idiom, not the problem (as Rust's ``push_str``).
"resource_construction_in_loop",
"serial_await_in_loop",
"membership_test_against_list_in_loop",
@@ -318,8 +343,6 @@ class TsJsPerfDialect(TsJsMarkerHooks, IterableSources):
}
)
- string_literal_kinds = _TS_STRING_KINDS
- aug_assign_kinds = _TS_AUG_ASSIGN_KINDS
switch_kinds = frozenset({"switch_statement"})
# Node's ``child_process`` launchers return a ChildProcess at once and report
# through callbacks or events; only their ``*Sync`` forms wait for the child.
@@ -328,33 +351,16 @@ class TsJsPerfDialect(TsJsMarkerHooks, IterableSources):
# is excluded with them, a recall loss only.
hot_path_excluded_methods = frozenset({"spawn", "exec", "execFile"})
- def is_string_concat(self, node: Node) -> bool:
- """``s += "x"`` that can grow ``s`` across loop iterations.
-
- A ``let`` declared or freshly assigned inside the loop body is bounded
- per pass, and an append right before ``break`` / ``return`` / ``throw``
- runs once. A member or subscript target (``buf[0] += ...``) keeps the
- flag: nothing here re-binds it.
- """
- if not super().is_string_concat(node):
- return False
- left = node.child_by_field_name("left")
- if left is None or left.type != "identifier" or left.text is None:
- return True
- return self.accumulates_across_iterations(node, left.text, _TS_LOOP_KINDS)
-
- def binds_name(self, node: Node, name: bytes) -> bool:
- # ``s = s + part`` keeps accumulating; only a value not built from ``s`` resets it.
- value = _assigned_value(node, name)
- return value is not None and not any(
- n.type == "identifier" and n.text == name for n in self._walk(value)
- )
-
# Only ``for ... of`` / ``for ... in`` multiply over a collection. C-style
# ``for (;;)``, ``while`` and ``do`` are cursors (pagination / polling), so
# they do not make an inner sink a nested O(n*m) round-trip.
_ITERATION_LOOP_KINDS: frozenset[str] = frozenset({"for_in_statement", "for_of_statement"})
+ def awaits_in_loop_allowed(self, source: bytes) -> frozenset[int]:
+ if _AWAIT_IN_LOOP_RULE.encode() not in source:
+ return frozenset()
+ return _eslint_allowed_lines(source, _AWAIT_IN_LOOP_RULE)
+
def is_iteration_loop(self, node: Node) -> bool:
return node.type in self._ITERATION_LOOP_KINDS
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js_markers.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js_markers.py
index 7e19742e9..9ef4d9d05 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js_markers.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js_markers.py
@@ -3,6 +3,7 @@ and client construction inside a loop."""
from __future__ import annotations
+from collections import Counter
from collections.abc import Iterator
from typing import TYPE_CHECKING
@@ -116,6 +117,92 @@ def _is_collection_spread_of(node: Node, name: str) -> bool:
return identifier_name(first_named_child(node)) == name
+# A literal table up to this size is a fixed set; past it a linear probe can
+# still cost enough to be worth a ``Set``. Ceiling: the size is a judgement, not
+# a measurement.
+_FIXED_TABLE_MAX = 64
+_SCALAR_KINDS: frozenset[str] = frozenset({"string", "number", "true", "false", "null"})
+# Array methods that change an array in place; ``sort`` / ``reverse`` / ``fill``
+# keep its length but show the file treats it as data, not a table.
+_MUTATING_METHODS: frozenset[str] = frozenset(
+ {"push", "unshift", "splice", "pop", "shift", "fill", "sort", "reverse", "copyWithin"}
+)
+_ASSIGN_KINDS: frozenset[str] = frozenset(
+ {"assignment_expression", "augmented_assignment_expression"}
+)
+
+
+def _is_fixed_table(declarator: Node, array: Node) -> bool:
+ """``const xs = ['a', 1, `b`]``: a non-empty ``const`` literal of at most
+ ``_FIXED_TABLE_MAX`` scalars. An empty literal is a container filled later.
+
+ The TS twin of the Python dialect's ``_fixed_set``.
+ """
+ decl = declarator.parent
+ if decl is None or decl.type != "lexical_declaration" or decl.children[0].type != "const":
+ return False
+ items = [c for c in array.children if c.is_named and c.type != "comment"]
+ return 0 < len(items) <= _FIXED_TABLE_MAX and all(_is_scalar(item) for item in items)
+
+
+def _is_scalar(item: Node) -> bool:
+ if item.type == "template_string":
+ return not any(c.type == "template_substitution" for c in item.children)
+ return item.type in _SCALAR_KINDS
+
+
+def _changed_arrays(node: Node) -> list[str]:
+ """Names *node* may change: ``xs.push(...)`` and the other mutating methods,
+ ``xs[i] = v`` / ``xs.length = 0``, and ``xs`` handed to a call (the callee
+ may change it)."""
+ if node.type in _ASSIGN_KINDS:
+ left = node.child_by_field_name("left")
+ if left is not None and left.type in ("subscript_expression", "member_expression"):
+ return [n for n in (identifier_name(left.child_by_field_name("object")),) if n]
+ return []
+ if node.type != "call_expression":
+ return []
+ names: list[str] = []
+ fn = node.child_by_field_name("function")
+ if fn is not None and fn.type == "member_expression":
+ method = node_text(fn.child_by_field_name("property"))
+ name = identifier_name(fn.child_by_field_name("object"))
+ if name is not None and method in _MUTATING_METHODS:
+ names.append(name)
+ args = node.child_by_field_name("arguments")
+ if args is not None:
+ names.extend(n for c in args.children if (n := identifier_name(c)) is not None)
+ return names
+
+
+# Nodes that bind the names under them (or under the named field).
+_BINDING_FIELDS: dict[str, str | None] = {
+ "variable_declarator": "name",
+ "formal_parameters": None,
+ "catch_clause": "parameter",
+ "arrow_function": "parameter",
+}
+
+
+def _declared_names(node: Node) -> list[str]:
+ """Identifiers *node* declares: a variable (plain or destructured), a
+ parameter list, a catch binding or a bare arrow parameter. A default value
+ inside a parameter list over-counts, which only keeps a table unfixed."""
+ if node.type not in _BINDING_FIELDS:
+ return []
+ field = _BINDING_FIELDS[node.type]
+ target = node.child_by_field_name(field) if field else node
+ if target is None:
+ return []
+ stack, names = [target], []
+ while stack:
+ cur = stack.pop()
+ if cur.type in ("identifier", "shorthand_property_identifier_pattern"):
+ names.extend(n for n in (node_text(cur),) if n)
+ stack.extend(cur.children)
+ return names
+
+
class TsJsMarkerHooks(BasePerfDialect):
def loop_call_marker(
self, root: str, method: str, node: Node, list_names: frozenset[str]
@@ -149,13 +236,29 @@ class TsJsMarkerHooks(BasePerfDialect):
return None
def list_bound_names(self, root: Node) -> frozenset[str]:
- """Names bound to an array literal (``const arr = [...]``)."""
+ """Names bound to an array literal (``const arr = [...]``), less fixed tables.
+
+ A ``const`` bound to a short literal of scalars that the file never
+ changes or hands to a call (``const booleanAttributes = ['async',
+ 'checked', ...]``) has a fixed length, so a probe per iteration is not
+ the O(n·m) the marker means.
+ """
names: set[str] = set()
+ fixed: set[str] = set()
+ changed: set[str] = set()
+ declared: Counter[str] = Counter()
for n in self._walk(root):
+ declared.update(_declared_names(n))
+ if n.type == "call_expression" or n.type in _ASSIGN_KINDS:
+ changed.update(_changed_arrays(n))
+ continue
if n.type != "variable_declarator":
continue
name = identifier_name(n.child_by_field_name("name"))
value = n.child_by_field_name("value")
if name is not None and value is not None and value.type == "array":
- names.add(name)
- return frozenset(names)
+ (fixed if _is_fixed_table(n, value) else names).add(name)
+ # A name the file binds again (a parameter, a local) may not be the table
+ # at a given probe; scope is not resolved, so such a table is not fixed.
+ reused = {name for name in fixed if declared[name] > 1}
+ return frozenset(names | (fixed & (changed | reused)))
diff --git a/packages/core/src/repowise/core/code_origin.py b/packages/core/src/repowise/core/code_origin.py
index 971b11844..fdf089745 100644
--- a/packages/core/src/repowise/core/code_origin.py
+++ b/packages/core/src/repowise/core/code_origin.py
@@ -663,6 +663,12 @@ _TOOLING_STEM_SUFFIXES = ("_benchmark", "_benchmarks")
_TOOLING_NAME_RE = re.compile(
r"^(?:eslint\.config|jest\.config|vitest\.config|babel\.config|karma\.conf)\.[cm]?[jt]s$"
)
+# Dart's package layout keeps private scripts in ``tool/`` beside ``lib/``. A bare
+# ``tool`` is shipped code elsewhere (Go's ``internal/tool``), so it counts only
+# for Dart files, and not once it sits under a package's shipped ``lib``/``bin``/
+# ``web``. Ceiling: path-only, so a ``tool/`` not at a package root also counts.
+_DART_TOOL_DIR = "tool"
+_DART_SHIPPED_DIRS = frozenset({"lib", "bin", "web"})
def _header_text(text: str | bytes | None) -> str:
@@ -728,9 +734,16 @@ def _is_tooling(name: str, dirs: list[str]) -> bool:
or (not dirs and name in _TOOLING_ROOT_NAMES)
or bool(_TOOLING_NAME_RE.match(name.lower()))
or _is_benchmark_file(name)
+ or _is_dart_tool(name, dirs)
)
+def _is_dart_tool(name: str, dirs: list[str]) -> bool:
+ if not name.lower().endswith(".dart") or _DART_TOOL_DIR not in dirs:
+ return False
+ return _DART_SHIPPED_DIRS.isdisjoint(dirs[: dirs.index(_DART_TOOL_DIR)])
+
+
def _is_benchmark_file(name: str) -> bool:
lowered = name.lower()
return lowered.endswith(_code_suffixes()) and PurePosixPath(lowered).stem.endswith(
diff --git a/tests/unit/health/test_perf_dialects.py b/tests/unit/health/test_perf_dialects.py
index 98531bec5..7fdb83c0c 100644
--- a/tests/unit/health/test_perf_dialects.py
+++ b/tests/unit/health/test_perf_dialects.py
@@ -580,65 +580,20 @@ def test_python_string_concat_reset_per_iteration_not_flagged():
assert ("string_concat_in_loop", "") in _hits("python", accum)
-def _ts_concat_lines(src: str) -> list[int]:
- fc = walk_file("t.ts", "typescript", src.encode())
- return [h.line for h in fc.perf_hits if h.kind == "string_concat_in_loop"]
-
-
- "src",
- [
- # Declared fresh each pass: bounded per iteration.
- "function f(fs){ for (const f of fs){ let js = read(f);\n js += '\\n//map'; write(f, js) } }",
- # Declared in the same branch that appends: fresh whenever the append runs.
- "function f(fs){ for (const f of fs){ if (ok(f)) { let js = read(f); js += '//map'; write(js) } } }",
- # Reset by a plain assignment inside the loop.
- "function f(rs){ let v; for (const r of rs){ v = r.style; v += ';'; use(v) } }",
- # Appended once, right before leaving the loop or the function.
- "function f(s){ let m=''; for (const c of s){ if (c.stop) { m += ' [cut]'; break } } return m }",
- "function f(xs){ let m=''; for (const x of xs){ if (x.bad) { m += 'bad'; return m } } }",
- "function f(xs){ let m='e:'; for (const x of xs){ if (x.bad) { m += 'bad'; throw new Error(m) } } }",
- # The break leaves the inner loop and the outer loop re-binds the name.
- "function f(ys){ for (const y of ys){ let s=''; while (more()){ s += 'a'; break } use(s) } }",
- ],
-)
-def test_ts_string_concat_bounded_per_iteration_not_flagged(src):
- assert _ts_concat_lines(src) == []
-
-
[email protected]("lang", ["typescript", "javascript"])
@pytest.mark.parametrize(
"src",
[
"function f(xs){ let s=''; for (const x of xs){ s += `${x}\\n` } return s }",
- # A re-bind that only some passes run is no reset.
- "function f(xs){ let s=''; for (const x of xs){ if (x.first) { s = 'head' } s += `${x}` } return s }",
- "function f(xs){ let s=''; for (const x of xs){ for (const y of x){ s = y } s += 'a' } return s }",
- # ``s = s + ...`` keeps the old value, so it is no reset.
- "function f(xs){ let s=''; for (const x of xs){ s = s + 'a'; s += 'b' } return s }",
- # A break that only leaves a switch, or only the inner of two loops.
- "function f(xs){ let s=''; for (const x of xs){ switch (x.k) { case 1: s += 'a'; break } } return s }",
- "function f(ys){ let s=''; for (const y of ys){ for (const x of y){ s += 'a'; break } } return s }",
- # Declared in the outer loop, grown across the inner one.
- "function f(ys){ for (const y of ys){ let s=''; for (const x of y){ s += 'a' } use(s) } }",
- # A path to ``continue`` before the exit keeps the loop going.
- "function f(xs){ let s=''; for (const x of xs){ s += 'a'; if (x) continue; break } return s }",
- # A subscript target is never re-bound by a declaration.
- "function f(xs, buf){ for (const x of xs){ buf[0] += ` ${x}` } }",
+ # hono ``toStringToBuffer``: appends into the string a buffer array holds.
+ "function f(props, buffer){ for (const [k, v] of props){\n"
+ " buffer[0] += ` ${k}=\"`\n escape(v, buffer)\n buffer[0] += '\"' } }",
],
)
-def test_ts_string_concat_across_iterations_still_flagged(src):
- assert len(_ts_concat_lines(src)) == 1
-
-
-def test_ts_string_concat_loop_local_and_accumulator_in_one_loop():
- src = (
- "function f(xs){ let out='';\n"
- " for (const x of xs){ let v = x.name;\n"
- " v += ';';\n"
- " out += `${v}`; }\n"
- " return out }"
- )
- assert _ts_concat_lines(src) == [4]
+def test_js_string_concat_is_never_a_marker(lang, src):
+ """JS engines concatenate through ropes, so ``+=`` in a loop is linear."""
+ fc = walk_file("t.ts", lang, src.encode())
+ assert not any(h.kind == "string_concat_in_loop" for h in fc.perf_hits)
def test_ts_nested_io_requires_collection_outer_loop():
diff --git a/tests/unit/health/test_perf_io_in_loop.py b/tests/unit/health/test_perf_io_in_loop.py
index cf77fd8b6..009e2bd10 100644
--- a/tests/unit/health/test_perf_io_in_loop.py
+++ b/tests/unit/health/test_perf_io_in_loop.py
@@ -535,6 +535,50 @@ def test_string_concat_not_reported_in_test_files(path, expected):
assert len(StringConcatInLoopDetector().detect(ctx)) == expected
+def test_string_concat_one_finding_per_loop_and_string():
+ """A loop's appends to one string are one edit, so one finding on the first."""
+ ctx = _ctx(
+ [
+ PerfHit("string_concat_in_loop", 9, "f", "", 3, loop_line=7, subject="out"),
+ PerfHit("string_concat_in_loop", 8, "f", "", 3, loop_line=7, subject="out"),
+ PerfHit("string_concat_in_loop", 12, "f", "", 3, loop_line=7, subject="out"),
+ # Another string in the same loop, and the same string in another loop.
+ PerfHit("string_concat_in_loop", 10, "f", "", 3, loop_line=7, subject="log"),
+ PerfHit("string_concat_in_loop", 15, "f", "", 3, loop_line=14, subject="out"),
+ ]
+ )
+ findings = sorted(StringConcatInLoopDetector().detect(ctx), key=lambda f: f.line_start)
+ # ``line_end`` stays on the first append, so an unanchored row's id is stable.
+ assert [(f.line_start, f.line_end) for f in findings] == [(8, 8), (10, 10), (15, 15)]
+ assert findings[0].details["lines"] == [8, 9, 12]
+ assert "lines" not in findings[1].details
+
+
+def test_string_concat_unnamed_targets_in_one_loop_stay_apart():
+ """``buf[0] +=`` and ``other[i] +=`` keep no name, so nothing says they are one string."""
+ ctx = _ctx(
+ [
+ PerfHit("string_concat_in_loop", 8, "f", "", 3, loop_line=7),
+ PerfHit("string_concat_in_loop", 9, "f", "", 3, loop_line=7),
+ PerfHit("string_concat_in_loop", 10, "f", "", 3, loop_line=7, subject="self.a"),
+ PerfHit("string_concat_in_loop", 11, "f", "", 3, loop_line=7, subject="self.b"),
+ ]
+ )
+ findings = StringConcatInLoopDetector().detect(ctx)
+ assert sorted(f.line_start for f in findings) == [8, 9, 10, 11]
+
+
+def test_string_concat_unnamed_targets_on_one_line_stay_apart():
+ """``a[0] += x; b[0] += y`` on one line: two unnamed targets, two findings."""
+ ctx = _ctx(
+ [
+ PerfHit("string_concat_in_loop", 8, "f", "", 3, loop_line=7),
+ PerfHit("string_concat_in_loop", 8, "f", "", 3, loop_line=7),
+ ]
+ )
+ assert len(StringConcatInLoopDetector().detect(ctx)) == 2
+
+
def test_no_perf_hits_yields_no_findings():
assert IoInLoopDetector().detect(_ctx([])) == []
diff --git a/tests/unit/health/test_perf_lint_suppression.py b/tests/unit/health/test_perf_lint_suppression.py
new file mode 100644
index 000000000..0dcc01998
--- /dev/null
+++ b/tests/unit/health/test_perf_lint_suppression.py
@@ -0,0 +1,99 @@
+"""An ESLint ``no-await-in-loop`` suppression states that awaiting in that loop is intended.
+
+ky ``Ky.#run`` retries a request in a loop, each retry awaited under
+``// eslint-disable-next-line no-await-in-loop``; the loop was reported as
+I/O per iteration through ``#retryFromError -> #retry -> #fetch``.
+"""
+
+from __future__ import annotations
+
+from repowise.core.analysis.health.complexity import walk_file
+from repowise.core.analysis.health.perf.dialects.ts_js import _eslint_allowed_lines
+
+_RULE = "no-await-in-loop"
+
+
+def _hits(src: str) -> list[tuple[str, int]]:
+ return sorted((h.kind, h.line) for h in walk_file("t.ts", "typescript", src.encode()).perf_hits)
+
+
+def test_directive_lines():
+ src = (
+ b"a\n"
+ b"// eslint-disable-next-line no-await-in-loop -- retries are sequential\n"
+ b"c\n"
+ b"d // eslint-disable-line no-await-in-loop\n"
+ b"/* eslint-disable no-await-in-loop */\n"
+ b"f\n"
+ b"/* eslint-enable no-await-in-loop */\n"
+ b"h\n"
+ b"// eslint-disable-next-line no-console\n"
+ b"j\n"
+ b"// eslint-disable-next-line\n"
+ b"l\n"
+ b"// eslint-disable-next-line no-console, no-await-in-loop\n"
+ b"n\n"
+ )
+ assert sorted(_eslint_allowed_lines(src, _RULE)) == [3, 4, 5, 6, 7, 14]
+
+
+def test_unclosed_disable_runs_to_the_end():
+ assert sorted(_eslint_allowed_lines(b"a\n/* eslint-disable no-await-in-loop */\nc\nd", _RULE)) == [
+ 2,
+ 3,
+ 4,
+ ]
+
+
+_LOOP = (
+ "import axios from 'axios'\n"
+ "async function f(urls, paths){\n"
+ " for (const u of urls){\n"
+ " {directive}\n"
+ " await axios.get(u)\n"
+ " }\n"
+ "}\n"
+)
+
+
+def test_suppressed_await_is_not_a_finding():
+ src = _LOOP.replace("{directive}", "// eslint-disable-next-line no-await-in-loop")
+ assert _hits(src) == []
+
+
+def test_other_rules_and_blanket_suppressions_do_not_count():
+ for directive in ("// eslint-disable-next-line no-console", "// eslint-disable-next-line"):
+ src = _LOOP.replace("{directive}", directive)
+ assert _hits(src) == [("io_in_loop", 5), ("serial_await_in_loop", 5)], directive
+
+
+def test_suppression_covers_only_its_line():
+ src = (
+ "import axios from 'axios'\n"
+ "async function f(urls){\n"
+ " for (const u of urls){\n"
+ " // eslint-disable-next-line no-await-in-loop\n"
+ " await axios.get(u)\n"
+ " await axios.post(u)\n"
+ " }\n"
+ "}\n"
+ )
+ assert _hits(src) == [("io_in_loop", 6), ("serial_await_in_loop", 6)]
+
+
+def test_suppressed_awaited_helper_is_not_a_loop_call_target():
+ src = (
+ "class Ky {\n"
+ " async run(){\n"
+ " for (;;){\n"
+ " // eslint-disable-next-line no-await-in-loop\n"
+ " response = await this.retryFromError(error)\n"
+ " log(response)\n"
+ " }\n"
+ " }\n"
+ "}\n"
+ )
+ facts = walk_file("t.ts", "typescript", src.encode()).perf_fn_facts
+ targets = {name for f in facts for name, _ in f.loop_call_targets}
+ assert "retryFromError" not in targets
+ assert "log" in targets
diff --git a/tests/unit/health/test_perf_phase7a.py b/tests/unit/health/test_perf_phase7a.py
index dbd95754b..43b0b76a3 100644
--- a/tests/unit/health/test_perf_phase7a.py
+++ b/tests/unit/health/test_perf_phase7a.py
@@ -235,11 +235,74 @@ _MEMBERSHIP_CASES = [
),
(
"typescript",
- "function f(items){ const big = [1,2,3]; "
- "for (const x of items){ if (big.includes(x)) use(x); } }",
+ "function f(items){ const big = []; "
+ "for (const x of items){ if (!big.includes(x)) big.push(x); } }",
[("membership_test_against_list_in_loop", "")],
"big.includes(x) where big is an array literal",
),
+ (
+ "typescript",
+ # hono ``src/jsx/base.ts``: a module table of attribute names.
+ "export const booleanAttributes = ['async', 'checked', 'disabled', `open`];\n"
+ "function f(props){ for (const [k, v] of props){ "
+ "if (typeof v === 'boolean' && booleanAttributes.includes(k)) use(k); } }",
+ [],
+ "a short const literal table is a fixed set",
+ ),
+ (
+ "typescript",
+ "const big = ['a', 'b'];\nbig.push(read());\n"
+ "function f(items){ for (const x of items){ if (big.includes(x)) use(x); } }",
+ [("membership_test_against_list_in_loop", "")],
+ "a literal table the file grows is still a list",
+ ),
+ *(
+ (
+ "typescript",
+ f"const big = ['a', 'b'];\n{change}\n"
+ "function f(items){ for (const x of items){ if (big.includes(x)) use(x); } }",
+ [("membership_test_against_list_in_loop", "")],
+ f"a literal table the file changes is still a list: {change}",
+ )
+ for change in (
+ "big[2] = read();",
+ "big.length = 0;",
+ "big.fill('c');",
+ "big.sort();",
+ "big.reverse();",
+ "load(big);",
+ )
+ ),
+ *(
+ (
+ "typescript",
+ f"const big = ['a', 'b'];\n{fn}",
+ [("membership_test_against_list_in_loop", "")],
+ f"a table name the file binds again may be another array: {fn}",
+ )
+ for fn in (
+ "function f(big, ys){ for (const y of ys){ if (big.includes(y)) use(y); } }",
+ "function f(ys){ let big = load(); for (const y of ys){ if (big.includes(y)) use(y); } }",
+ "function f(ys){ try { g() } catch (big) {} "
+ "for (const y of ys){ if (big.includes(y)) use(y); } }",
+ "const f = ({ big }, ys) => { for (const y of ys){ if (big.includes(y)) use(y); } }",
+ "const f = big => { for (const y of ys){ if (big.includes(y)) use(y); } }",
+ )
+ ),
+ (
+ "typescript",
+ "let big = ['a', 'b'];\n"
+ "function f(items){ for (const x of items){ if (big.includes(x)) use(x); } }",
+ [("membership_test_against_list_in_loop", "")],
+ "a let-bound literal can be replaced, so it is no fixed table",
+ ),
+ (
+ "typescript",
+ "const big = [" + ", ".join(["'x'"] * 65) + "];\n"
+ "function f(items){ for (const x of items){ if (big.includes(x)) use(x); } }",
+ [("membership_test_against_list_in_loop", "")],
+ "a literal table past the size cap still flags",
+ ),
(
"typescript",
"function f(items){ const big = new Set(); "
diff --git a/tests/unit/health/test_perf_plan_steps_per_loop.py b/tests/unit/health/test_perf_plan_steps_per_loop.py
index 8874246ce..0c22fc1af 100644
--- a/tests/unit/health/test_perf_plan_steps_per_loop.py
+++ b/tests/unit/health/test_perf_plan_steps_per_loop.py
@@ -260,26 +260,22 @@ def test_python_records_the_string_and_the_list():
]
-def test_typescript_records_the_string_and_the_array():
+def test_typescript_records_the_array():
source = (
"export function f(rows: string[]) {\n"
" let out = '';\n"
- " const big = [1, 2, 3];\n"
+ " const big = [];\n"
" for (const r of rows) {\n"
" out += 'a';\n"
- " this.buf += 'b';\n"
" if (big.includes(r)) { out += 'c'; }\n"
+ " big.push(r);\n"
" }\n"
" return out;\n"
"}\n"
)
- assert _subjects("a.ts", "typescript", source) == [
- (_CONCAT, 5, "out"),
- (_CONCAT, 6, "this.buf"),
- (_PROBE, 7, "big"),
- (_CONCAT, 7, "out"),
- ]
+ # JS ``+=`` is linear (ropes), so only the probe is a hit.
+ assert _subjects("a.ts", "typescript", source) == [(_PROBE, 6, "big")]
@pytest.mark.parametrize(
diff --git a/tests/unit/test_code_origin.py b/tests/unit/test_code_origin.py
index 442663e0e..fce438dc4 100644
--- a/tests/unit/test_code_origin.py
+++ b/tests/unit/test_code_origin.py
@@ -71,6 +71,15 @@ _OWN_HEADER = (
("scripts/release.py", "tooling"),
(".github/scripts/label.js", "tooling"),
("tools/gen.go", "tooling"),
+ # Dart's ``tool/`` (flutter samples' CI scripts), but not a shipped one.
+ ("tool/ci_script.dart", "tooling"),
+ ("desktop_photo_search/material/tool/grind.dart", "tooling"),
+ ("lib/src/tool/picker.dart", "production"),
+ ("lib/tool/picker.dart", "production"),
+ ("bin/tool/run.dart", "production"),
+ ("packages/app/lib/tool/picker.dart", "production"),
+ ("src/cmd/go/internal/tool/tool.go", "production"),
+ ("tool/release.py", "production"),
("benchmarks/bench_app.py", "tooling"),
("app/migrations/0001_initial.py", "tooling"),
("db/alembic/versions/abc_add.py", "tooling"),