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(dead-code): a VB.NET Module is used when its members are (#3509)
Raghav Chamadiya4c1e31fe3a9b
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex c8f8e2cdf..ddc91fd83 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -91,6 +91,7 @@ from .risk_factors import (path_risk_factors,risk_evidence,)+from .vbnet_modules import vbnet_module_names#: The unindexed scan below and the repo-wide absence check ask the same#: question of different file sets, so they share one identifier shape rather@@ -738,7 +739,8 @@ class _ExportFile:# ``using`` names a namespace, so neither says anything about a symbol.importers_name_symbols: bool# Classes holding C# extension methods, called as ``x.Method()`` without- # naming the class, so no importer would name them either.+ # naming the class, and VB.NET Modules, whose members are in scope+ # unqualified: no importer would name either.extension_containers: frozenset[str]imported_as_namespace: boolenclosing_ranges: list[tuple[int, int]]@@ -1462,7 +1464,7 @@ class DeadCodeAnalyzer:node_data=node_data,symbol_pairs=symbol_pairs,importers_name_symbols=self._importers_name_symbols(node, symbols),- extension_containers=self._extension_containers(node_data, symbol_pairs),+ extension_containers=self._extension_containers(node, node_data, symbol_pairs),imported_as_namespace=self._imported_as_namespace(node, node_data),# Function bodies, so nested defs (closures) can be skipped.enclosing_ranges=[@@ -1482,12 +1484,15 @@ class DeadCodeAnalyzer:)def _extension_containers(- self, node_data: dict, symbol_pairs: list[tuple[str, dict]]+ self, node: Any, node_data: dict, symbol_pairs: list[tuple[str, dict]]) -> frozenset[str]:- """Names of the classes in this file that declare a C# extension method."""+ """Containers here a use never names: C# extension holders, VB.NET Modules."""if node_data.get("language") not in _CONTAINER_USE_LANGUAGES:return frozenset()- return frozenset(+ modules = vbnet_module_names(+ (sym for _, sym in symbol_pairs), self._source_map.get(str(node))+ )+ return modules | frozenset(sym.get("name", "")for sym_id, sym in symbol_pairsif self._declares_extension_method(sym_id)@@ -1695,7 +1700,7 @@ class DeadCodeAnalyzer:Not when no importer names this file's symbols; not where thepreprocessor reaches a symbol through macros, typedef aliases and token- pasting; not for a class holding C# extension methods.+ pasting; not for a C# extension holder or a VB.NET Module."""return (file_ctx.importers_name_symbolsdiff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.pyindex 7e15830eb..0db524073 100644--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py@@ -998,9 +998,9 @@ _PURE_WRAPPER_DECORATOR_ATTRS: frozenset[str] = frozenset()# Languages whose idiom is a static holder class the call site never names,-# because it names only the member (C# extension methods). A set so widening it-# is a deliberate act.-_CONTAINER_USE_LANGUAGES: frozenset[str] = frozenset({"csharp"})+# because it names only the member (C# extension methods, VB.NET Modules). A+# set so widening it is a deliberate act.+_CONTAINER_USE_LANGUAGES: frozenset[str] = frozenset({"csharp", "vbnet"})# Languages whose files are run, never imported: a directory holding only these# (a ``docker/`` folder of Dockerfiles and an entrypoint script) is not a packagediff --git a/packages/core/src/repowise/core/analysis/dead_code/vbnet_modules.py b/packages/core/src/repowise/core/analysis/dead_code/vbnet_modules.pynew file mode 100644index 000000000..aa799fd73--- /dev/null+++ b/packages/core/src/repowise/core/analysis/dead_code/vbnet_modules.py@@ -0,0 +1,58 @@+"""VB.NET ``Module``s: containers a use of their members never names.++A Module's members are in scope unqualified wherever its namespace is visible+(an ``Imports`` line, the project's root namespace, a project-level import),+so call sites write ``ShowProgramInfo()`` and never ``MainMod.ShowProgramInfo()``.+No importer names the Module, so the absence of one says nothing about it.++The graph emits a Module as ``kind="class"`` (``module_block`` in+``ingestion/language_configs.py``), so the declaration header is read from the+source already in memory to tell it from a Class.+"""++from __future__ import annotations++import re+from collections.abc import Iterable++#: Lines read from a symbol's start to find its header: its span starts at a+#: leading attribute list, which may wrap over a few lines.+_HEADER_LOOKAHEAD = 6++#: A comment line that mentions ``Module X`` is not a header.+_COMMENT_RE = re.compile(rb"\s*(?:'|REM\b)", re.IGNORECASE)++_KEYWORD_RE = re.compile(rb"\b(Module|Class|Structure|Interface|Enum)\s+(\w+)", re.IGNORECASE)+++def _is_module(lines: list[bytes] | None, sym: dict) -> bool:+ """Whether *sym*'s header declares a ``Module``; True when it cannot be read.++ Unreadable counts as a Module on purpose: the caller only lowers a+ confidence for it, so the cost is a Class kept off the deletion-ready tier.+ """+ start = sym.get("start_line")+ if not lines or not start:+ return True+ name = sym.get("name", "").lower().encode("utf-8", "ignore")+ for line in lines[start - 1 : start - 1 + _HEADER_LOOKAHEAD]:+ if _COMMENT_RE.match(line):+ continue+ for match in _KEYWORD_RE.finditer(line):+ if match.group(2).lower() == name:+ return match.group(1).lower() == b"module"+ return True+++def vbnet_module_names(symbols: Iterable[dict], source: bytes | None) -> frozenset[str]:+ """Names of the VB.NET Modules among *symbols* of one file.++ A Module may sit inside a ``Namespace`` block, which is its parent here.+ """+ candidates = [+ sym for sym in symbols if sym.get("language") == "vbnet" and sym.get("kind") == "class"+ ]+ if not candidates:+ return frozenset()+ lines = source.split(b"\n") if source else None+ return frozenset(sym.get("name", "") for sym in candidates if _is_module(lines, sym))diff --git a/tests/unit/dead_code/test_vbnet_modules.py b/tests/unit/dead_code/test_vbnet_modules.pynew file mode 100644index 000000000..f46464371--- /dev/null+++ b/tests/unit/dead_code/test_vbnet_modules.py@@ -0,0 +1,130 @@+"""A VB.NET ``Module`` is used when its members are, and never named for it.++Its members are in scope unqualified wherever its namespace is visible, so a+call site writes ``Run()`` and no importer ever names ``Tools``. Repro of+SCrawler's ``MainModShared`` and ``STDownloaderDeclarations``, both reported+deletion-ready while their members were called across the solution.+"""++from __future__ import annotations++import pytest++from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind+from repowise.core.analysis.dead_code.risk_factors import UNPROVEN_EXPORT_CONFIDENCE+from repowise.core.analysis.dead_code.vbnet_modules import vbnet_module_names+from tests.unit.dead_code._helpers import _build_graph++_EXPORTS_ONLY = {+ "detect_unreachable_files": False,+ "detect_unused_internals": False,+ "detect_zombie_packages": False,+ "min_confidence": 0.0,+}++_PATH = "Shared/Helpers.vb"+_CALLER = "App/Main.vb"+++def _source(container: str) -> bytes:+ return (+ "Public Class Used\n"+ "End Class\n"+ f"Public {container} Tools\n"+ " Public Sub Run()\n"+ " End Sub\n"+ f"End {container}\n"+ ).encode()+++def _sym(name: str, start: int, end: int, kind: str = "class") -> dict:+ return {+ "name": name,+ "kind": kind,+ "visibility": "public",+ "decorators": [],+ "start_line": start,+ "end_line": end,+ "language": "vbnet",+ }+++def _tools_finding(container: str, member_called: bool):+ graph = _build_graph(+ nodes={+ _PATH: {"language": "vbnet", "symbols": [_sym("Used", 1, 2), _sym("Tools", 3, 6)]},+ _CALLER: {+ "language": "vbnet",+ "is_entry_point": True,+ "symbols": [_sym("Start", 1, 3, kind="function")],+ },+ },+ # The importer names a sibling, so import absence would read as evidence.+ edges=[(_CALLER, _PATH, {"edge_type": "imports", "imported_names": ["Used"]})],+ )+ member = f"{_PATH}::Tools::Run"+ graph.add_node(member, node_type="symbol", file_path=_PATH, language="vbnet", kind="method")+ graph.add_edge(f"{_PATH}::Tools", member, edge_type="has_method")+ if member_called:+ graph.add_edge(f"{_CALLER}::Start", member, edge_type="calls")+ source_map = {_PATH: _source(container), _CALLER: b"Sub Start()\n Run()\nEnd Sub\n"}+ report = DeadCodeAnalyzer(graph, source_map=source_map).analyze(dict(_EXPORTS_ONLY))+ found = [+ f+ for f in report.findings+ if f.kind is DeadCodeKind.UNUSED_EXPORT and f.symbol_name == "Tools"+ ]+ return found[0] if found else None+++def test_module_whose_member_is_called_is_not_reported():+ assert _tools_finding("Module", member_called=True) is None+++def test_module_with_no_used_member_is_reported_but_not_deletion_ready():+ finding = _tools_finding("Module", member_called=False)+ assert finding is not None+ assert finding.confidence == pytest.approx(UNPROVEN_EXPORT_CONFIDENCE)+ assert not finding.safe_to_delete+++def test_class_keeps_the_import_absence_evidence():+ """Only a Module's members are in scope unqualified; a Class is named."""+ finding = _tools_finding("Class", member_called=False)+ assert finding is not None+ assert finding.confidence == pytest.approx(1.0)+ assert finding.safe_to_delete+++def test_header_after_an_attribute_line_is_read():+ source = b"<HideModuleName>\nPublic Module Tools\nEnd Module\n"+ assert vbnet_module_names([_sym("Tools", 1, 3)], source) == {"Tools"}+++def test_crlf_source_is_read():+ source = b"Public Class Used\r\nEnd Class\r\nPublic Module Tools\r\nEnd Module\r\n"+ syms = [_sym("Used", 1, 2), _sym("Tools", 3, 4)]+ assert vbnet_module_names(syms, source) == {"Tools"}+++def test_module_nested_in_a_namespace_is_read():+ """The Namespace block is the Module's parent; it is still a Module."""+ source = b"Namespace Downloads\n Public Module Tools\n End Module\nEnd Namespace\n"+ sym = dict(_sym("Tools", 2, 3), parent_name="Downloads")+ assert vbnet_module_names([sym], source) == {"Tools"}++[email protected]("comment", ["' Module Tools was split out", "REM Module Tools"])+def test_a_comment_naming_the_module_is_not_its_header(comment):+ source = f"<Serializable>\n{comment}\nPublic Class Tools\nEnd Class\n".encode()+ assert vbnet_module_names([_sym("Tools", 1, 4)], source) == frozenset()+++def test_unreadable_header_counts_as_a_module():+ """Unknown lowers a confidence; it never keeps a deletion-ready claim."""+ assert vbnet_module_names([_sym("Tools", 1, 3)], None) == {"Tools"}+++def test_other_languages_are_not_read():+ sym = dict(_sym("Tools", 1, 3), language="csharp")+ assert vbnet_module_names([sym], b"public static class Tools {}\n") == frozenset()