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
feat(perf): say whether Rust, Kotlin and C++ perf loops grow with the data (#3515)
Raghav Chamadiya1a7e10acab28
diff --git a/docs/layers/PERFORMANCE.md b/docs/layers/PERFORMANCE.mdindex c2ee6f5bd..f6269224a 100644--- a/docs/layers/PERFORMANCE.md+++ b/docs/layers/PERFORMANCE.md@@ -60,7 +60,7 @@ graph and the import graph. An opportunity with a supported shared fix links toEach loop also says what it walks: rows a query returns, a collection its callerpasses in, the rows of one key, a registry or configuration table, a fixed set, adirectory listing or a stream, and plan steps name it. Python, TypeScript/JavaScript,-Go, Java, C# and Ruby loops say whether they grow with the data or are bounded; a+Go, Java, C#, Ruby, Rust, Kotlin and C++ loops say whether they grow with the data or are bounded; aloop whose size the code does not show stays unknown and is never treated asbounded. A loop that stops at the first call that answers, or feeds each call'sresult into the next, gets no batch advice (reason `loop_not_batchable`).diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/cpp.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/cpp.pyindex b7e2f590c..dd5d75078 100644--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/cpp.py+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/cpp.py@@ -44,6 +44,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGfrom .base import BasePerfDialect+from .iterables import IterableSources, text_of, upper_boundif TYPE_CHECKING:from collections.abc import Iterable, Iterator@@ -439,7 +440,119 @@ def _declaration_has_initializer(node: Node) -> bool:return False-class CppPerfDialect(BasePerfDialect):+_CPP_FN_KINDS: frozenset[str] = frozenset({"function_definition", "lambda_expression"})+# ``while ((row = mysql_fetch_row(res)))``: a row cursor over the result set it is passed.+_ROW_CURSORS: frozenset[str] = frozenset({"mysql_fetch_row", "PQgetResult"})+_DECLARATORS: frozenset[str] = frozenset(+ {"array_declarator", "reference_declarator", "pointer_declarator", "init_declarator"}+)+++def _declared_name(node: Node | None) -> bytes | None:+ """``x`` of ``x`` / ``x[4]`` / ``&x`` / ``*x`` / ``x = v`` (a member's ``x`` too)."""+ while node is not None and node.type in _DECLARATORS:+ node = node.child_by_field_name("declarator") or next(+ (c for c in node.named_children if c.type == "identifier"), None+ )+ named = node is not None and node.type in ("identifier", "field_identifier")+ return node.text if named else None+++def _std_array(node: Node | None) -> bool:+ """``std::array<T, 4>`` / ``array<T, 4>``: a size fixed in the type."""+ if node is not None and node.type == "qualified_identifier":+ if text_of(node.child_by_field_name("scope")) != "std":+ return False+ node = node.child_by_field_name("name")+ if node is None or node.type != "template_type":+ return False+ args = node.child_by_field_name("arguments")+ if args is None or text_of(node.child_by_field_name("name")) != "array":+ return False+ return any(arg.type == "number_literal" for arg in args.named_children)+++def _cpp_bindings(node: Node) -> list[tuple[bytes, Node]]:+ """What *node* binds: ``T x = v`` / ``T x{a, b}`` (the value), ``T x[16]``+ (the declarator), ``std::array<T, 4> x`` (the type), ``x = v``, or+ ``sqlite3_prepare_v2(db, sql, n, &x, ..)`` (the call). A null pointer binds+ nothing: the statement that fills it does."""+ if node.type == "declaration":+ return _declared_values(node)+ if node.type == "assignment_expression":+ left, op = node.child_by_field_name("left"), node.child_by_field_name("operator")+ right = node.child_by_field_name("right")+ plain = left is not None and op is not None and op.type == "=" and right is not None+ return [(left.text, right)] if plain and left.type == "identifier" and left.text else []+ return _prepared_into(node) if node.type == "call_expression" else []+++def _prepared_into(call: Node) -> list[tuple[bytes, Node]]:+ """``stmt`` of ``sqlite3_prepare_v2(db, sql, n, &stmt, ..)``, bound to the call."""+ args = call.child_by_field_name("arguments")+ if args is None or not _callee_name(call).startswith("sqlite3_prepare"):+ return []+ out = [a.child_by_field_name("argument") for a in args.named_children]+ return [(a.text, call) for a in out if a is not None and a.type == "identifier" and a.text]+++def _declared_values(node: Node) -> list[tuple[bytes, Node]]:+ found: list[tuple[bytes, Node]] = []+ ty = node.child_by_field_name("type")+ for decl in node.children_by_field_name("declarator"):+ name = _declared_name(decl)+ if name is None:+ continue+ if decl.type == "init_declarator":+ value = decl.child_by_field_name("value")+ if value is not None and value.type != "null" and value.text != b"NULL":+ found.append((name, value))+ elif decl.type == "array_declarator":+ found.append((name, decl))+ elif _std_array(ty):+ found.append((name, ty))+ return found+++def _fixed_decl(node: Node) -> bool:+ """A file-level ``const`` / ``constexpr`` declaration, or an array of one."""+ qualified = any(c.type == "type_qualifier" for c in node.children)+ return qualified or any(_declared_array(d) for d in node.children_by_field_name("declarator"))+++def _declared_array(node: Node | None) -> bool:+ while node is not None and node.type in ("init_declarator", "reference_declarator", "pointer_declarator"):+ node = node.child_by_field_name("declarator")+ return node is not None and node.type == "array_declarator"+++def _end_of(cond: Node | None) -> Node | None:+ """``xs`` of an iterator loop's ``it != xs.end()``."""+ if cond is None or cond.type != "binary_expression":+ return None+ op, right = cond.child_by_field_name("operator"), cond.child_by_field_name("right")+ if op is None or op.type != "!=" or right is None or right.type != "call_expression":+ return None+ fn = right.child_by_field_name("function")+ if fn is None or fn.type != "field_expression":+ return None+ field = text_of(fn.child_by_field_name("field"))+ return fn.child_by_field_name("argument") if field in ("end", "cend") else None+++def _row_test(cond: Node | None) -> Node | None:+ """The call a ``while`` tests: ``f(..)``, ``f(..) == ROW``, ``(row = f(..))``."""+ while cond is not None and cond.type in ("condition_clause", "parenthesized_expression"):+ inner = cond.child_by_field_name("value")+ cond = inner if inner is not None else next(iter(cond.named_children), None)+ if cond is not None and cond.type == "binary_expression":+ cond = cond.child_by_field_name("left")+ if cond is not None and cond.type == "assignment_expression":+ cond = cond.child_by_field_name("right")+ return cond if cond is not None and cond.type == "call_expression" else None+++class CppPerfDialect(IterableSources):language = "cpp"markers = frozenset({@@ -624,6 +737,137 @@ class CppPerfDialect(BasePerfDialect):return "lock_in_loop"return None+ # -- what a loop walks (perf/dialects/iterables.py) ---------------------------++ function_kinds = _CPP_FN_KINDS+ file_container_kinds = frozenset({"namespace_definition"})+ member_scope_kinds = frozenset({"class_specifier", "struct_specifier", "union_specifier"})++ int_kinds = frozenset({"number_literal"})+ wrapper_kinds = frozenset({"parenthesized_expression", "pointer_expression"})+ size_names = frozenset({"size", "length", "ssize", "ABSL_ARRAYSIZE", "arraysize"})+ # ``while (rs->next())`` (a SQL connector's result set).+ cursor_advances = frozenset({"next"})+ listings = frozenset({"directory_iterator", "recursive_directory_iterator"})+ recursive_listings = frozenset({"recursive_directory_iterator"})+ streams = frozenset({"getline"})+ member_kinds = frozenset({"field_expression"})+ change_kinds = frozenset({"assignment_expression", "update_expression"})+ grow_methods = frozenset(+ {+ "push_back", "emplace_back", "emplace", "push_front", "emplace_front", "insert",+ "resize", "assign", "append",+ }+ )+ conditional_kinds = frozenset(+ {+ "if_statement", "else_clause", "switch_statement", "case_statement", "for_statement",+ "for_range_loop", "while_statement", "do_statement", "try_statement", "catch_clause",+ "conditional_expression",+ }+ )++ def loop_header(self, loop: Node) -> tuple[str, Node | None]:+ if loop.type == "for_range_loop":+ return "each", loop.child_by_field_name("right")+ cond = loop.child_by_field_name("condition")+ end = _end_of(cond)+ if end is not None:+ return "each", end+ if loop.type == "for_statement":+ return "counted", upper_bound(cond)+ call = _row_test(cond)+ parts = self.call_parts(call) if call is not None else None+ if parts is None:+ return "each", None+ method, _receiver, args = parts+ if method in _ROW_CURSORS:+ return "each", args[0] if args else None+ # ``sqlite3_step(stmt)`` is the read itself; ``getline(in, s)`` reads a stream.+ if method in DB_FUNCTIONS or method in self.streams:+ return "each", call+ return "cursor", call++ def is_literal(self, node: Node) -> bool:+ """``{a, b}``, ``T x[16]`` and ``std::array<T, 4>``; not ``{args...}``."""+ if node.type == "initializer_list":+ entries = [c for c in node.named_children if c.type != "comment"]+ return bool(entries) and not any(c.type == "parameter_pack_expansion" for c in entries)+ if node.type == "array_declarator":+ size = node.child_by_field_name("size")+ return size is not None and size.type in self.int_kinds+ return _std_array(node)++ def call_parts(self, node: Node) -> tuple[str, Node | None, list[Node]] | None:+ if node.type != "call_expression":+ return None+ fn = node.child_by_field_name("function")+ args = node.child_by_field_name("arguments")+ arg_nodes = [c for c in args.named_children if c.type != "comment"] if args else []+ if fn is not None and fn.type == "field_expression":+ field, obj = fn.child_by_field_name("field"), fn.child_by_field_name("argument")+ return text_of(field), obj, arg_nodes+ # ``std::size(xs)``: a namespace is not a receiver.+ while fn is not None and fn.type in ("qualified_identifier", "template_function"):+ fn = fn.child_by_field_name("name")+ return text_of(fn), None, arg_nodes++ def member_parts(self, node: Node) -> tuple[str, Node] | None:+ obj = node.child_by_field_name("argument") if node.type == "field_expression" else None+ return (text_of(node.child_by_field_name("field")), obj) if obj is not None else None++ def bindings_of(self, node: Node) -> list[tuple[bytes, Node]]:+ return _cpp_bindings(node)++ def declared_names(self, node: Node) -> list[bytes]:+ """Every name a declaration, parameter or range-for declares, initialised or not."""+ if node.type in ("declaration", "parameter_declaration", "optional_parameter_declaration"):+ names = (_declared_name(d) for d in node.children_by_field_name("declarator"))+ return [name for name in names if name]+ if node.type == "for_range_loop":+ decl = node.child_by_field_name("declarator")+ return [n.text for n in self._walk(decl) if n.type == "identifier" and n.text] if decl else []+ return []++ def escaped_names(self, node: Node) -> list[bytes]:+ """``v`` of ``fill(v)`` / ``fill(&v)``: the callee may take it by reference."""+ parts = self.call_parts(node)+ names: list[bytes] = []+ for arg in parts[2] if parts is not None else []:+ if arg.type == "pointer_expression":+ arg = arg.child_by_field_name("argument") or arg+ if arg.type == "identifier" and arg.text:+ names.append(arg.text)+ return names++ def file_bindings_of(self, item: Node) -> list[tuple[bytes, Node]]:+ """A namespace-level ``const`` / ``constexpr`` or array."""+ return _declared_values(item) if item.type == "declaration" and _fixed_decl(item) else []++ def member_names(self, owner: Node) -> set[bytes]:+ """Fields a method defined in the class body reads bare. Ceiling: a method+ defined out of line (``void A::f()``) is not inside its class here."""+ body = owner.child_by_field_name("body")+ fields = [c for c in body.named_children if c.type == "field_declaration"] if body else []+ return {+ name+ for member in fields+ for decl in member.children_by_field_name("declarator")+ if (name := _declared_name(decl))+ }++ def param_names(self, loop: Node) -> set[bytes]:+ scope = self._scope(loop)+ decl = scope.child_by_field_name("declarator") if scope is not None else None+ while decl is not None and decl.child_by_field_name("parameters") is None:+ decl = decl.child_by_field_name("declarator")+ params = decl.child_by_field_name("parameters") if decl is not None else None+ return {+ name+ for param in (params.named_children if params is not None else ())+ if (name := _declared_name(param.child_by_field_name("declarator")))+ }+@staticmethoddef _has_literal_pattern(node: Node) -> bool:"""True when the construction's first argument is a compile-time stringdiff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/iterables.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/iterables.pyindex 76f7ef396..0af43c283 100644--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/iterables.py+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/iterables.py@@ -36,6 +36,31 @@ def text_of(node: Node | None) -> str:return (node.text or b"").decode("utf-8", "replace") if node is not None else ""+# The reading recurses once per link of a header's call chain; a header nested+# deeper than this (a generated chain hundreds of calls long) stays unknown.+_MAX_HEADER_DEPTH = 120+++def _deeper_than(node: Node, limit: int) -> bool:+ stack = [(node, 0)]+ while stack:+ cur, depth = stack.pop()+ if depth > limit:+ return True+ stack.extend((child, depth + 1) for child in cur.children)+ return False+++def _root(node: Node) -> Node:+ while node.parent is not None:+ node = node.parent+ return node+++def _same_node(a: Node, b: Node) -> bool:+ return (a.id, a.start_byte, a.end_byte) == (b.id, b.start_byte, b.end_byte)++def upper_bound(cond: Node | None) -> Node | None:"""``n`` of a counted loop's ``i < n`` / ``i <= n``; ``None`` for any other condition."""if cond is None or cond.type != "binary_expression":@@ -50,11 +75,15 @@ class ScopeFacts:"""One function's bindings and mutations, read in one pass over its body.``bindings``: name -> ``(statement, value)`` in source order; ``changes``:- name -> start offsets of statements that grow or step it.+ name -> start offsets of statements that grow or step it, or hand it to a+ call that may; ``declared``: every name the function declares in any form+ (parameters, loop variables, patterns), which a file-level binding of the+ same name does not reach."""bindings: dict[bytes, list[tuple[Node, Node]]] = field(default_factory=dict)changes: dict[bytes, list[int]] = field(default_factory=dict)+ declared: set[bytes] = field(default_factory=set)class IterableSources(BasePerfDialect):@@ -98,9 +127,15 @@ class IterableSources(BasePerfDialect):conditional_kinds: frozenset[str] = frozenset()# ``None``: a dialect whose own syntax rules size a read (Python, TS).read_grows: LoopMagnitude | None = "grows_with_data"+ # Declarations whose ``body`` holds more file-level items (a C++ namespace),+ # and class-like declarations whose members a bare name in a method may read.+ file_container_kinds: frozenset[str] = frozenset()+ member_scope_kinds: frozenset[str] = frozenset()- # The last scope read, held so its tree (and so the node id in the key) stays live.- _facts_cache: tuple[Node, tuple[int, int, int], ScopeFacts] | None = None+ # The facts of each function read in the current tree, and that tree's+ # file-level bindings; the root is held so the node ids in the keys stay live.+ _facts_cache: tuple[Node, dict[tuple[int, int, int], ScopeFacts]] | None = None+ _file_cache: tuple[Node, dict[bytes, Node | None]] | None = None# -- hooks -----------------------------------------------------------------@@ -130,6 +165,24 @@ class IterableSources(BasePerfDialect):"""``(name, value)`` for each bare name the statement *node* binds."""return []+ def declared_names(self, node: Node) -> list[bytes]:+ """Names *node* declares without a value :meth:`bindings_of` reads: a+ parameter, a loop variable, a destructuring or catch pattern."""+ return []++ def escaped_names(self, node: Node) -> list[bytes]:+ """Names *node* hands to a call that may grow them (``fill(&mut xs)``)."""+ return []++ def file_bindings_of(self, item: Node) -> list[tuple[bytes, Node]]:+ """``(name, value)`` for a file-level item whose value cannot change+ (a ``const``, an enum, a read-only list)."""+ return []++ def member_names(self, owner: Node) -> set[bytes]:+ """Names a class-like *owner* declares as members or constructor parameters."""+ return set()+def mutated_name(self, node: Node) -> bytes | None:"""The name *node* grows or steps (``xs.Add(x)``, ``m[k] = v``, ``n++``)."""if node.type in self.change_kinds and node.named_children:@@ -174,7 +227,7 @@ class IterableSources(BasePerfDialect):def loop_source(self, loop: Node, probe: SinkProbe) -> LoopSource | None:kind, node = self.loop_header(loop)- if node is None:+ if node is None or _deeper_than(node, _MAX_HEADER_DEPTH):return Noneif kind == "counted":iterates, magnitude = self._counted(node, loop, probe)@@ -290,18 +343,21 @@ class IterableSources(BasePerfDialect):def _int_arg(self, args: list[Node]) -> bool:return len(args) == 1 and self._unwrap(args[0]).type in self.int_kinds- def _counted(self, stop: Node, loop: Node, probe: SinkProbe) -> Source:- """``i < 3`` is a constant; ``i < len(rows)`` walks ``rows``; ``i < n`` a parameter."""+ def _counted(self, stop: Node, loop: Node, probe: SinkProbe, *, hop: bool = True) -> Source:+ """``i < 3`` is a constant; ``i < len(rows)`` walks ``rows``; ``i < n`` a parameter.++ A name is followed one binding deep, as in :meth:`_name`: ``val n = n``+ (Kotlin shadowing a property) would otherwise follow itself forever."""node = self._unwrap(stop)if node.type in self.int_kinds:return "constant", "bounded"if node.type in self.name_kinds:if (node.text or b"") in self.param_names(loop):return "parameter", None- value = self.reaching_value(loop, node.text or b"")+ value = self.reaching_value(loop, node.text or b"") if hop else Noneif value is None or self._changed_before(value, loop, node.text or b""):return _UNKNOWN- return self._counted(value, loop, probe)+ return self._counted(value, loop, probe, hop=False)sized = self._sized(node)return self._iterable(sized, loop, probe, hop=True) if sized is not None else _UNKNOWN@@ -328,15 +384,9 @@ class IterableSources(BasePerfDialect):def _query(self, call: Node, loop: Node) -> Source:"""Rows of one key, a capped read, a rare state, or rows that grow; thenames the call reads may be bound to their statement before the loop."""- # A Ruby ``find_each do ... end`` reads before its block runs.- block = call.child_by_field_name("block")- head = (call.text or b"")[: block.start_byte - call.start_byte] if block else call.text- names = [n.text for n in self._walk(call, prune=_BLOCKS) if n.type in self.name_kinds]- values = [v for name in dict.fromkeys(names) if (v := self.reaching_value(loop, name or b""))]- nodes = [call, *values]+ nodes, text = self._query_parts(call, loop)if self.reads_config_table(call, nodes):return "config_table", None- text = b" ".join([head or b"", *(value.text or b"" for value in values)])if lex.is_key_lookup(text):return "caller_key", "bounded"# The children of one parent (``user_id = ?``) are as many as that parent@@ -348,6 +398,16 @@ class IterableSources(BasePerfDialect):return "query", Nonereturn ("rare_subset" if lex.is_rare_filter(text) else "query"), self.read_grows+ def _query_parts(self, call: Node, loop: Node) -> tuple[list[Node], bytes]:+ """The read and the values its names are bound to, and their text."""+ # A Ruby ``find_each do ... end`` reads before its block runs.+ block = call.child_by_field_name("block")+ head = (call.text or b"")[: block.start_byte - call.start_byte] if block else call.text+ names = [n.text for n in self._walk(call, prune=_BLOCKS) if n.type in self.name_kinds]+ values = [v for name in dict.fromkeys(names) if (v := self.reaching_value(loop, name or b""))]+ text = b" ".join([head or b"", *(value.text or b"" for value in values)])+ return [call, *values], text+def _walks_repo(self, call: Node, method: str, loop: Node) -> bool:"""A recursive listing whose path names a repository root; any other pathproves nothing about its size."""@@ -376,20 +436,27 @@ class IterableSources(BasePerfDialect):"""The bindings and mutations of the function around *anchor*, read onceper function: every loop and call in it asks the same map."""scope = self._scope(anchor)- if scope is None:- return None+ return self._facts_of(scope) if scope is not None else None++ def _facts_of(self, scope: Node) -> ScopeFacts:key = (scope.id, scope.start_byte, scope.end_byte)+ root = _root(scope)cached = self._facts_cache- if cached is not None and cached[1] == key:- return cached[2]+ if cached is None or not _same_node(cached[0], root):+ cached = self._facts_cache = (root, {})+ if key not in cached[1]:+ cached[1][key] = self._read_scope(scope)+ return cached[1][key]++ def _read_scope(self, scope: Node) -> ScopeFacts:facts = ScopeFacts()for node in self._walk(scope, prune=self.function_kinds):for name, value in self.bindings_of(node):facts.bindings.setdefault(name, []).append((node, value))changed = self.mutated_name(node)- if changed:- facts.changes.setdefault(changed, []).append(node.start_byte)- self._facts_cache = (scope, key, facts)+ for name in ([changed] if changed else []) + self.escaped_names(node):+ facts.changes.setdefault(name, []).append(node.start_byte)+ facts.declared.update(self.declared_names(node))return factsdef bindings_before(self, anchor: Node, name: bytes) -> list[tuple[Node, Node]]:@@ -401,12 +468,59 @@ class IterableSources(BasePerfDialect):def reaching_value(self, loop: Node, name: bytes) -> Node | None:"""The value *name* surely holds at *loop*: its one binding before theloop, made where the loop also runs. A second binding, or one under a- branch or loop the target loop is not in, leaves it unknown."""+ branch or loop the target loop is not in, leaves it unknown. With no+ binding before the loop, a file-level value (:meth:`file_binding`)."""before = self.bindings_before(loop, name)+ if not before:+ return self.file_binding(loop, name)if len(before) != 1 or not self._surely_reaches(before[0][0], loop):return Nonereturn before[0][1]+ def file_binding(self, loop: Node, name: bytes) -> Node | None:+ """The file-level value of *name* (:meth:`file_bindings_of`), unless a+ function or class around *loop* binds or declares the name anywhere,+ before or after the loop: that name may be the one the loop reads."""+ if type(self).file_bindings_of is IterableSources.file_bindings_of:+ return None+ node, root = loop.parent, loop+ while node is not None:+ if node.type in self.function_kinds:+ facts = self._facts_of(node)+ if name in facts.declared or name in facts.bindings:+ return None+ elif node.type in self.member_scope_kinds and name in self.member_names(node):+ return None+ root, node = node, node.parent+ return self._file_items(root).get(name)++ def _file_items(self, root: Node) -> dict[bytes, Node | None]:+ """Every file-level binding, read once per tree; a name bound twice is ``None``."""+ cached = self._file_cache+ if cached is not None and _same_node(cached[0], root):+ return cached[1]+ items: dict[bytes, Node | None] = {}+ containers = [root]+ while containers:+ for item in containers.pop().named_children:+ body = item.child_by_field_name("body")+ if item.type in self.file_container_kinds and body is not None:+ containers.append(body)+ for name, value in self.file_bindings_of(item):+ items[name] = None if name in items else value+ self._file_cache = (root, items)+ return items++ def chain_root(self, node: Node) -> Node:+ """The innermost call of a method chain ``a(..).b(..).c(..)``, or a+ non-call receiver it starts from that :meth:`call_parts` reads as a call."""+ while True:+ parts = self.call_parts(node)+ receiver = self._unwrap(parts[1]) if parts is not None and parts[1] is not None else None+ if receiver is None or self.call_parts(receiver) is None:+ return node+ node = receiver+def _surely_reaches(self, stmt: Node, loop: Node) -> bool:"""Every node between *stmt* and the first one holding *loop* runswhenever that one does (a branch's condition or initializer does)."""diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/kotlin.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/kotlin.pyindex f1d2c0984..4ec8689ff 100644--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/kotlin.py+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/kotlin.py@@ -43,8 +43,9 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING-from .base import BasePerfDialect+from .iterables import IterableSources, text_offrom .java import (+ _JAVA_TYPE_NAME,AMBIGUOUS_DB,FILES_METHODS,FS_CONSTRUCTORS,@@ -63,6 +64,9 @@ from .java import (if TYPE_CHECKING:from tree_sitter import Node+ from ..loop_facts import SinkProbe+ from .iterables import Source+# Full-iteration combinators (the shared block-iteration definition — see# ``BasePerfDialect.block_loop_body``). Early-exit searches (``find`` /# ``firstOrNull`` / ``any`` / ``all`` / ``none``) are deliberately absent: they@@ -200,7 +204,85 @@ def _callee(call_node: Node) -> Node | None:return next((c for c in call_node.children if c.is_named), None)-class KotlinPerfDialect(BasePerfDialect):+_KT_FN_KINDS: frozenset[str] = frozenset(+ {+ "function_declaration", "lambda_literal", "anonymous_function", "secondary_constructor",+ "getter", "setter", "anonymous_initializer",+ }+)+# Collections that keep the size the call spells out.+_KT_READ_ONLY: frozenset[str] = frozenset(+ {+ "listOf", "setOf", "mapOf", "arrayOf", "sequenceOf", "listOfNotNull", "intArrayOf",+ "longArrayOf", "doubleArrayOf", "charArrayOf", "booleanArrayOf",+ }+)+_KT_FACTORIES: frozenset[str] = _KT_READ_ONLY | frozenset(+ {+ "mutableListOf", "mutableSetOf", "mutableMapOf", "arrayListOf", "hashSetOf", "hashMapOf",+ "linkedSetOf", "linkedMapOf", "sortedSetOf", "sortedMapOf",+ }+)+# Exposed reads: ``Users.selectAll()``, and ``Users.select(..)`` / ``User.all()`` /+# ``User.find { .. }`` on a table or entity object.+_EXPOSED_READS: frozenset[str] = frozenset({"selectAll", "selectAllBatched", "selectBatched"})+_EXPOSED_TYPE_READS: frozenset[str] = frozenset({"select", "all", "find", "wrapRows"})+++def _kt_bindings(node: Node) -> list[tuple[bytes, Node]]:+ """What *node* binds: ``val x = v`` / ``var x = v`` / ``x = v``."""+ if node.type == "assignment":+ op, left = node.child_by_field_name("operator"), node.child_by_field_name("left")+ right = node.child_by_field_name("right")+ plain = op is not None and op.text == b"=" and left is not None and right is not None+ return [(left.text, right)] if plain and left.type == "identifier" and left.text else []+ return _kt_property_value(node) if node.type == "property_declaration" else []+++def _is_enum(node: Node) -> bool:+ """``enum class Role { .. }``."""+ if node.type != "class_declaration":+ return False+ mods = next((c for c in node.named_children if c.type == "modifiers"), None)+ return mods is not None and any(c.text == b"enum" for c in mods.named_children)+++def _kt_member_name(member: Node) -> list[bytes]:+ """The name a ``class_parameter`` or ``property_declaration`` declares."""+ if member.type == "property_declaration":+ member = next((c for c in member.named_children if c.type == "variable_declaration"), member)+ ident = next((c for c in member.named_children if c.type == "identifier"), None)+ return [ident.text] if ident is not None and ident.text else []+++def _kt_property_value(node: Node) -> list[tuple[bytes, Node]]:+ named = node.named_children+ binder = next((i for i, c in enumerate(named) if c.type == "variable_declaration"), None)+ if binder is None or binder + 1 >= len(named):+ return []+ ident = next((c for c in named[binder].named_children if c.type == "identifier"), None)+ value = named[binder + 1]+ if ident is None or not ident.text or value.type == "property_delegate":+ return []+ return [(ident.text, value)]+++def _kt_range(node: Node | None) -> tuple[str, Node | None]:+ """The header of ``for (i in ..)``: ``0..n`` / ``0 until n`` / ``n downTo 0``+ (``step k`` dropped) count to ``n``; anything else is walked."""+ if node is not None and node.type == "range_expression" and node.named_child_count == 2:+ return "counted", node.named_children[1]+ if node is None or node.type != "infix_expression" or node.named_child_count != 3:+ return "each", node+ left, op, right = node.named_children+ if op.text == b"step":+ return _kt_range(left)+ if op.text == b"until":+ return "counted", right+ return ("counted", left) if op.text == b"downTo" else ("each", node)+++class KotlinPerfDialect(IterableSources):language = "kotlin"lock_acquire_functions = JAVA_LOCK_ACQUIRE_FUNCTIONSspin_loop_header = JAVA_SPIN_LOOP_HEADER@@ -536,6 +618,165 @@ class KotlinPerfDialect(BasePerfDialect):return Falsereturn not _TEMPLATE_RE.search(inner.text.decode("utf-8", "replace"))+ # -- what a loop walks (perf/dialects/iterables.py) ---------------------------++ function_kinds = _KT_FN_KINDS+ member_scope_kinds = frozenset({"class_declaration", "object_declaration"})++ int_kinds = frozenset({"number_literal"})+ wrapper_kinds = frozenset({"parenthesized_expression"})+ pass_through = frozenset(+ {+ "asSequence", "asIterable", "filter", "filterNot", "filterNotNull", "filterIsInstance",+ "map", "mapNotNull", "flatMap", "flatten", "sorted", "sortedBy", "sortedDescending",+ "sortedByDescending", "sortedWith", "distinct", "distinctBy", "reversed", "asReversed",+ "withIndex", "toList", "toMutableList", "toSet", "toMutableSet", "toTypedArray",+ "keys", "values", "entries", "indices", "iterator", "chunked", "windowed", "drop",+ "dropWhile", "takeWhile", "onEach", "shuffled",+ }+ )+ caps = frozenset({"take"})+ size_names = frozenset({"size", "count", "length", "lastIndex"})+ # ``while (rs.next())`` (JDBC), ``while (it.hasNext())``.+ cursor_advances = frozenset({"next", "hasNext"})+ listings = frozenset({"listFiles", "walk", "walkTopDown", "walkBottomUp"})+ recursive_listings = frozenset({"walk", "walkTopDown", "walkBottomUp"})+ streams = frozenset({"readLines", "useLines", "lineSequence", "lines"})+ query_caps = frozenset({"limit"})+ member_kinds = frozenset({"navigation_expression"})+ # ``n++`` is a ``unary_expression``; so is ``!x``, which only costs a constant.+ change_kinds = frozenset({"assignment", "unary_expression"})+ grow_methods = frozenset(+ {"add", "addAll", "put", "putAll", "plusAssign", "addFirst", "addLast", "push", "offer"}+ )+ conditional_kinds = frozenset(+ {+ "if_expression", "when_expression", "when_entry", "for_statement", "while_statement",+ "do_while_statement", "try_expression", "catch_block", "finally_block", "elvis_expression",+ }+ )++ def loop_header(self, loop: Node) -> tuple[str, Node | None]:+ if loop.type == "for_statement":+ return _kt_range(self._for_iterable(loop))+ if loop.type in ("while_statement", "do_while_statement"):+ cond = loop.child_by_field_name("condition")+ return ("cursor", cond) if cond is not None else ("each", None)+ if loop.type == "call_expression" and self.block_loop_body(loop) is not None:+ parts = self.call_parts(loop)+ return "each", parts[1] if parts is not None else None+ return "each", None++ def is_literal(self, node: Node) -> bool:+ """An enum class declared in the file: ``Role.entries`` / ``Role.values()``+ walk its constants, spelled out in the declaration."""+ return _is_enum(node)++ def call_parts(self, node: Node) -> tuple[str, Node | None, list[Node]] | None:+ if node.type != "call_expression":+ return None+ fn = _callee(node)+ args = next((c for c in node.children if c.type == "value_arguments"), None)+ arg_nodes = [+ inner+ for arg in (args.named_children if args is not None else ())+ if (inner := next((c for c in arg.named_children if "comment" not in c.type), None))+ ]+ if fn is not None and fn.type == "navigation_expression":+ named = fn.named_children+ return text_of(named[-1]), named[0], arg_nodes+ return (text_of(fn), None, arg_nodes) if fn is not None and fn.type == "identifier" else None++ def member_parts(self, node: Node) -> tuple[str, Node] | None:+ if node.type != "navigation_expression" or node.named_child_count < 2:+ return None+ return text_of(node.named_children[-1]), node.named_children[0]++ def special_call(+ self,+ call: Node,+ parts: tuple[str, Node | None, list[Node]],+ loop: Node,+ probe: SinkProbe,+ ) -> Source | None:+ method, receiver, args = parts+ if receiver is None and method in _KT_FACTORIES:+ # ``listOf(a, b)``; an empty ``mutableListOf()`` is filled later.+ spread = any(arg.type == "spread_expression" for arg in args)+ return ("constant", "bounded") if args and not spread else None+ if receiver is None and method in ("enumValues", "enumEntries") and not args:+ return "constant", "bounded" # the type argument must be an enum+ return None++ def query_chain(self, node: Node) -> bool:+ """``Users.selectAll().where { … }`` / ``User.find { … }``: an Exposed read+ anywhere down the chain, on a table or entity object."""+ parts = self.call_parts(node)+ while parts is not None:+ method, receiver, _args = parts+ if method in _EXPOSED_READS:+ return True+ on_type = receiver is not None and bool(_JAVA_TYPE_NAME.match(text_of(receiver)))+ if on_type and method in _EXPOSED_TYPE_READS:+ return True+ parts = self.call_parts(receiver) if receiver is not None else None+ return False++ def bindings_of(self, node: Node) -> list[tuple[bytes, Node]]:+ return _kt_bindings(node)++ def declared_names(self, node: Node) -> list[bytes]:+ """``val x`` / ``for (x in ..)`` / ``(a, b) ->`` / ``catch (e: ..)`` / a parameter."""+ if node.type not in ("variable_declaration", "parameter", "catch_block"):+ return []+ ident = next((c for c in node.named_children if c.type == "identifier"), None)+ return [ident.text] if ident is not None and ident.text else []++ def escaped_names(self, node: Node) -> list[bytes]:+ """``xs`` of ``fill(xs)``: a callee that may add to a mutable list."""+ parts = self.call_parts(node)+ args = parts[2] if parts is not None else []+ return [arg.text for arg in args if arg.type == "identifier" and arg.text]++ def file_bindings_of(self, item: Node) -> list[tuple[bytes, Node]]:+ """An enum class, or a ``val`` of a read-only list (``listOf(..)``)."""+ if _is_enum(item):+ name = item.child_by_field_name("name")+ return [(name.text, item)] if name is not None and name.text else []+ if item.type != "property_declaration" or not any(c.type == "val" for c in item.children):+ return []+ return [+ (bound, value)+ for bound, value in _kt_bindings(item)+ if (parts := self.call_parts(value)) is not None and parts[0] in _KT_READ_ONLY+ ]++ def member_names(self, owner: Node) -> set[bytes]:+ """Constructor parameters and properties, read bare in a method."""+ names: set[bytes] = set()+ for part in owner.named_children:+ if part.type == "primary_constructor":+ params = next((c for c in part.named_children if c.type == "class_parameters"), None)+ members = params.named_children if params is not None else []+ elif part.type == "class_body":+ members = [c for c in part.named_children if c.type == "property_declaration"]+ else:+ continue+ for member in members:+ names.update(_kt_member_name(member))+ return names++ def param_names(self, loop: Node) -> set[bytes]:+ scope = self._scope(loop)+ kinds = ("function_value_parameters", "lambda_parameters")+ params = next((c for c in scope.children if c.type in kinds), None) if scope else None+ names: set[bytes] = set()+ for param in params.named_children if params is not None else ():+ ident = next((c for c in param.named_children if c.type == "identifier"), None)+ if ident is not None and ident.text:+ names.add(ident.text)+ return names+def is_lock_scope(self, node: Node) -> bool:# ``synchronized(x) { … }`` / ``lock.withLock { … }`` — the trailing# lambda is the held region (the walker raises lock_depth for block-diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/rust.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/rust.pyindex a36769977..7a308abe3 100644--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/rust.py+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/rust.py@@ -37,12 +37,15 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING-from .base import BasePerfDialect+from .iterables import IterableSources, text_offrom .python import HTTP_VERBSif TYPE_CHECKING:from tree_sitter import Node+ from ..loop_facts import SinkProbe+ from .iterables import Source+# Rust string-literal node kinds (the hoistable-pattern gate)._RUST_STRING_KINDS: frozenset[str] = frozenset({"string_literal", "raw_string_literal"})@@ -122,7 +125,84 @@ def _scoped_segments(call_node: Node) -> list[str] | None:return segs or None-class RustPerfDialect(BasePerfDialect):+_RS_FN_KINDS: frozenset[str] = frozenset({"function_item", "closure_expression"})+# Directory walkers that recurse unless capped with ``max_depth``.+_RS_WALKERS: frozenset[str] = frozenset({"WalkDir", "WalkBuilder"})+# sqlx query builders whose ``fetch`` streams the rows they select.+_SQLX_QUERIES: frozenset[str] = frozenset(+ {"query", "query_as", "query_scalar", "query_with", "query_as_with"}+)+++def _rs_bindings(node: Node) -> list[tuple[bytes, Node]]:+ """What *node* binds: ``let x = v`` or ``x = v``."""+ if node.type == "let_declaration":+ target, value = node.child_by_field_name("pattern"), node.child_by_field_name("value")+ elif node.type == "assignment_expression":+ target, value = node.child_by_field_name("left"), node.child_by_field_name("right")+ else:+ return []+ ok = target is not None and target.type == "identifier" and target.text and value is not None+ return [(target.text, value)] if ok else []+++def _rs_file_bindings(item: Node) -> list[tuple[bytes, Node]]:+ """A file-level ``const`` / ``static`` (never ``static mut``)."""+ if item.type not in ("const_item", "static_item"):+ return []+ if any(child.type == "mutable_specifier" for child in item.children):+ return []+ name, value = item.child_by_field_name("name"), item.child_by_field_name("value")+ return [(name.text, value)] if name is not None and name.text and value is not None else []+++# Statements and the field holding the pattern they declare names in.+_RS_PATTERN_FIELDS: dict[str, str] = {+ "let_declaration": "pattern",+ "for_expression": "pattern",+ "parameter": "pattern",+ "let_condition": "pattern",+ "match_arm": "pattern",+}+++def _rs_declared(node: Node) -> list[bytes]:+ """Names a ``let`` / ``for`` / parameter / ``if let`` / match / closure pattern declares."""+ if node.type == "closure_parameters":+ pattern: Node | None = node+ else:+ field = _RS_PATTERN_FIELDS.get(node.type)+ pattern = node.child_by_field_name(field) if field else None+ if pattern is None:+ return []+ return [n.text for n in IterableSources._walk(pattern) if n.type == "identifier" and n.text]+++def _rs_escaped(args: list[Node]) -> list[bytes]:+ """``xs`` of ``f(&mut xs)`` / ``f(xs)``: a callee that may grow it."""+ names: list[bytes] = []+ for arg in args:+ if arg.type == "reference_expression" and any(c.type == "mutable_specifier" for c in arg.children):+ arg = arg.child_by_field_name("value") or arg+ if arg.type == "identifier" and arg.text:+ names.append(arg.text)+ return names+++def _range_end(node: Node) -> Node | None:+ """``n`` of ``a..n`` / ``a..=n``; ``None`` for an open ``a..``."""+ last = node.children[-1] if node.children else None+ return last if last is not None and last.is_named and node.named_child_count == 2 else None+++def _deref(node: Node | None) -> Node | None:+ """``xs`` of ``&xs`` / ``&mut xs``."""+ while node is not None and node.type == "reference_expression":+ node = node.child_by_field_name("value")+ return node+++class RustPerfDialect(IterableSources):language = "rust"markers = frozenset({@@ -264,6 +344,164 @@ class RustPerfDialect(BasePerfDialect):return "resource_construction_in_loop"return None+ # -- what a loop walks (perf/dialects/iterables.py) ---------------------------++ function_kinds = _RS_FN_KINDS++ int_kinds = frozenset({"integer_literal"})+ # ``&xs`` / ``&mut xs`` walk ``xs``; a call handed ``&mut xs`` before the+ # loop may grow it (:meth:`escaped_names`).+ wrapper_kinds = frozenset(+ {"parenthesized_expression", "try_expression", "await_expression", "reference_expression"}+ )+ pass_through = frozenset(+ {+ "iter", "iter_mut", "into_iter", "enumerate", "rev", "cloned", "copied", "filter",+ "filter_map", "map", "flat_map", "flatten", "skip", "skip_while", "take_while",+ "peekable", "keys", "values", "values_mut", "into_keys", "into_values", "drain",+ "windows", "chunks", "chunks_exact", "by_ref", "as_slice", "to_vec", "collect",+ "inspect", "step_by", "sorted", "unique",+ }+ )+ caps = frozenset({"take"})+ size_names = frozenset({"len"})+ # ``while let Some(row) = rows.next()`` (rusqlite), ``stream.try_next().await`` (sqlx).+ cursor_advances = frozenset({"next", "try_next"})+ listings = frozenset({"read_dir", "glob"})+ recursive_listings = _RS_WALKERS+ query_caps = frozenset({"limit"})+ member_kinds = frozenset({"field_expression"})+ change_kinds = frozenset({"assignment_expression", "compound_assignment_expr"})+ grow_methods = frozenset(+ {+ "push", "push_str", "extend", "extend_from_slice", "insert", "append", "push_back",+ "push_front", "resize",+ }+ )+ conditional_kinds = frozenset(+ {+ "if_expression", "if_let_expression", "else_clause", "match_expression", "match_arm",+ "for_expression", "while_expression", "while_let_expression", "loop_expression",+ }+ )++ def loop_header(self, loop: Node) -> tuple[str, Node | None]:+ if loop.type == "for_expression":+ value = _deref(loop.child_by_field_name("value"))+ if value is not None and value.type == "range_expression":+ return "counted", _range_end(value)+ return "each", value+ if loop.type in ("while_expression", "while_let_expression"):+ cond = loop.child_by_field_name("condition") or loop.child_by_field_name("value")+ if cond is not None and cond.type == "let_condition":+ cond = cond.child_by_field_name("value")+ return ("cursor", cond) if cond is not None else ("each", None)+ return "each", None++ def is_literal(self, node: Node) -> bool:+ """``[a, b]`` / ``[0; 16]`` / ``vec![a, b]`` / ``vec![0; 16]`` / ``0..10``."""+ if node.type == "range_expression":+ ends = node.named_children+ return len(ends) == 2 and all(end.type in self.int_kinds for end in ends)+ if node.type == "array_expression":+ length = node.child_by_field_name("length")+ if length is not None:+ return length.type in self.int_kinds+ return any("comment" not in c.type for c in node.named_children)+ return node.type == "macro_invocation" and self._vec_literal(node)++ def _vec_literal(self, node: Node) -> bool:+ if text_of(node.child_by_field_name("macro")) != "vec":+ return False+ tree = next((c for c in node.named_children if c.type == "token_tree"), None)+ entries = tree.named_children if tree is not None else []+ if tree is not None and any(c.type == ";" for c in tree.children):+ return bool(entries) and entries[-1].type in self.int_kinds+ return bool(entries)++ def call_parts(self, node: Node) -> tuple[str, Node | None, list[Node]] | None:+ if node.type != "call_expression":+ return None+ fn = node.child_by_field_name("function")+ if fn is not None and fn.type == "generic_function":+ fn = fn.child_by_field_name("function")+ args = node.child_by_field_name("arguments")+ arg_nodes = [c for c in args.named_children if "comment" not in c.type] if args else []+ if fn is not None and fn.type == "field_expression":+ field, value = fn.child_by_field_name("field"), fn.child_by_field_name("value")+ return text_of(field), value, arg_nodes+ if fn is not None and fn.type == "scoped_identifier":+ # ``WalkDir::new(p)``: the receiver is the type the function belongs to.+ return text_of(fn.child_by_field_name("name")), fn.child_by_field_name("path"), arg_nodes+ return text_of(fn), None, arg_nodes++ def special_call(+ self,+ call: Node,+ parts: tuple[str, Node | None, list[Node]],+ loop: Node,+ probe: SinkProbe,+ ) -> Source | None:+ root = self.call_parts(self.chain_root(call))+ if root is not None and root[0].startswith("build") and root[1] is not None:+ # ``builder.build().fetch_all(..)``: the SQL, its filter and its LIMIT+ # were pushed onto the builder piece by piece, out of sight here.+ reads = probe(call) == "db" or self.query_chain(call)+ return ("query", None) if reads else None+ if root is None or root[0] != "new" or root[1] is None:+ return None+ if text_of(root[1]).rsplit("::", 1)[-1] not in _RS_WALKERS:+ return None+ # ``WalkDir::new(p).max_depth(1)`` lists one directory.+ recursive = b"max_depth" not in (call.text or b"")+ grows = recursive and self._walks_repo(call, "WalkDir", loop)+ return "listing", "grows_with_data" if grows else None++ def query_chain(self, node: Node) -> bool:+ """A read the probe does not name: a sqlx ``fetch`` stream, rusqlite's+ ``query_map`` / ``stmt.query``, diesel's ``load(conn)`` / ``get_results``."""+ parts = self.call_parts(node)+ if parts is None:+ return False+ method, receiver, args = parts+ if method in ("fetch", "fetch_many"):+ root_parts = self.call_parts(self.chain_root(node))+ if root_parts is None:+ return False+ base = self._unwrap(root_parts[1]) if root_parts[1] is not None else None+ if base is not None and base.type == "macro_invocation":+ # ``sqlx::query!(..).fetch(..)``+ return text_of(base.child_by_field_name("macro")).startswith("query")+ return root_parts[0] in _SQLX_QUERIES+ if method in ("query_map", "query_and_then", "get_results"):+ return True+ if method == "query":+ return text_of(receiver).lower().endswith(("stmt", "statement"))+ return method == "load" and bool(args) and "conn" in text_of(args[0])++ def bindings_of(self, node: Node) -> list[tuple[bytes, Node]]:+ return _rs_bindings(node)++ def declared_names(self, node: Node) -> list[bytes]:+ return _rs_declared(node)++ def escaped_names(self, node: Node) -> list[bytes]:+ parts = self.call_parts(node)+ return _rs_escaped(parts[2]) if parts is not None else []++ def file_bindings_of(self, item: Node) -> list[tuple[bytes, Node]]:+ return _rs_file_bindings(item)++ def param_names(self, loop: Node) -> set[bytes]:+ scope = self._scope(loop)+ params = scope.child_by_field_name("parameters") if scope is not None else None+ names: set[bytes] = set()+ for param in params.named_children if params is not None else ():+ target = param.child_by_field_name("pattern") if param.type == "parameter" else param+ if target is not None and target.type == "identifier" and target.text:+ names.add(target.text)+ return names+@staticmethoddef _has_static_pattern_arg(node: Node) -> bool:"""True if the call's first argument is a compile-time string literaldiff --git a/packages/core/src/repowise/core/analysis/health/perf/loop_lexicon.py b/packages/core/src/repowise/core/analysis/health/perf/loop_lexicon.pyindex 1370f2154..d6031f4f4 100644--- a/packages/core/src/repowise/core/analysis/health/perf/loop_lexicon.py+++ b/packages/core/src/repowise/core/analysis/health/perf/loop_lexicon.py@@ -150,19 +150,31 @@ _PARENT_KEY = re.compile()+_RECURSIVE = re.compile(rb"\bRECURSIVE\b", re.IGNORECASE)+_UNION = re.compile(rb"\bUNION\b", re.IGNORECASE)++def is_parent_key_filter(text: bytes) -> bool:- """The read filters on equality with one foreign key."""+ """The read filters on equality with one foreign key, or walks the tree+ below one row: a ``WITH RECURSIVE`` whose seed (the part before the first+ ``UNION``) keys on one id. A key only in the recursive member says nothing+ about how many roots the seed starts from."""+ recursive = _RECURSIVE.search(text)+ if recursive is not None:+ seed = _UNION.split(text[recursive.end() :], maxsplit=1)[0]+ if _KEY_EQUALITY.search(seed):+ return Truereturn bool(_PARENT_KEY.search(text))_SQL_LIMIT = re.compile(- rb"\bselect\b.*?(?:\blimit\s+\d+\b|\btop\s*\(?\s*\d+|\bfetch\s+first\s+\d+)",+ rb"\bselect\b.*?(?:\blimit\s+(?:\d+\b|\?|\$\d|:\w)|\btop\s*\(?\s*\d+|\bfetch\s+first\s+\d+)",re.IGNORECASE | re.DOTALL,)def has_sql_limit(text: bytes) -> bool:- """A SELECT capped at a literal row count (``LIMIT 10``, ``TOP 5``)."""+ """A SELECT capped at a row count (``LIMIT 10``, ``LIMIT ?``, ``TOP 5``)."""return bool(_SQL_LIMIT.search(text))diff --git a/tests/unit/health/test_perf_loop_sources_rust_kotlin_cpp.py b/tests/unit/health/test_perf_loop_sources_rust_kotlin_cpp.pynew file mode 100644index 000000000..e6676cd53--- /dev/null+++ b/tests/unit/health/test_perf_loop_sources_rust_kotlin_cpp.py@@ -0,0 +1,437 @@+"""What a perf loop walks, and the magnitude that proves, in Rust, Kotlin and C++.++Through the real walker, as for the other hook dialects: each shape that grows+or is bounded sits beside one the syntax does not settle, which stays ``unknown``.+"""++from __future__ import annotations++import pytest++from tests.unit.health.test_perf_loop_sources_dialects import _loops++_RUST = """const KINDS: &[&str] = &["a", "b"];+fn f(ids: &[i64], pool: &PgPool, repo_root: &Path, dir: &Path) {+ for id in ids { sqlx::query("x").fetch_one(pool).await?; }+ for id in ids.iter().take(5) { sqlx::query("x").fetch_one(pool).await?; }+ for k in vec!["a", "b"] { sqlx::query("x").fetch_one(pool).await?; }+ for k in KINDS { sqlx::query("x").fetch_one(pool).await?; }+ let rows = sqlx::query("SELECT id FROM orders").fetch_all(pool).await?;+ for r in &rows { sqlx::query("x").fetch_one(pool).await?; }+ let one = sqlx::query("SELECT * FROM orders WHERE id = $1").fetch_all(pool).await?;+ for r in one { sqlx::query("x").fetch_one(pool).await?; }+ let mut s = sqlx::query("SELECT id FROM orders").fetch(pool);+ while let Some(r) = s.try_next().await? { sqlx::query("x").fetch_one(pool).await?; }+ for e in WalkDir::new(repo_root) { sqlx::query("x").fetch_one(pool).await?; }+ for e in WalkDir::new(repo_root).max_depth(1) { sqlx::query("x").fetch_one(pool).await?; }+ for e in std::fs::read_dir(dir)? { sqlx::query("x").fetch_one(pool).await?; }+ for i in 0..ids.len() { sqlx::query("x").fetch_one(pool).await?; }+ let mut grown = vec![1];+ grown.extend(ids);+ for g in grown { sqlx::query("x").fetch_one(pool).await?; }+ let built = builder.build().fetch_all(pool).await?;+ for b in built { sqlx::query("x").fetch_one(pool).await?; }+ for p in &self.providers { sqlx::query("x").fetch_one(pool).await?; }+}+"""+++ ("line", "expected"),+ [+ (3, ("unknown", "parameter")),+ (4, ("bounded", "parameter")), # a literal cap on what is in hand+ (5, ("bounded", "constant")),+ (6, ("bounded", "constant")), # a file-level const array+ (8, ("grows_with_data", "query")),+ (10, ("bounded", "caller_key")),+ (12, ("grows_with_data", "query")), # a sqlx row stream+ (13, ("grows_with_data", "listing")), # a recursive walk of the repository+ (14, ("unknown", "listing")), # capped at one level+ (15, ("unknown", "listing")),+ (16, ("unknown", "parameter")),+ (19, ("unknown", "unknown")), # the literal was extended before the loop+ (21, ("unknown", "query")), # SQL pushed onto a builder out of sight+ (22, ("unknown", "config_table")),+ ],+)+def test_rust_loop_sources(line, expected):+ assert _loops("f.rs", "rust", _RUST)[line] == expected+++_KOTLIN = """private val KINDS = listOf("a", "b")+fun f(ids: List<Long>, n: Int, stmt: Statement, repoRoot: File) {+ for (id in ids) { stmt.executeQuery("x") }+ ids.take(5).forEach { stmt.executeQuery("x") }+ for (k in listOf("a", "b")) { stmt.executeQuery("x") }+ for (k in KINDS) { stmt.executeQuery("x") }+ for (r in Role.entries) { stmt.executeQuery("x") }+ for (r in Role.values()) { stmt.executeQuery("x") }+ val rs = stmt.executeQuery("SELECT * FROM orders")+ while (rs.next()) { stmt.executeQuery("x") }+ for (i in 0 until n) { stmt.executeQuery("x") }+ for (i in 0 until ids.size) { stmt.executeQuery("x") }+ Users.selectAll().forEach { stmt.executeQuery("x") }+ Users.selectAll().limit(10).forEach { stmt.executeQuery("x") }+ for (f in repoRoot.walkTopDown()) { stmt.executeQuery("x") }+ val grown = mutableListOf(1)+ grown.add(2)+ for (g in grown) { stmt.executeQuery("x") }+ for (x in arrayOf(*ids.toTypedArray())) { stmt.executeQuery("x") }+ for (k in Kind.entries) { stmt.executeQuery("x") }+}+enum class Role { A, B }+"""+++ ("line", "expected"),+ [+ (3, ("unknown", "parameter")),+ (4, ("bounded", "parameter")),+ (5, ("bounded", "constant")),+ (6, ("bounded", "constant")), # a file-level read-only list+ (7, ("bounded", "constant")), # an enum declared in the file+ (8, ("bounded", "constant")),+ (10, ("grows_with_data", "query")), # a JDBC cursor over a table+ (11, ("unknown", "parameter")),+ (12, ("unknown", "parameter")),+ (13, ("grows_with_data", "query")), # an Exposed read+ (14, ("unknown", "query")), # capped in the query+ (15, ("grows_with_data", "listing")),+ (18, ("unknown", "unknown")), # grown before the loop+ (19, ("unknown", "unknown")), # a spread adds what ``ids`` holds+ (20, ("unknown", "unknown")), # ``Kind`` may be any class with ``entries``+ ],+)+def test_kotlin_loop_sources(line, expected):+ assert _loops("F.kt", "kotlin", _KOTLIN)[line] == expected+++_CPP = """static const char* kNames[] = {"a", "b"};+void f(sqlite3* db, const std::vector<int>& ids, int n) {+ for (int id : ids) { sqlite3_exec(db, "x", 0, 0, 0); }+ for (auto k : {1, 2, 3}) { sqlite3_exec(db, "x", 0, 0, 0); }+ for (const char* k : kNames) { sqlite3_exec(db, "x", 0, 0, 0); }+ for (size_t i = 0; i < ids.size(); ++i) { sqlite3_exec(db, "x", 0, 0, 0); }+ for (auto it = ids.begin(); it != ids.end(); ++it) { sqlite3_exec(db, "x", 0, 0, 0); }+ std::array<int, 4> fixed;+ for (int x : fixed) { sqlite3_exec(db, "x", 0, 0, 0); }+ std::vector<int> grown = {1};+ grown.push_back(2);+ for (int g : grown) { sqlite3_exec(db, "x", 0, 0, 0); }+ sqlite3_stmt* stmt;+ sqlite3_prepare_v2(db, "SELECT id FROM orders", -1, &stmt, nullptr);+ while (sqlite3_step(stmt) == SQLITE_ROW) { sqlite3_exec(db, "x", 0, 0, 0); }+ for (auto& e : std::filesystem::recursive_directory_iterator(repo_root)) { sqlite3_exec(db, "x", 0, 0, 0); }+ for (auto& e : std::filesystem::directory_iterator(dir)) { sqlite3_exec(db, "x", 0, 0, 0); }+ for (auto& x : items_) { sqlite3_exec(db, "x", 0, 0, 0); }+}+"""+++ ("line", "expected"),+ [+ (3, ("unknown", "parameter")),+ (4, ("bounded", "constant")),+ (5, ("bounded", "constant")), # a file-level const array+ (6, ("unknown", "parameter")),+ (7, ("unknown", "parameter")), # an iterator walk over ``ids``+ (9, ("bounded", "constant")), # a std::array's fixed size+ (12, ("unknown", "unknown")), # grown before the loop+ (15, ("grows_with_data", "query")), # a sqlite cursor over a table+ (16, ("grows_with_data", "listing")),+ (17, ("unknown", "listing")),+ (18, ("unknown", "unknown")), # a field+ ],+)+def test_cpp_loop_sources(line, expected):+ assert _loops("f.cpp", "cpp", _CPP)[line] == expected+++def test_a_read_capped_by_a_bound_limit_is_a_query_of_unknown_size():+ rs = _loops(+ "f.rs",+ "rust",+ "fn f(pool: &PgPool, n: i64) {\n"+ ' let page = sqlx::query("SELECT id FROM t LIMIT ? OFFSET ?").bind(n).fetch_all(pool).await?;\n'+ ' for r in page { sqlx::query("x").fetch_one(pool).await?; }\n'+ "}\n",+ )+ assert rs[3] == ("unknown", "query")+++def test_a_recursive_read_below_one_row_is_a_query_of_unknown_size():+ rs = _loops(+ "f.rs",+ "rust",+ "fn f(pool: &PgPool, id: i64) {\n"+ ' let rows = sqlx::query("WITH RECURSIVE tree(id) AS (SELECT id FROM s WHERE id = ? '+ 'UNION SELECT s.id FROM s JOIN tree ON s.parent_id = tree.id) SELECT * FROM tree")'+ ".bind(id).fetch_all(pool).await?;\n"+ ' for r in rows { sqlx::query("x").fetch_one(pool).await?; }\n'+ "}\n",+ )+ assert rs[3] == ("unknown", "query")+++def test_a_binding_that_may_not_reach_the_loop_bounds_nothing():+ rs = _loops(+ "f.rs",+ "rust",+ "fn f(pool: &PgPool, ids: Vec<i64>, small: bool) {\n"+ " let mut xs = ids;\n"+ " if small { xs = vec![1, 2]; }\n"+ ' for x in xs { sqlx::query("x").fetch_one(pool).await?; }\n'+ "}\n",+ )+ assert rs[4] == ("unknown", "unknown")+++def test_a_statement_prepared_into_a_null_pointer_is_its_read():+ cpp = _loops(+ "f.cpp",+ "cpp",+ "void f(sqlite3* db) {\n"+ " sqlite3_stmt* stmt = nullptr;\n"+ ' sqlite3_prepare_v2(db, "SELECT id FROM orders", -1, &stmt, nullptr);\n'+ ' while (sqlite3_step(stmt) == SQLITE_ROW) { sqlite3_exec(db, "x", 0, 0, 0); }\n'+ "}\n",+ )+ assert cpp[4] == ("grows_with_data", "query")+++_SINK_KT = 'stmt.executeQuery("x")'+++ "body",+ [+ "fun f(items: List<String>, stmt: Statement) {\n for (i in items) { %s }\n}",+ "fun f(groups: List<List<String>>, stmt: Statement) {\n for (items in groups) { for (i in items) { %s } }\n}",+ "fun f(p: Pair<List<String>, Int>, stmt: Statement) {\n val (items, n) = p\n for (i in items) { %s }\n}",+ "class C(val items: List<String>) {\n fun f(stmt: Statement) { for (i in items) { %s } }\n}",+ "fun f(m: Map<String, List<String>>, stmt: Statement) {\n m.forEach { (k, items) -> for (i in items) { %s } }\n}",+ ],+)+def test_a_kotlin_file_level_list_does_not_reach_a_name_declared_around_the_loop(body):+ src = 'val items = listOf("a", "b")\n' + body % _SINK_KT + "\n"+ found = _loops("F.kt", "kotlin", src)+ assert found and all(magnitude == "unknown" for magnitude, _ in found.values()), found+++def test_a_kotlin_file_level_var_or_a_list_handed_to_a_call_bounds_nothing():+ kt = _loops(+ "F.kt",+ "kotlin",+ "var KS = listOf(1, 2)\n"+ "fun f(stmt: Statement) {\n"+ f" for (k in KS) {{ {_SINK_KT} }}\n"+ " val xs = mutableListOf(1)\n"+ " fill(xs)\n"+ f" for (x in xs) {{ {_SINK_KT} }}\n"+ " val ys = listOf(1, 2)\n"+ f" for (y in ys) {{ {_SINK_KT} }}\n"+ "}\n",+ )+ assert kt[3] == ("unknown", "unknown")+ assert kt[6] == ("unknown", "unknown")+ assert kt[8] == ("bounded", "constant")+++def test_a_kotlin_negation_steps_nothing_and_an_increment_does():+ kt = _loops(+ "F.kt",+ "kotlin",+ "fun f(stmt: Statement, ready: Boolean) {\n"+ " val n = 3\n"+ " if (!ready) return\n"+ f" for (i in 0 until n) {{ {_SINK_KT} }}\n"+ " var m = 3\n"+ " m++\n"+ f" for (i in 0 until m) {{ {_SINK_KT} }}\n"+ "}\n",+ )+ assert kt[4] == ("bounded", "constant")+ assert kt[7] == ("unknown", "unknown")+++def test_a_kotlin_name_bound_to_itself_is_followed_once():+ kt = _loops(+ "F.kt",+ "kotlin",+ "class C(val length: Int) {\n"+ " fun f(stmt: Statement) {\n"+ " val length = length\n"+ f" for (i in 0 until length) {{ {_SINK_KT} }}\n"+ " }\n"+ "}\n",+ )+ assert kt[4] == ("unknown", "unknown")+++_SINK_RS = 'sqlx::query("x").fetch_one(pool).await?;'+++def test_rust_shadowing_mutation_and_macros_bound_nothing():+ rs = _loops(+ "f.rs",+ "rust",+ "static mut XS: [i32; 2] = [1, 2];\n"+ "const KS: [i32; 2] = [1, 2];\n"+ "fn f(pool: &PgPool, KS: Vec<i32>, other: Vec<i32>) {\n"+ f" for x in XS {{ {_SINK_RS} }}\n"+ f" for k in KS {{ {_SINK_RS} }}\n"+ " let ys = vec![1, 2];\n"+ " let ys = other;\n"+ f" for y in ys {{ {_SINK_RS} }}\n"+ " let mut zs = vec![1, 2];\n"+ " fill(&mut zs);\n"+ f" for z in zs {{ {_SINK_RS} }}\n"+ f" for m in my_items!() {{ {_SINK_RS} }}\n"+ " let ws = vec![1, 2];\n"+ " show(&ws);\n"+ f" for w in &ws {{ {_SINK_RS} }}\n"+ "}\n",+ )+ assert rs[4] == ("unknown", "unknown") # static mut+ assert rs[5] == ("unknown", "parameter") # a parameter shadows the const+ assert rs[8] == ("unknown", "unknown") # bound twice+ assert rs[11] == ("unknown", "unknown") # handed out as ``&mut``+ assert rs[12] == ("unknown", "unknown") # a macro other than ``vec!``+ assert rs[15] == ("bounded", "constant") # a shared borrow cannot grow it+++_SINK_CPP = 'sqlite3_exec(db, "x", 0, 0, 0);'+++def test_cpp_a_namespace_const_does_not_reach_a_local_or_member_of_the_same_name():+ cpp = _loops(+ "f.cpp",+ "cpp",+ "namespace n { static const int kItems[] = {1, 2}; }\n"+ "void f(sqlite3* db, const std::vector<int>& kItems) {\n"+ f" for (int x : kItems) {{ {_SINK_CPP} }}\n"+ "}\n"+ "void g(sqlite3* db) {\n"+ " std::vector<int> kItems;\n"+ " fill(kItems);\n"+ f" for (int x : kItems) {{ {_SINK_CPP} }}\n"+ "}\n"+ "void h(sqlite3* db) {\n"+ " const int* kItems = nullptr;\n"+ f" for (int i = 0; i < 2; ++i) {{ for (int x : kItems) {{ {_SINK_CPP} }} }}\n"+ "}\n"+ "struct S {\n"+ " std::vector<int> kItems;\n"+ f" void m(sqlite3* db) {{ for (int x : kItems) {{ {_SINK_CPP} }} }}\n"+ "};\n"+ "void k(sqlite3* db) {\n"+ f" for (int x : kItems) {{ {_SINK_CPP} }}\n"+ " std::vector<int> local = {1, 2};\n"+ " fill(local);\n"+ f" for (int x : local) {{ {_SINK_CPP} }}\n"+ " my::array<int, 4> fake;\n"+ f" for (int x : fake) {{ {_SINK_CPP} }}\n"+ "}\n",+ )+ assert cpp[3] == ("unknown", "parameter")+ assert cpp[8] == ("unknown", "unknown") # declared without a value+ assert cpp[12] == ("unknown", "unknown") # a null pointer, not the const+ assert cpp[16] == ("unknown", "unknown") # a member+ assert cpp[19] == ("bounded", "constant") # the namespace const itself+ assert cpp[22] == ("unknown", "unknown") # handed to a call by reference+ assert cpp[24] == ("unknown", "unknown") # not ``std::array``+++ ("language", "src"),+ [+ ("rust", "fn f(xs: &[i64]) {{ for x in xs{} {{ }} }}", ),+ ("kotlin", "fun f(xs: List<Int>) {{ for (x in xs{}) {{ }} }}"),+ ],+)+def test_a_header_chain_hundreds_of_links_long_stays_unknown(language, src):+ from tree_sitter import Parser++ from repowise.core.analysis.health.perf.dialects import PERF_DIALECTS+ from repowise.core.ingestion.parser import _get_language++ link = ".iter().map(|x| x)" if language == "rust" else ".filter { it > 0 }"+ tree = Parser(_get_language(language)).parse(src.format(link * 2000).encode())+ loop = next(n for n in _nodes(tree.root_node) if n.type in ("for_expression", "for_statement"))+ assert PERF_DIALECTS[language].loop_source(loop, lambda call: None) is None+++def _nodes(root):+ stack = [root]+ while stack:+ node = stack.pop()+ yield node+ stack.extend(node.children)+++_RECURSIVE = (+ "WITH RECURSIVE tree(id) AS (SELECT id FROM s WHERE id = ? "+ "UNION SELECT s.id FROM s JOIN tree ON s.parent_id = tree.id) SELECT * FROM tree"+)++[email protected]("sql", ["SELECT id FROM t", "SELECT id FROM t LIMIT ?", _RECURSIVE])+def test_a_bound_limit_or_a_read_below_one_row_only_moves_a_loop_to_unknown(sql):+ """In every dialect on the shared reader, not only the three above. Python+ sizes a read with its own rules, which these do not change."""+ grows = sql == "SELECT id FROM t"+ go = _loops(+ "f.go",+ "go",+ 'package m\nimport "database/sql"\n'+ "func f(db *sql.DB, n int) {\n"+ f' rows, _ := db.Query("{sql}", n)\n'+ ' for rows.Next() { db.Exec("x") }\n'+ "}\n",+ )+ java = _loops(+ "A.java",+ "java",+ "import java.sql.*;\n"+ "class A { void f(Statement stmt, UserRepository userRepository) {\n"+ f' ResultSet rs = stmt.executeQuery("{sql}");\n'+ " while (rs.next()) { userRepository.findById(rs.getLong(1)); } } }\n",+ )+ py = _loops(+ "a.py",+ "python",+ "import sqlite3\n"+ "def f(conn):\n"+ f' rows = conn.execute("{sql}").fetchall()\n'+ " for r in rows:\n"+ ' conn.execute("UPDATE t SET x = 1 WHERE id = ?", (r[0],))\n',+ )+ for found, line in ((go, 5), (java, 4)):+ assert found[line] == ("grows_with_data" if grows else "unknown", "query")+ assert py[5][0] == "grows_with_data"+++_ALL_ROOTS = (+ "WITH RECURSIVE tree(id) AS (SELECT id FROM s WHERE parent_id IS NULL "+ "UNION SELECT s.id FROM s JOIN tree ON s.parent_id = tree.id WHERE s.id = ?) SELECT * FROM tree"+)++[email protected](("sql", "parent"), [(_RECURSIVE, True), (_ALL_ROOTS, False)])+def test_a_recursive_read_is_one_row_s_tree_only_when_its_seed_keys_on_one_id(sql, parent):+ from repowise.core.analysis.health.perf import loop_lexicon as lex++ assert lex.is_parent_key_filter(sql.encode()) is parent+ go = _loops(+ "f.go",+ "go",+ 'package m\nimport "database/sql"\n'+ "func f(db *sql.DB, n int) {\n"+ f' rows, _ := db.Query("{sql}", n)\n'+ ' for rows.Next() { db.Exec("x") }\n'+ "}\n",+ )+ assert go[5] == ("unknown" if parent else "grows_with_data", "query")