Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(health): add Rust performance dialect (#581)

Raghav Chamadiya93716aa4075e
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.md
index c69f021f0..0eef9ed43 100644
--- a/docs/LANGUAGE_SUPPORT.md
+++ b/docs/LANGUAGE_SUPPORT.md
@@ -463,12 +463,17 @@ findings.
| Java | Y | Y | resource_construction, lock | `regex_compile_in_loop` | --- (no async syntax) |
| Go | Y | Y | resource_construction, lock | `defer_in_loop`, `regex_compile_in_loop` | --- (goroutines) |
| C# | Y | Y | resource_construction, lock, serial_await | --- (.NET caches regexes) | `blocking_sync_in_async` (`.Result` / `.Wait()` / `.GetResult()`) |
-| Kotlin / Rust / C++ | --- | --- | --- | --- | --- |
-
-Kotlin will be nearly free once it rides the JVM lexicon; Rust (sqlx /
-reqwest) and C++ are later. What each dialect classifies as a db / network /
-filesystem / subprocess sink, and the per-language precision hazards, lives
-in `docs/CODE_HEALTH.md` and
+| Rust | Y | --- (`String` is amortized) | resource_construction, serial_await | `regex_compile_in_loop` (`Regex::new`) | `blocking_sync_in_async` (`block_on` / `std::thread::sleep` / sync `std::fs` in `async fn`) |
+| Kotlin / C++ | --- | --- | --- | --- | --- |
+
+The Rust dialect classifies `sqlx` executor verbs (db), `reqwest::get` /
+`reqwest::post` and `std::fs` (network / filesystem) as sinks; `io_in_loop` is
+multi-repo validated (85% on bevy / rtk / deepwiki-rs). `string_concat_in_loop`
+is intentionally absent — Rust `String::push_str` / `+=` are amortized O(1), so
+it would be a guaranteed false positive. Kotlin will be nearly free once it
+rides the JVM lexicon; C++ is later. What each dialect classifies as a db /
+network / filesystem / subprocess sink, and the per-language precision hazards,
+lives in `docs/CODE_HEALTH.md` and
`local-stash/performance-pillar/PHASE6_PLAN.md`.
---
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
index cb4e57fa9..80d8f0081 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -268,6 +268,12 @@ _RUST = LanguageNodeMap(
member_access_kinds=frozenset({"field_expression"}),
# ``assert!`` / ``assert_eq!`` / ``assert_ne!`` are macro invocations.
assert_call_kinds=frozenset({"macro_invocation"}),
+ # The perf pass: both ``foo()`` and method/scoped calls (``x.fetch_all()`` /
+ # ``std::fs::read()``) parse as ``call_expression``. Rust has no dedicated
+ # async function node type — ``async fn`` is a ``function_item`` carrying a
+ # ``function_modifiers`` child — so ``async_function_kinds`` stays empty and
+ # ``RustPerfDialect.is_async_fn`` sniffs the modifier instead.
+ call_kinds=frozenset({"call_expression"}),
)
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py
index 0dc4b9366..837d5cee8 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py
@@ -18,6 +18,7 @@ from . import csharp as _csharp
from . import go as _go
from . import java as _java
from . import python as _python
+from . import rust as _rust
from . import ts_js as _ts_js
from .base import PERF_DIALECTS, BasePerfDialect
@@ -33,6 +34,7 @@ _REGISTER: tuple[tuple[str, BasePerfDialect], ...] = (
("java", _java.DIALECT),
("go", _go.DIALECT),
("csharp", _csharp.DIALECT),
+ ("rust", _rust.DIALECT),
)
for _tag, _dialect in _REGISTER:
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.py
new file mode 100644
index 000000000..468244a45
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/rust.py
@@ -0,0 +1,278 @@
+"""Rust ``PerfDialect``.
+
+Flagship: a ``sqlx`` query or a ``std::fs`` / ``reqwest`` round-trip inside a
+``for … in collection`` loop (the Rust N+1). Rust-distinctive markers ride along:
+
+* ``regex_compile_in_loop`` — ``Regex::new("…")`` recompiled every iteration
+ instead of hoisted into a ``once_cell`` / ``lazy_static``. Compiling a Rust
+ ``regex`` is famously expensive, so this is the same high-precision marker
+ Java/Go already emit; clippy has no in-loop analogue.
+* ``resource_construction_in_loop`` — a fresh ``reqwest::Client::new()`` /
+ ``PgPool::connect()`` / ``redis::Client::open()`` per iteration instead of a
+ hoisted, pooled one.
+* ``blocking_sync_in_async`` — a synchronous, executor-blocking call inside an
+ ``async fn``: ``block_on`` (the canonical deadlock-shaped smell),
+ ``std::thread::sleep`` (use ``tokio::time::sleep().await``), and the sync
+ ``std::fs`` family (use ``tokio::fs`` / ``spawn_blocking``). The walker's ``not
+ awaited`` gate excludes the async ``tokio::*`` equivalents by construction
+ (they are always ``.await``ed).
+
+Rust has no compile-optimization hazard around ``String`` building — ``push_str``
+/ ``+=`` on a ``String`` are amortized O(1) (the buffer grows geometrically), so
+``string_concat_in_loop`` is deliberately NOT in :attr:`markers` (it would be a
+guaranteed-FP marker — the language-scope rule in ``MARKER_BACKLOG.md``).
+
+The per-grammar seam: Rust spells free calls (``foo()``), method calls
+(``x.fetch_all()`` -> ``call_expression`` over a ``field_expression``) and
+scoped/associated calls (``std::fs::read()`` / ``Regex::new()`` ->
+``call_expression`` over a ``scoped_identifier``) all as ``call_expression``. The
+base extraction returns the right method for every form and the right root for
+the bare/method forms; :meth:`callee_root_name` is overridden so a scoped call's
+"root" is its module/type QUALIFIER (``std::fs::read`` -> ``fs``, ``reqwest::get``
+-> ``reqwest``, ``File::open`` -> ``File``), letting ``sink_kind`` match on the
+distinctive segment instead of the leftmost crate root (which would be ``std``).
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from .base import BasePerfDialect
+from .python import HTTP_VERBS
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
+
+# Rust string-literal node kinds (the hoistable-pattern gate).
+_RUST_STRING_KINDS: frozenset[str] = frozenset({"string_literal", "raw_string_literal"})
+
+# ``std::fs`` / ``tokio::fs`` / ``async_std::fs`` filesystem round-trips, keyed on
+# the function name once an ``fs`` module qualifier is the callee root.
+RUST_FS_METHODS: frozenset[str] = frozenset(
+ {
+ "read",
+ "write",
+ "read_to_string",
+ "read_dir",
+ "copy",
+ "rename",
+ "remove_file",
+ "remove_dir",
+ "remove_dir_all",
+ "create_dir",
+ "create_dir_all",
+ "metadata",
+ "canonicalize",
+ "hard_link",
+ "read_link",
+ "set_permissions",
+ }
+)
+# The synchronous, executor-blocking subset — flagged inside an ``async fn`` as
+# ``blocking_sync_in_async`` (use ``tokio::fs`` / ``spawn_blocking``).
+RUST_SYNC_FS_METHODS: frozenset[str] = frozenset(
+ {
+ "read",
+ "write",
+ "read_to_string",
+ "read_dir",
+ "copy",
+ "remove_file",
+ "create_dir",
+ "create_dir_all",
+ "metadata",
+ }
+)
+# Distinctive sqlx / sea-orm executor verbs (a real DB round-trip, not a builder
+# step). ``fetch_all`` / ``fetch_one`` / ``fetch_optional`` are sqlx-only verbs
+# with no common non-db collision, so they fire un-gated; the ambiguous
+# ``execute`` is gated on db-import evidence.
+RUST_DB_EXEC: frozenset[str] = frozenset({"fetch_all", "fetch_one", "fetch_optional"})
+
+# Heavy connection / client constructors keyed ``(type_qualifier, method)``.
+# ``PgPool::connect`` etc. are distinctive on their own; ``Client::new`` /
+# ``Client::open`` collide (many types have ``new``) so they are gated on a
+# ``reqwest`` / ``redis`` segment in :meth:`loop_call_marker`.
+RUST_RESOURCE_CTORS: frozenset[tuple[str, str]] = frozenset(
+ {
+ ("PgPool", "connect"),
+ ("MySqlPool", "connect"),
+ ("SqlitePool", "connect"),
+ ("AnyPool", "connect"),
+ ("Pool", "connect"),
+ ("PgConnection", "connect"),
+ ("MySqlConnection", "connect"),
+ ("SqliteConnection", "connect"),
+ ("PgPoolOptions", "connect_lazy"),
+ }
+)
+# ``Regex::new`` / ``RegexBuilder::new`` — the recompile-in-loop type qualifiers.
+RUST_REGEX_TYPES: frozenset[str] = frozenset({"Regex", "RegexBuilder", "RegexSet"})
+
+
+def _scoped_segments(call_node: Node) -> list[str] | None:
+ """Segments of a ``scoped_identifier`` callee (``std::fs::read`` ->
+ ``['std', 'fs', 'read']``), or ``None`` when the callee is a bare or method
+ call. The last element is the called function / associated name."""
+ fn = call_node.child_by_field_name("function")
+ if fn is None or fn.type != "scoped_identifier":
+ return None
+ txt = (fn.text or b"").decode("utf-8", "replace")
+ segs = [s for s in txt.split("::") if s]
+ return segs or None
+
+
+class RustPerfDialect(BasePerfDialect):
+ language = "rust"
+ markers = frozenset(
+ {
+ "io_in_loop",
+ "blocking_sync_in_async",
+ "regex_compile_in_loop",
+ "resource_construction_in_loop",
+ "serial_await_in_loop",
+ # Phase 7b — centrality-gated / nesting-confidence markers (parity).
+ "nested_loop_with_io",
+ "nested_loop_quadratic",
+ "hot_path_sync_io",
+ }
+ )
+
+ # -- callee extraction (the per-grammar seam) -----------------------------
+
+ def callee_root_name(self, call_node: Node) -> str | None:
+ """For a scoped/associated call, the QUALIFIER segment (the one before
+ the called name): ``std::fs::read`` -> ``fs``, ``reqwest::get`` ->
+ ``reqwest``, ``File::open`` -> ``File``, ``reqwest::Client::new`` ->
+ ``Client``. For bare/method calls, the base extraction (the receiver /
+ function identifier) is correct."""
+ segs = _scoped_segments(call_node)
+ if segs is not None and len(segs) >= 2:
+ return segs[-2]
+ return super().callee_root_name(call_node)
+
+ # -- sink classification --------------------------------------------------
+
+ def sink_kind(
+ self,
+ root: str,
+ method: str,
+ *,
+ awaited: bool,
+ is_attribute: bool,
+ io_names: dict[str, str],
+ has_db_import: bool,
+ ) -> str | None:
+ # Scoped/associated calls (``not is_attribute``): ``root`` is the
+ # module/type qualifier supplied by :meth:`callee_root_name`.
+ if not is_attribute:
+ if root == "fs" and method in RUST_FS_METHODS:
+ return "filesystem"
+ if root == "File" and method in ("open", "create"):
+ return "filesystem"
+ if root == "reqwest" and method in HTTP_VERBS:
+ return "network"
+ return None
+ # Method call on a receiver (``q.fetch_all(&pool)``).
+ if method in RUST_DB_EXEC:
+ return "db"
+ if method == "execute" and (has_db_import or io_names.get(root) == "db"):
+ return "db"
+ return None
+
+ # -- loop / async predicates ----------------------------------------------
+
+ def is_constant_loop(self, node: Node) -> bool:
+ """``for _ in 0..10`` (an integer-literal range) is a bounded count loop,
+ not a data-dependent N+1. ``for x in 0..n`` / ``for x in items`` and
+ ``while`` / ``loop`` are real loops."""
+ if node.type != "for_expression":
+ return False
+ val = node.child_by_field_name("value")
+ if val is None or val.type != "range_expression":
+ return False
+ named = [c for c in val.children if c.is_named]
+ return bool(named) and all(c.type == "integer_literal" for c in named)
+
+ def is_iteration_loop(self, node: Node) -> bool:
+ """Only ``for x in collection`` multiplies over data; ``while`` / ``loop``
+ spin a cursor (the ``nested_loop_with_io`` outer-loop gate)."""
+ return node.type == "for_expression"
+
+ def loop_iterable_name(self, node: Node) -> str | None:
+ """The collection a ``for x in coll`` loop iterates (``coll``) — the
+ same-collection ``nested_loop_quadratic`` shape gate."""
+ if node.type != "for_expression":
+ return None
+ val = node.child_by_field_name("value")
+ if val is None:
+ return None
+ if val.type in ("identifier", "field_expression"):
+ return self._dotted_path(val)
+ return None
+
+ def is_async_fn(self, node: Node) -> bool:
+ """``async fn`` carries an ``async`` token inside a ``function_modifiers``
+ child (tree-sitter-rust has no dedicated async function node type)."""
+ return any(
+ c.type == "function_modifiers" and any(cc.type == "async" for cc in c.children)
+ for c in node.children
+ )
+
+ def blocking_sync_api(self, root: str, method: str) -> str | None:
+ """Executor-blocking sync calls flagged inside an ``async fn``.
+
+ The walker only calls this for a NON-awaited call, which excludes the
+ async ``tokio::*`` equivalents (always ``.await``ed) by construction, so
+ the ``sleep`` / ``fs`` matches cannot collide with their async forms.
+ ``root`` is the scoped qualifier (``std::fs::read`` -> ``fs``,
+ ``std::thread::sleep`` -> ``thread``).
+ """
+ if method == "block_on":
+ # ``futures::executor::block_on`` / ``Handle::block_on`` inside async
+ # blocks the executor thread — the canonical sync-in-async smell.
+ return "block_on"
+ if root in ("std", "thread") and method == "sleep":
+ return "thread::sleep"
+ if root in ("std", "fs") and method in RUST_SYNC_FS_METHODS:
+ return f"fs::{method}"
+ return None
+
+ # -- extra-marker hooks ---------------------------------------------------
+
+ def loop_call_marker(
+ self, root: str, method: str, node: Node, list_names: frozenset[str]
+ ) -> str | None:
+ segs = _scoped_segments(node)
+ if segs is None or len(segs) < 2:
+ return None
+ type_seg = segs[-2]
+ earlier = {s.lower() for s in segs[:-2]}
+ # ``Regex::new("^…$")`` recompiled per iteration — only a string-literal
+ # pattern is unambiguously hoistable (a dynamic ``Regex::new(&pat)`` may
+ # legitimately vary), mirroring the Go/Java regex gate.
+ if type_seg in RUST_REGEX_TYPES and method == "new" and self._has_static_pattern_arg(node):
+ return "regex_compile_in_loop"
+ # Heavy connection/client constructors per iteration.
+ if (type_seg, method) in RUST_RESOURCE_CTORS:
+ return "resource_construction_in_loop"
+ # ``reqwest::Client::new()`` / ``redis::Client::open()`` — the generic
+ # ``Client`` qualifier is gated on the distinctive crate segment.
+ if type_seg == "Client" and method == "new" and "reqwest" in earlier:
+ return "resource_construction_in_loop"
+ if type_seg == "Client" and method == "open" and "redis" in earlier:
+ return "resource_construction_in_loop"
+ return None
+
+ @staticmethod
+ def _has_static_pattern_arg(node: Node) -> bool:
+ """True if the call's first argument is a compile-time string literal
+ (``Regex::new("^x$")`` is hoistable; ``Regex::new(&pat)`` is not)."""
+ args = node.child_by_field_name("arguments")
+ if args is None:
+ return False
+ first = next((c for c in args.children if c.is_named), None)
+ return first is not None and first.type in _RUST_STRING_KINDS
+
+
+DIALECT = RustPerfDialect()
diff --git a/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py b/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py
index 4a15234e9..c626129e4 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py
@@ -35,7 +35,7 @@ from ....ingestion.external_systems.io_kind import classify_io_kind
# Tokens that are syntax, not bindable import names.
_IMPORT_KW: frozenset[str] = frozenset(
- {"import", "from", "as", "require", "const", "let", "var", "default", "type", "typeof"}
+ {"import", "from", "as", "require", "const", "let", "var", "default", "type", "typeof", "use"}
)
@@ -70,9 +70,19 @@ def _candidate_variants(tok: str) -> set[str]:
parts = [p for p in tok.split("/") if p]
out.update(parts)
for seg in parts:
- dotted = seg.split(".")
- for i in range(1, len(dotted) + 1):
- out.add(".".join(dotted[:i]))
+ # Rust scoped paths use ``::`` (``std::fs::read`` / ``sqlx::query``).
+ # Decompose into interior segments + progressive ``::`` prefixes so
+ # ``use sqlx::Pool`` resolves via ``sqlx`` and ``use std::fs`` via the
+ # ``fs`` segment (already a filesystem name, cross-ecosystem). A no-op
+ # for the dotted/slash ecosystems (no ``::`` to split).
+ colon_parts = [c for c in seg.split("::") if c]
+ out.update(colon_parts)
+ for i in range(1, len(colon_parts) + 1):
+ out.add("::".join(colon_parts[:i]))
+ for cp in colon_parts:
+ dotted = cp.split(".")
+ for i in range(1, len(dotted) + 1):
+ out.add(".".join(dotted[:i]))
return out
@@ -124,9 +134,9 @@ def collect_io_names(tree_root: _NodeLike, language: str) -> dict[str, str]:
while stack:
node = stack.pop()
# ``import`` covers Python / TS / Java / Go import nodes; C# spells its
- # import a ``using_directive`` (and Go an ``import_spec``), neither of
- # which contains the substring "import".
- if "import" in node.type or node.type == "using_directive":
+ # import a ``using_directive`` (and Go an ``import_spec``), Rust a
+ # ``use_declaration`` — none of which contains the substring "import".
+ if "import" in node.type or node.type in ("using_directive", "use_declaration"):
# Classify only the *leaf* import node. A Go grouped
# ``import ( "database/sql"; "regexp" )`` is an ``import_declaration``
# wrapping per-line ``import_spec`` leaves; classifying the wrapper
diff --git a/packages/core/src/repowise/core/ingestion/external_systems/io_kind.py b/packages/core/src/repowise/core/ingestion/external_systems/io_kind.py
index 86cc8ec2e..7990b7228 100644
--- a/packages/core/src/repowise/core/ingestion/external_systems/io_kind.py
+++ b/packages/core/src/repowise/core/ingestion/external_systems/io_kind.py
@@ -59,6 +59,11 @@ _DB_NAMES: frozenset[str] = frozenset({
"microsoft.entityframeworkcore", "system.data.sqlclient",
"microsoft.data.sqlclient", "dapper", "npgsql", "mongodb.driver",
"stackexchange.redis",
+ # Rust (the crate root as imported, ``use sqlx::...`` -> ``sqlx``; both the
+ # hyphenated Cargo name and the underscore import alias are seeded). ``sqlx``
+ # is already listed under the Go section above.
+ "diesel", "sea-orm", "sea_orm", "tokio-postgres", "tokio_postgres",
+ "rusqlite", "deadpool-postgres", "deadpool_postgres", "scylla", "bb8",
})
_NETWORK_NAMES: frozenset[str] = frozenset({
@@ -75,6 +80,8 @@ _NETWORK_NAMES: frozenset[str] = frozenset({
"net/http", "grpc", "resty", "fasthttp",
# .NET
"system.net.http", "grpc.net.client", "restsharp", "flurl",
+ # Rust (HTTP / gRPC client crates as imported).
+ "reqwest", "hyper", "isahc", "surf", "ureq", "awc", "tonic",
})
_FILESYSTEM_NAMES: frozenset[str] = frozenset({
diff --git a/tests/fixtures/lang_samples/rust/perf_io_in_loop.rs b/tests/fixtures/lang_samples/rust/perf_io_in_loop.rs
new file mode 100644
index 000000000..a3411c22d
--- /dev/null
+++ b/tests/fixtures/lang_samples/rust/perf_io_in_loop.rs
@@ -0,0 +1,78 @@
+// Fixture for the Rust performance dialect (io_in_loop / regex_compile_in_loop /
+// resource_construction_in_loop / blocking_sync_in_async). Every POSITIVE is a
+// genuine per-iteration cost; every NEGATIVE is a shape the dialect must NOT
+// flag. Hand-counted expectations live in test_perf_dialects.py.
+//
+// NOTE: Rust `String` building (`push_str` / `+=`) is amortized O(1), so
+// `string_concat_in_loop` is intentionally not a Rust marker — the push_str
+// loop below is a NEGATIVE by design.
+
+use std::fs;
+
+// --- POSITIVES -------------------------------------------------------------
+
+async fn sqlx_fetch_in_loop(pool: &PgPool, ids: Vec<i32>) {
+ for id in ids {
+ // POSITIVE: a sqlx executor verb (db round-trip) per item, awaited
+ // (also a serial_await_in_loop co-signal).
+ let _ = sqlx::query("SELECT 1").fetch_all(pool).await;
+ }
+}
+
+fn fs_read_in_loop(paths: Vec<String>) {
+ for p in paths {
+ let _ = std::fs::read(&p); // POSITIVE: filesystem per item
+ }
+}
+
+fn fs_read_to_string_in_loop(paths: Vec<String>) {
+ for p in paths {
+ let _ = fs::read_to_string(&p); // POSITIVE: filesystem (short `fs::` path)
+ }
+}
+
+async fn reqwest_get_in_loop(urls: Vec<String>) {
+ for u in urls {
+ // POSITIVE: network per item, awaited (serial_await co-signal).
+ let _ = reqwest::get(&u).await;
+ }
+}
+
+fn regex_new_in_loop(items: Vec<String>) {
+ for x in items {
+ let re = Regex::new("^[a-z]+$"); // POSITIVE: static literal pattern, hoistable
+ let dyn_re = Regex::new(&x); // NEGATIVE: dynamic arg cannot be hoisted
+ let _ = (re, dyn_re);
+ }
+}
+
+async fn pgpool_connect_in_loop(urls: Vec<String>) {
+ for u in urls {
+ // POSITIVE: a fresh pooled connection per item (resource construction).
+ let _ = PgPool::connect(&u).await;
+ }
+}
+
+async fn thread_sleep_in_async(d: std::time::Duration) {
+ std::thread::sleep(d); // POSITIVE: blocking the executor inside an async fn
+}
+
+// --- NEGATIVES -------------------------------------------------------------
+
+fn fs_read_constant_loop() {
+ for _ in 0..10 {
+ let _ = std::fs::read("x"); // NEGATIVE: bounded integer-literal range
+ }
+}
+
+fn fs_read_outside_loop(p: String) {
+ let _ = std::fs::read(&p); // NEGATIVE: runs once, not in a loop
+}
+
+fn push_str_in_loop(items: Vec<String>) -> String {
+ let mut s = String::new();
+ for x in items {
+ s.push_str(&x); // NEGATIVE: amortized O(1) — not a Rust perf smell
+ }
+ s
+}
diff --git a/tests/unit/health/test_perf_dialects.py b/tests/unit/health/test_perf_dialects.py
index bba556f19..3de4d9baa 100644
--- a/tests/unit/health/test_perf_dialects.py
+++ b/tests/unit/health/test_perf_dialects.py
@@ -192,6 +192,111 @@ def test_csharp_cases(src, expected, note):
assert _hits("csharp", src) == sorted(expected), note
+# ---------------------------------------------------------------------------
+# Rust
+# ---------------------------------------------------------------------------
+
+
+def test_rust_fixture_counts():
+ fc = _walk("rust/perf_io_in_loop.rs", "rust")
+ counts = _kinds(fc.perf_hits)
+ # db (sqlx fetch_all) · filesystem (std::fs::read + fs::read_to_string) ·
+ # network (reqwest::get) = 4. The constant-range and out-of-loop reads and
+ # the push_str loop (amortized O(1)) do not fire.
+ assert counts["io_in_loop"] == 4
+ assert {h.detail for h in fc.perf_hits if h.kind == "io_in_loop"} == {
+ "db",
+ "filesystem",
+ "network",
+ }
+ # The two awaited sinks (sqlx + reqwest) carry the serial_await co-signal.
+ assert counts["serial_await_in_loop"] == 2
+ assert counts["regex_compile_in_loop"] == 1
+ assert counts["resource_construction_in_loop"] == 1
+ assert counts["blocking_sync_in_async"] == 1
+ # Rust String building is amortized, so string_concat is never a Rust marker.
+ assert counts["string_concat_in_loop"] == 0
+
+
+_RUST_CASES = [
+ (
+ "async fn f(pool: &PgPool, ids: Vec<i32>){ for id in ids { "
+ 'let _ = sqlx::query("x").fetch_one(pool).await; } }',
+ [("io_in_loop", "db"), ("serial_await_in_loop", "db")],
+ "a sqlx fetch_one verb in a for loop is an awaited db round-trip",
+ ),
+ (
+ "fn f(paths: Vec<String>){ for p in paths { let _ = std::fs::read(&p); } }",
+ [("io_in_loop", "filesystem")],
+ "std::fs::read keys on the `fs` module qualifier, not the `std` root",
+ ),
+ (
+ "use reqwest;\nasync fn f(urls: Vec<String>){ for u in urls { "
+ "let _ = reqwest::get(&u).await; } }",
+ [("io_in_loop", "network"), ("serial_await_in_loop", "network")],
+ "reqwest::get free function in a loop is a network round-trip",
+ ),
+ (
+ "async fn f(tx: Sender<i32>, n: i32){ for i in 0..n { tx.send(i).await; } }",
+ [],
+ "a channel tx.send(i).await is NOT a reqwest round-trip (no false sink)",
+ ),
+ (
+ 'fn f(items: Vec<i32>){ for x in items { let r = Regex::new("^a$"); let _ = r; } }',
+ [("regex_compile_in_loop", "")],
+ "Regex::new with a static literal pattern is hoistable",
+ ),
+ (
+ "fn f(items: Vec<String>){ for x in items { let r = Regex::new(&x); let _ = r; } }",
+ [],
+ "Regex::new with a dynamic arg may vary per iteration — not flagged",
+ ),
+ (
+ "async fn f(urls: Vec<String>){ for u in urls { let _ = PgPool::connect(&u).await; } }",
+ [("resource_construction_in_loop", "")],
+ "a fresh PgPool::connect per iteration is resource construction",
+ ),
+ (
+ "fn f(items: Vec<i32>){ let mut s = String::new(); "
+ "for x in items { s.push_str(&x.to_string()); } let _ = s; }",
+ [],
+ "String::push_str is amortized O(1) — Rust has no string_concat marker",
+ ),
+ (
+ "async fn f(){ let _ = futures::executor::block_on(g()); }",
+ [("blocking_sync_in_async", "block_on")],
+ "block_on inside an async fn blocks the executor",
+ ),
+]
+
+
[email protected]("src,expected,note", _RUST_CASES, ids=[c[2] for c in _RUST_CASES])
+def test_rust_cases(src, expected, note):
+ assert _hits("rust", src) == sorted(expected), note
+
+
+def test_rust_execute_gated_on_db_import():
+ """``.execute()`` is ambiguous, so it fires only with file-level db evidence
+ (a ``use sqlx::...`` resolved through the ``use_declaration`` io_names pass)."""
+ with_import = (
+ "use sqlx::PgPool;\nasync fn f(pool: &PgPool, ids: Vec<i32>){ "
+ 'for id in ids { let _ = sqlx::query("x").execute(pool).await; } }'
+ )
+ no_import = "async fn f(c: &Conn, ids: Vec<i32>){ for id in ids { c.execute(id); } }"
+ assert ("io_in_loop", "db") in _hits("rust", with_import)
+ assert not any(k == "io_in_loop" for k, _ in _hits("rust", no_import))
+
+
+def test_rust_fs_in_async_blocks():
+ """Sync ``std::fs`` inside an ``async fn`` is executor-blocking; the awaited
+ ``tokio::fs`` equivalent is excluded by the walker's not-awaited gate."""
+ blocking = "async fn f(p: String){ let _ = std::fs::read(&p); }"
+ assert ("blocking_sync_in_async", "fs::read") in _hits("rust", blocking)
+ # tokio::fs::read is always awaited -> never read as a blocking sync call.
+ awaited = "async fn f(p: String){ let _ = tokio::fs::read(&p).await; }"
+ assert not any(k == "blocking_sync_in_async" for k, _ in _hits("rust", awaited))
+
+
# ---------------------------------------------------------------------------
# Phase-7c precision fixes (multi-language corpus FP classes)
# ---------------------------------------------------------------------------