Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(health): classify each leaf of a grouped Rust use statement on its own (#3076)
Aman74d47a76e2ed
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.pyindex 87f956a26..d50f90712 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@@ -123,10 +123,12 @@ def _classify_import(node: _NodeLike) -> tuple[str | None, list[str]]:finding when it is later *called as an execution sink*, which a non-I/Osymbol never is.- When a statement names several I/O modules (a Rust ``use { ... }`` block),- the first one in source order wins, and within one token its most specific- (longest) variant. The order is fixed so the result never depends on set- iteration, which varies with ``PYTHONHASHSEED``.+ Within one token, the most specific (longest) variant wins; candidates are+ tried in a fixed order so the result never depends on set iteration, which+ varies with ``PYTHONHASHSEED``. Rust ``use`` declarations do not reach this+ function at all — :func:`_classify_rust_leaf` classifies each flattened+ leaf of the use tree on its own, so a grouped ``use { ... }`` cannot bind+ one member's kind onto another (#2894)."""text = _decode(node)# TS / JS module sources are quoted string literals, tried first; then@@ -150,6 +152,116 @@ def _classify_import(node: _NodeLike) -> tuple[str | None, list[str]]:return kind, bound+def _rust_use_argument(node: _NodeLike) -> _NodeLike | None:+ """The use tree of a ``use_declaration`` (the part after ``use``)."""+ arg = node.child_by_field_name("argument") if hasattr(node, "child_by_field_name") else None+ if arg is not None:+ return arg+ for child in node.children:+ if child.type not in ("use", ";", "pub", "visibility_modifier"):+ return child+ return None+++def _rust_leaf_bound_names(path: str) -> list[str]:+ """Every identifier segment of one leaf's own path, for over-binding.++ Mirrors :func:`_classify_import`'s bound-name extraction (every+ identifier-looking token of the classified unit's own text binds), but+ scoped to one leaf's path instead of a whole statement's text — so+ ``std::fs::File`` binds both ``fs`` and ``File``, and a sibling leaf in+ the same group (``collections::HashMap``) binds neither.+ """+ return [+ t for t in re.split(r"[^A-Za-z0-9_]+", path) if t.isidentifier() and t not in _IMPORT_KW+ ]+++def _rust_use_leaves(+ node: _NodeLike, prefix: str = "", depth: int = 0+) -> list[tuple[str, list[str]]]:+ """Flatten a Rust use tree into one ``(full_path, bound_names)`` per leaf.++ A brace group (``use a::{b::c, d}``) names members from different+ sub-paths; walking to each leaf keeps every member's own path distinct+ instead of classifying the whole group as one unresolvable string (#2894).+ Loosely mirrors ``ingestion.extractors.bindings.rust.expand_rust_use_tree``+ (one leaf per import, same tree shapes), but stays duck-typed on+ ``node.text`` instead of threading a source string through, and binds+ every segment of a leaf's own path rather than only its final one, since+ an over-bound non-callable name is harmless here (see module docstring)+ and a ``use std::{fs::File, ...}``-shaped leaf should still classify+ ``fs`` itself.+ """+ if depth > 10:+ return []+ get = node.child_by_field_name if hasattr(node, "child_by_field_name") else lambda _f: None+ if node.type == "scoped_use_list":+ path_node = get("path")+ list_node = get("list")+ new_prefix = f"{prefix}::{_decode(path_node)}" if path_node is not None else prefix+ if list_node is None:+ return []+ return _rust_use_leaves(list_node, new_prefix, depth + 1)+ if node.type == "use_list":+ out: list[tuple[str, list[str]]] = []+ for child in node.children:+ if child.type in ("{", "}", ","):+ continue+ out.extend(_rust_use_leaves(child, prefix, depth + 1))+ return out+ if node.type == "use_wildcard":+ return [(f"{prefix}::*" if prefix else "*", [])]+ if node.type == "use_as_clause":+ path_node = get("path")+ alias_node = get("alias")+ if path_node is None or alias_node is None:+ return []+ alias = _decode(alias_node)+ text = _decode(path_node)+ path = prefix if text == "self" and prefix else (f"{prefix}::{text}" if prefix else text)+ # An alias replaces the imported name entirely: only ``C`` is a real+ # identifier after ``use reqwest::Client as C;``, never ``Client``.+ return [(path, [alias] if alias.isidentifier() else [])]+ text = _decode(node)+ # ``{self}`` names the enclosing path itself: ``a::{self}`` binds ``a``.+ path = prefix if text == "self" and prefix else (f"{prefix}::{text}" if prefix else text)+ return [(path, _rust_leaf_bound_names(path))]+++def _classify_rust_leaf(path: str) -> str | None:+ """``io_kind`` for one flattened Rust use-tree leaf path, or ``None``.++ Reuses :func:`_candidate_variants`' segment/prefix expansion and local-root+ exclusion (``crate::`` / ``self::`` / ``super::`` never classify), applied+ to one leaf's own path instead of a whole statement's regex-tokenized text.+ """+ for cand in sorted(_candidate_variants(path), key=lambda c: (-len(c), c)):+ kind = classify_io_kind(cand)+ if kind:+ return kind+ return None+++def _bind_rust_use_names(node: _NodeLike, names: dict[str, str]) -> None:+ """Bind the I/O names one Rust ``use_declaration`` brings in.++ A Rust ``use`` statement is flattened to one leaf per imported member+ and each leaf classified on its own, so a grouped import+ (``use std::{fs::File, collections::HashMap};``) cannot let one+ member's kind leak onto another (#2894). A single-path ``use`` flattens+ to one leaf too, so behaviour there is unchanged.+ """+ arg = _rust_use_argument(node)+ if arg is None:+ return+ for path, bound in _rust_use_leaves(arg):+ kind = _classify_rust_leaf(path)+ if kind is not None:+ for name in bound:+ names.setdefault(name, kind)++def collect_io_names(tree_root: _NodeLike, language: str) -> dict[str, str]:"""Map every imported identifier that resolves to an I/O library → io_kind.@@ -217,6 +329,8 @@ def _io_visit(if kind is not None:for name in bound:names.setdefault(name, kind)+ elif node_type == "use_declaration" and language == "rust":+ _bind_rust_use_names(node, names)elif "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``diff --git a/tests/unit/health/test_perf_io_in_loop.py b/tests/unit/health/test_perf_io_in_loop.pyindex f126a9585..96e461369 100644--- a/tests/unit/health/test_perf_io_in_loop.py+++ b/tests/unit/health/test_perf_io_in_loop.py@@ -354,18 +354,49 @@ def test_python_fixture_counts():@pytest.mark.parametrize(- "use_block,expected",- [- (b"use {std::fs, reqwest::Client};\n", "filesystem"),- (b"use {reqwest::Client, std::fs};\n", "network"),- ],+ "use_block",+ [b"use {std::fs, reqwest::Client};\n", b"use {reqwest::Client, std::fs};\n"],)-def test_a_use_block_naming_two_io_modules_takes_the_first(use_block, expected):- # Picking from an unordered set made the kind follow PYTHONHASHSEED. Under- # any seed the old pick agreed for both orders, so one case failed.+def test_a_use_block_naming_two_io_modules_keeps_each_members_own_kind(use_block):+ # #2894: a grouped use statement no longer lets the first classifying+ # module win the whole group. Each member keeps its own kind, in either+ # source order.fc = walk_file("t.rs", "rust", use_block + b"fn f() {}\n")- assert fc.io_boundary_names- assert set(fc.io_boundary_names.values()) == {expected}+ assert fc.io_boundary_names["fs"] == "filesystem"+ assert fc.io_boundary_names["Client"] == "network"+++def test_a_use_block_naming_two_different_filesystem_and_collection_members():+ # The in-group name a module resolves through (``fs``) never binds a+ # sibling member's unrelated name (``collections``/``HashMap``).+ fc = walk_file(+ "t.rs", "rust", b"use std::{fs::File, collections::HashMap};\nfn f() {}\n"+ )+ assert fc.io_boundary_names["fs"] == "filesystem"+ assert fc.io_boundary_names["File"] == "filesystem"+ assert "collections" not in fc.io_boundary_names+ assert "HashMap" not in fc.io_boundary_names+++def test_a_nested_use_group_classifies_each_leaf_on_its_own():+ fc = walk_file(+ "t.rs", "rust", b"use tokio::{fs, net::TcpStream};\nfn f() {}\n"+ )+ assert fc.io_boundary_names["fs"] == "filesystem"+++def test_a_use_alias_binds_only_the_local_alias_name():+ fc = walk_file("t.rs", "rust", b"use reqwest::Client as C;\nfn f() {}\n")+ assert fc.io_boundary_names == {"C": "network"}+++def test_io_in_loop_fires_regardless_of_grouped_use_order():+ # The issue's own repro: a db execute sink must be found whichever order+ # the grouped use's two modules are written in.+ for use_block in (b"use {std::fs, sqlx::PgPool};\n", b"use {sqlx::PgPool, std::fs};\n"):+ src = use_block + b"fn f(c: &PgPool, xs: &[i32]) { for i in xs { c.execute(i); } }\n"+ fc = walk_file("t.rs", "rust", src)+ assert ("io_in_loop", "db") in {(h.kind, h.detail) for h in fc.perf_hits}class _FakeImportNode: