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(php): treat files a PHP tool loads as reachability roots (#2979)
Raghav Chamadiya9574806d35db
diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.pyindex 76b0e98f2..55667e9a1 100644--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py@@ -521,6 +521,16 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = ("*_string.go","*zz_generated*.go","*bindata.go",+ # ---- PHP conventions -------------------------------------------------+ # Lint and refactoring tools load their config by file name.+ "rector.php",+ "*/rector.php",+ "ecs.php",+ "*/ecs.php",+ ".php-cs-fixer.php",+ "*/.php-cs-fixer.php",+ ".php-cs-fixer.dist.php",+ "*/.php-cs-fixer.dist.php",# ---- JavaScript conventions ------------------------------------------# Bundles and minified artifacts are served to the browser, not imported."*.bundle.js",diff --git a/packages/core/src/repowise/core/ingestion/composer.py b/packages/core/src/repowise/core/ingestion/composer.pyindex bbd2012ab..b2fd97f4b 100644--- a/packages/core/src/repowise/core/ingestion/composer.py+++ b/packages/core/src/repowise/core/ingestion/composer.py@@ -74,6 +74,9 @@ class ComposerManifest:psr4: tuple[tuple[str, tuple[str, ...]], ...] = ()psr0: tuple[tuple[str, tuple[str, ...]], ...] = ()classmap: tuple[str, ...] = ()+ #: ``autoload.files``: loaded on every request by the autoloader, so a+ #: file listed there needs no importer (global helper functions).+ files: tuple[str, ...] = ()#: ``url`` of every ``{"type": "path"}`` repository, relative to ``rel_dir``#: exactly as written (it is a filesystem path, often ``../shared``).path_repositories: tuple[str, ...] = ()@@ -125,10 +128,12 @@ def parse_composer(data: object, rel_dir: str = "") -> ComposerManifest | None:if not isinstance(data, dict):return Noneclassmap: list[str] = []+ files: list[str] = []for section in ("autoload", "autoload-dev"):block = data.get(section)if isinstance(block, dict):classmap.extend(_rebase(rel_dir, d) for d in _dirs(block.get("classmap")))+ files.extend(_rebase(rel_dir, f) for f in _dirs(block.get("files")))repositories = data.get("repositories")if isinstance(repositories, dict): # the keyed form composer also acceptsrepositories = list(repositories.values())@@ -147,6 +152,7 @@ def parse_composer(data: object, rel_dir: str = "") -> ComposerManifest | None:psr4=_prefix_map(data, "psr-4", rel_dir),psr0=_prefix_map(data, "psr-0", rel_dir),classmap=tuple(classmap),+ files=tuple(files),path_repositories=path_repos,extra=extra if isinstance(extra, dict) else {},)diff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.pyindex 5b357619f..6023b9c24 100644--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py@@ -344,6 +344,37 @@ def _warmup_rust(ctx: ResolverContext) -> None:node["is_reachability_root"] = True+def _warmup_php(ctx: ResolverContext) -> None:+ """Stamp the PHP files a tool loads with no importer as reachability roots.++ Composer's autoloader loads every file a ``composer.json`` lists in+ ``autoload.files`` on every run (a ``helpers.php`` of global functions),+ and PHPStan alone runs a type-test corpus (:mod:`.phpstan`).+ """+ from .composer import repo_composer_manifests+ from .phpstan import type_test_files++ graph = getattr(ctx, "graph", None)+ repo_path = getattr(ctx, "repo_path", None)+ if graph is None:+ return+ manifests = repo_composer_manifests(ctx)+ roots = {path for manifest in manifests for path in manifest.files}+ if repo_path is not None:+ parsed = getattr(ctx, "parsed_files", None) or {}+ source_map = getattr(ctx, "source_map", None)+ roots |= type_test_files(+ repo_path,+ manifests,+ (path for path, pf in parsed.items() if pf.file_info.language == "php"),+ lambda path: _read_warmup_source(path, parsed[path], source_map),+ )+ for path in roots:+ node = graph.nodes.get(path)+ if node is not None:+ node["is_reachability_root"] = True++def _warmup_go(ctx: ResolverContext) -> None:"""Build the Go package index and stamp ``is_entry_point`` on every``package main`` file declaring ``func main()``. Go's entry convention@@ -561,6 +592,7 @@ _WARMUPS: dict[str, tuple[str, Warmup]] = {"cpp": ("graph.cpp_index", _warmup_cpp),"c": ("graph.cpp_index", _warmup_cpp),"swift": ("graph.swift_entry", _warmup_swift),+ "php": ("graph.composer_files", _warmup_php),"dart": ("graph.dart_shells", _warmup_dart),# Registered under both tags: a repo of loose .gd scripts has no scenes,# and an addon distributed as scenes plus a project.godot may carry nodiff --git a/packages/core/src/repowise/core/ingestion/phpstan.py b/packages/core/src/repowise/core/ingestion/phpstan.pynew file mode 100644index 000000000..9b3ac1568--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/phpstan.py@@ -0,0 +1,94 @@+"""PHPStan type-test corpora: PHP files only the analyser runs.++A library proves its generic types with files of ``assertType()`` calls that+PHPStan analyses (laravel/framework's ``types/``, listed in+``phpstan.types.neon.dist``). Nothing imports them and no autoloader loads+them, so dead code would read the whole corpus as unreachable.++A folder is a corpus when a ``phpstan*.neon`` beside a ``composer.json`` lists+it under ``paths``, it lies outside every autoload root (shipped code is+autoloaded; ``src`` analysed by the same tool is not a corpus), and a file in+it imports ``PHPStan\\Testing\\assertType``.+"""++from __future__ import annotations++import posixpath+import re+from collections.abc import Callable, Iterable+from pathlib import Path++from .composer import ComposerManifest++#: PHPStan's own config names: ``phpstan.neon``, ``phpstan.neon.dist``,+#: ``phpstan.types.neon.dist``.+_CONFIG_GLOBS = ("phpstan*.neon", "phpstan*.neon.dist")+#: The ``paths:`` key and the more indented lines under it.+_PATHS_BLOCK_RE = re.compile(+ r"^(?P<indent>[ \t]*)paths:[ \t]*\n(?P<body>(?:(?P=indent)[ \t]+\S.*\n?|[ \t]*\n)*)",+ re.MULTILINE,+)+_LIST_ITEM_RE = re.compile(r"""^[ \t]*-[ \t]*['"]?(?P<value>[^'"\s#]+)""", re.MULTILINE)+_TYPE_TEST_MARKER = "PHPStan\\Testing\\assertType"+++def analysed_paths(neon: str) -> list[str]:+ """The ``paths`` list of a PHPStan config, as written.++ A pattern rather than a NEON parser: ``paths`` is always a plain list of+ strings. Entries built from a parameter (``%rootDir%``) are skipped.+ """+ block = _PATHS_BLOCK_RE.search(neon)+ if block is None:+ return []+ values = _LIST_ITEM_RE.findall(block.group("body"))+ return [value for value in values if "%" not in value]+++def _autoload_roots(manifest: ComposerManifest) -> list[str]:+ dirs = [d for _, ds in (*manifest.psr4, *manifest.psr0) for d in ds]+ return [*dirs, *manifest.classmap, *manifest.files]+++def _overlaps(a: str, b: str) -> bool:+ return not a or not b or a == b or a.startswith(b + "/") or b.startswith(a + "/")+++def type_test_files(+ repo_root: Path,+ manifests: Iterable[ComposerManifest],+ php_paths: Iterable[str],+ text_of: Callable[[str], str | None],+) -> set[str]:+ """Every PHP file in a PHPStan type-test corpus of *repo_root*."""+ paths = sorted(php_paths)+ out: set[str] = set()+ for manifest in manifests:+ roots = _autoload_roots(manifest)+ for folder in _corpus_candidates(repo_root, manifest.rel_dir):+ if any(_overlaps(folder, root) for root in roots):+ continue+ inside = [p for p in paths if p.startswith(folder + "/")]+ if any(_TYPE_TEST_MARKER in (text_of(p) or "") for p in inside):+ out.update(inside)+ return out+++def _corpus_candidates(repo_root: Path, rel_dir: str) -> set[str]:+ """Repo-relative folders the PHPStan configs in *rel_dir* analyse."""+ base = repo_root / rel_dir if rel_dir else repo_root+ entries = [+ entry+ for pattern in _CONFIG_GLOBS+ for config in base.glob(pattern)+ for entry in analysed_paths(_read(config))+ ]+ folders = {posixpath.normpath(posixpath.join(rel_dir, e.rstrip("/"))) for e in entries}+ return {f for f in folders if not f.startswith("..")}+++def _read(path: Path) -> str:+ try:+ return path.read_text(encoding="utf-8", errors="ignore")+ except OSError:+ return ""diff --git a/tests/unit/dead_code/test_php_tool_loaded_files.py b/tests/unit/dead_code/test_php_tool_loaded_files.pynew file mode 100644index 000000000..3ed3af5b7--- /dev/null+++ b/tests/unit/dead_code/test_php_tool_loaded_files.py@@ -0,0 +1,99 @@+"""PHP files a tool loads with no importer are live.++Composer's autoloader loads ``autoload.files``; PHPStan alone runs a+type-test corpus; lint tools read their config by name.+"""++from __future__ import annotations++import json+from pathlib import Path++from repowise.core.analysis.dead_code import DeadCodeAnalyzer+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder+from repowise.core.ingestion.phpstan import analysed_paths++_HELPERS = {+ "src/helpers.php": "<?php\nfunction money(int $cents): string { return ''; }\n",+ "src/legacy.php": "<?php\nfunction old_money(int $cents): string { return ''; }\n",+}++_TYPE_TEST = (+ "<?php\nuse function PHPStan\\Testing\\assertType;\n"+ "class Fixture {}\nassertType('int', 1);\n"+)+++def _flagged(repo: Path, autoload: dict, files: dict[str, str]) -> set[tuple[str, str]]:+ (repo / "composer.json").write_text(json.dumps({"autoload": autoload}), encoding="utf-8")+ for rel, text in files.items():+ (repo / rel).parent.mkdir(parents=True, exist_ok=True)+ (repo / rel).write_text(text, encoding="utf-8")+ builder = GraphBuilder(repo)+ parser = ASTParser()+ for fi in FileTraverser(repo).traverse():+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))+ builder.build()+ report = DeadCodeAnalyzer(builder.graph(), {}, repo_root=repo).analyze(+ {"detect_unused_internals": False}+ )+ return {(f.kind.value, f.file_path) for f in report.findings}+++def _files(flagged: set[tuple[str, str]]) -> set[str]:+ return {path for _kind, path in flagged}+++def test_an_autoloaded_helper_file_is_live_and_an_unlisted_one_is_not(tmp_path: Path) -> None:+ flagged = _flagged(tmp_path, {"files": ["src/helpers.php"]}, _HELPERS)++ assert "src/helpers.php" not in _files(flagged)+ assert ("unreachable_file", "src/legacy.php") in flagged+++def test_without_the_listing_the_helper_file_is_flagged(tmp_path: Path) -> None:+ flagged = _flagged(tmp_path, {}, _HELPERS)++ assert ("unreachable_file", "src/helpers.php") in flagged+++def test_a_phpstan_type_corpus_is_live(tmp_path: Path) -> None:+ flagged = _flagged(+ tmp_path,+ {"psr-4": {"Acme\\": "src/"}},+ {+ "phpstan.types.neon.dist": "parameters:\n level: max\n paths:\n - types\n",+ "types/Cache.php": _TYPE_TEST,+ "types/Support.php": "<?php\nclass Support {}\n",+ # Analysed by PHPStan too, but no assertType: not a corpus.+ "phpstan.neon": "parameters:\n paths:\n - bin\n - src\n",+ "bin/orphan.php": "<?php\nclass Orphan {}\n",+ "src/Unused.php": "<?php\nnamespace Acme;\nclass Unused {}\n",+ },+ )++ assert {"types/Cache.php", "types/Support.php"}.isdisjoint(_files(flagged))+ assert ("unreachable_file", "bin/orphan.php") in flagged+ assert ("unreachable_file", "src/Unused.php") in flagged+++def test_lint_tool_configs_are_live(tmp_path: Path) -> None:+ flagged = _flagged(+ tmp_path,+ {},+ {+ "rector.php": "<?php\nreturn static function () {};\n",+ ".php-cs-fixer.dist.php": "<?php\nreturn [];\n",+ },+ )++ assert {"rector.php", ".php-cs-fixer.dist.php"}.isdisjoint(_files(flagged))+++def test_analysed_paths_reads_only_the_paths_list() -> None:+ neon = (+ "includes:\n - baseline.neon\nparameters:\n paths:\n - src\n"+ " # a comment\n - 'types/'\n - %rootDir%/x\n"+ " excludePaths:\n - src/views\n"+ )+ assert analysed_paths(neon) == ["src", "types/"]diff --git a/tests/unit/ingestion/test_composer.py b/tests/unit/ingestion/test_composer.pyindex 84d1a4eb3..af103242a 100644--- a/tests/unit/ingestion/test_composer.py+++ b/tests/unit/ingestion/test_composer.py@@ -36,8 +36,12 @@ class TestParse:"psr-4": {"Billing\\": "src/"},"psr-0": {"Legacy_": "lib/"},"classmap": ["database/"],+ "files": ["src/helpers.php"],+ },+ "autoload-dev": {+ "psr-4": {"Billing\\Tests\\": ["tests/", "./spec"]},+ "files": "tests/functions.php",},- "autoload-dev": {"psr-4": {"Billing\\Tests\\": ["tests/", "./spec"]}},"repositories": [{"type": "path", "url": "../core"},{"type": "vcs", "url": "https://example.com/x.git"},@@ -60,6 +64,10 @@ class TestParse:)assert manifest.psr0 == (("Legacy_", ("packages/billing/lib",)),)assert manifest.classmap == ("packages/billing/database",)+ assert manifest.files == (+ "packages/billing/src/helpers.php",+ "packages/billing/tests/functions.php",+ )assert manifest.path_repositories == ("../core",)assert manifest.extra == {"laravel": {"providers": []}}