Skip to main content

codelens_engine/
phantom_modules.rs

1//! Detects "phantom" module declarations — `mod NAME;` lines whose target
2//! is never `use`d anywhere else in the workspace. Complements the
3//! `find_dead_code_v2` file-level pass: that one flags files with no
4//! importers in the import graph, this one catches the prerequisite step
5//! (a `mod` line that should never have been written or that survives a
6//! deletion cascade).
7//!
8//! Heuristic, not authoritative — `pub mod` declarations are still
9//! reported because re-export patterns (`pub use foo::*`) can keep them
10//! useful, but a private `mod foo;` with no `use` references on the
11//! parent symbol path is almost always cleanup-eligible.
12
13use crate::project::{collect_files, ProjectRoot};
14use anyhow::Result;
15use regex::Regex;
16use serde::Serialize;
17use std::collections::HashSet;
18use std::path::Path;
19use std::sync::LazyLock;
20
21/// Matches `[pub(...)] mod NAME;` (declaration form, not `mod NAME { ... }`).
22static MOD_DECL_RE: LazyLock<Regex> = LazyLock::new(|| {
23    Regex::new(r"(?m)^\s*(?P<vis>pub(?:\([^)]*\))?\s+)?mod\s+(?P<name>[A-Za-z_][A-Za-z0-9_]*)\s*;")
24        .unwrap()
25});
26
27#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
28pub struct PhantomModuleEntry {
29    pub parent_file: String,
30    pub module_name: String,
31    pub line: usize,
32    pub visibility: &'static str,
33    pub kind: &'static str,
34}
35
36/// Finds Rust `mod NAME;` declarations whose `NAME` does not appear as a
37/// path segment anywhere else in the workspace.
38///
39/// Match strategy (v1, regex-only):
40/// 1. Collect every `mod NAME;` declaration with its parent file and line.
41/// 2. Build a set of *referenced* module names by scanning all Rust source
42///    for tokens that look like `NAME::`, `::NAME;`, or `::NAME::`.
43/// 3. Any declared `NAME` not in the set is a phantom.
44///
45/// Tradeoffs:
46/// - Reports `pub mod` too — re-export patterns may keep them useful;
47///   visibility is reported so callers can filter.
48/// - Does not understand path aliases (`use foo as bar;`); we still catch
49///   the original name on either side of the alias.
50pub fn find_phantom_modules(
51    project: &ProjectRoot,
52    max_results: usize,
53) -> Result<Vec<PhantomModuleEntry>> {
54    let mut declarations: Vec<PhantomModuleEntry> = Vec::new();
55    let mut referenced: HashSet<String> = HashSet::new();
56    let candidates = collect_files(project.as_path(), is_rust_file)?;
57
58    for path in &candidates {
59        let source = match std::fs::read_to_string(path) {
60            Ok(s) => s,
61            Err(_) => continue,
62        };
63        let relative = project.to_relative(path);
64        if is_excluded_path(&relative) {
65            continue;
66        }
67        scan_declarations(&source, &relative, &mut declarations);
68        collect_referenced_names(&source, &mut referenced);
69    }
70
71    let mut phantoms: Vec<PhantomModuleEntry> = declarations
72        .into_iter()
73        .filter(|d| !referenced.contains(&d.module_name))
74        .filter(|d| !is_test_module_name(&d.module_name))
75        .collect();
76
77    phantoms.sort_by(|a, b| {
78        a.parent_file
79            .cmp(&b.parent_file)
80            .then(a.line.cmp(&b.line))
81            .then(a.module_name.cmp(&b.module_name))
82    });
83    if max_results > 0 && phantoms.len() > max_results {
84        phantoms.truncate(max_results);
85    }
86    Ok(phantoms)
87}
88
89fn scan_declarations(source: &str, file: &str, out: &mut Vec<PhantomModuleEntry>) {
90    for caps in MOD_DECL_RE.captures_iter(source) {
91        let name = match caps.name("name") {
92            Some(m) => m.as_str().to_owned(),
93            None => continue,
94        };
95        let mod_start = caps.get(0).map(|m| m.start()).unwrap_or(0);
96        // Codex P2 (PR #151): skip mod declarations that are gated by
97        // `#[cfg(test)]` (or `#[cfg(any(test, ...))]`). Test-only mods are
98        // already excluded from production semantics by the compiler; they
99        // do not need a workspace path-reference to justify their existence,
100        // and reporting them just adds noise.
101        if line_before_is_cfg_test(source, mod_start) {
102            continue;
103        }
104        let visibility = if caps.name("vis").is_some() {
105            "public"
106        } else {
107            "private"
108        };
109        let line = source[..mod_start].matches('\n').count() + 1;
110        out.push(PhantomModuleEntry {
111            parent_file: file.to_owned(),
112            module_name: name,
113            line,
114            visibility,
115            kind: "rust_mod_declaration",
116        });
117    }
118}
119
120/// Returns true when the line immediately above `offset` is a
121/// `#[cfg(test)]`-style attribute. Walks one line back, skipping blank
122/// lines but not other attributes (so `#[derive(...)]` followed by mod
123/// is *not* treated as cfg-gated).
124fn line_before_is_cfg_test(source: &str, offset: usize) -> bool {
125    let line_start = source[..offset]
126        .rfind('\n')
127        .map(|i| i + 1)
128        .unwrap_or(offset);
129    if line_start == 0 {
130        return false;
131    }
132    let mut prev_end = line_start - 1;
133    loop {
134        let prev_start = source[..prev_end].rfind('\n').map(|i| i + 1).unwrap_or(0);
135        let prev_line = source[prev_start..prev_end].trim();
136        if !prev_line.is_empty() {
137            return prev_line.starts_with("#[cfg") && prev_line.contains("test");
138        }
139        if prev_start == 0 {
140            return false;
141        }
142        prev_end = prev_start - 1;
143    }
144}
145
146/// Adds every identifier that participates in any `::`-adjacent position
147/// into the referenced set, plus single-segment `use NAME;` lines (codex
148/// P2 from PR #151). Three regexes:
149///   - `IDENT::` matches leading and middle segments (`crate::foo::bar`
150///     → `crate`, `foo`).
151///   - `::IDENT` matches trailing segments (`crate::foo::bar` → `bar`).
152///   - `use NAME(\s+as\s+ALIAS)?\s*;` matches single-segment imports of a
153///     sibling module (`use ghost;`) so that re-exporting modules don't
154///     show up as phantom.
155fn collect_referenced_names(source: &str, into: &mut HashSet<String>) {
156    static LEADING_RE: LazyLock<Regex> =
157        LazyLock::new(|| Regex::new(r"([A-Za-z_][A-Za-z0-9_]*)::").unwrap());
158    static TRAILING_RE: LazyLock<Regex> =
159        LazyLock::new(|| Regex::new(r"::([A-Za-z_][A-Za-z0-9_]*)").unwrap());
160    static SINGLE_USE_RE: LazyLock<Regex> = LazyLock::new(|| {
161        Regex::new(
162            r"(?m)^\s*(?:pub(?:\([^)]*\))?\s+)?use\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s+as\s+[A-Za-z_][A-Za-z0-9_]*)?\s*;",
163        )
164        .unwrap()
165    });
166    for caps in LEADING_RE.captures_iter(source) {
167        if let Some(m) = caps.get(1) {
168            into.insert(m.as_str().to_owned());
169        }
170    }
171    for caps in TRAILING_RE.captures_iter(source) {
172        if let Some(m) = caps.get(1) {
173            into.insert(m.as_str().to_owned());
174        }
175    }
176    for caps in SINGLE_USE_RE.captures_iter(source) {
177        if let Some(m) = caps.get(1) {
178            into.insert(m.as_str().to_owned());
179        }
180    }
181}
182
183fn is_rust_file(path: &Path) -> bool {
184    path.extension().and_then(|s| s.to_str()) == Some("rs")
185}
186
187fn is_excluded_path(relative: &str) -> bool {
188    if relative == "crates/codelens-engine/src/phantom_modules.rs" {
189        return true;
190    }
191    let lower = relative.to_ascii_lowercase();
192    if lower.ends_with("_tests.rs") || lower.ends_with("_test.rs") {
193        return true;
194    }
195    lower.split('/').any(|seg| {
196        matches!(
197            seg,
198            "tests"
199                | "test"
200                | "bench"
201                | "benches"
202                | "examples"
203                | "fixtures"
204                | "integration_tests"
205                | "http_tests"
206        )
207    })
208}
209
210fn is_test_module_name(name: &str) -> bool {
211    name.ends_with("_tests") || name.ends_with("_test") || name == "tests" || name == "test"
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    #[test]
219    fn detects_unreferenced_private_mod() {
220        let mut decls = Vec::new();
221        scan_declarations("mod ghost;\nmod live;\n", "lib.rs", &mut decls);
222        assert_eq!(decls.len(), 2);
223        assert_eq!(decls[0].module_name, "ghost");
224        assert_eq!(decls[0].visibility, "private");
225        assert_eq!(decls[1].module_name, "live");
226    }
227
228    #[test]
229    fn detects_pub_mod_as_public() {
230        let mut decls = Vec::new();
231        scan_declarations("pub mod api;\n", "lib.rs", &mut decls);
232        assert_eq!(decls.len(), 1);
233        assert_eq!(decls[0].visibility, "public");
234    }
235
236    #[test]
237    fn skips_inline_mod_blocks() {
238        let mut decls = Vec::new();
239        scan_declarations("mod inline { fn x() {} }\n", "lib.rs", &mut decls);
240        // inline `mod NAME { ... }` should NOT match (no trailing `;`)
241        assert!(decls.is_empty(), "got: {:?}", decls);
242    }
243
244    #[test]
245    fn skips_cfg_test_gated_mod() {
246        // Codex P2 (PR #151): `#[cfg(test)] mod tests;` and the `any(test, ...)`
247        // form must not be reported as phantom — the compiler already gates
248        // them out of production semantics.
249        let mut decls = Vec::new();
250        scan_declarations(
251            "#[cfg(test)]\nmod tests;\n#[cfg(any(test, feature = \"x\"))]\nmod fixtures;\nmod live;\n",
252            "lib.rs",
253            &mut decls,
254        );
255        assert_eq!(decls.len(), 1, "got: {:?}", decls);
256        assert_eq!(decls[0].module_name, "live");
257    }
258
259    #[test]
260    fn single_segment_use_keeps_module_alive() {
261        // Codex P2 (PR #151): `use foo;` must register `foo` as referenced
262        // so a sibling `mod foo;` is not flagged phantom.
263        let mut set = HashSet::new();
264        collect_referenced_names("use foo;\npub use bar as renamed;\n", &mut set);
265        assert!(
266            set.contains("foo"),
267            "single-segment `use foo;` missed: {:?}",
268            set
269        );
270        assert!(
271            set.contains("bar"),
272            "single-segment `pub use bar as renamed;` missed: {:?}",
273            set
274        );
275    }
276
277    #[test]
278    fn referenced_set_picks_up_path_segments() {
279        let mut set = HashSet::new();
280        collect_referenced_names("use crate::foo::bar;\nlet z = self::baz::x();\n", &mut set);
281        assert!(set.contains("foo"));
282        assert!(set.contains("bar"));
283        assert!(set.contains("baz"));
284    }
285
286    #[test]
287    fn referenced_set_picks_up_pub_use_with_braces() {
288        // Real false-positive shape from dogfooding: `pub use dead_code::{A, B, C};`
289        // The path `dead_code::A` is the first multi-segment chunk before the `{`,
290        // and the regex must catch `dead_code` so the `mod dead_code;` line above
291        // is not mis-flagged as phantom.
292        let mut set = HashSet::new();
293        collect_referenced_names(
294            "pub use dead_code::{DeadCodeEntryV2, find_dead_code, find_dead_code_v2};",
295            &mut set,
296        );
297        assert!(set.contains("dead_code"), "missing dead_code in {:?}", set);
298    }
299
300    #[test]
301    #[ignore]
302    fn dogfood_self_repo() {
303        // Run with: cargo test -p codelens-engine phantom_modules::tests::dogfood_self_repo -- --ignored --nocapture
304        // Derive workspace root from CARGO_MANIFEST_DIR so contributor's
305        // clone path works without hardcoding (codex P2 from PR #149).
306        let repo = std::env::var("CODELENS_REPO_ROOT").unwrap_or_else(|_| {
307            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
308                .ancestors()
309                .nth(2)
310                .expect("workspace root not found above CARGO_MANIFEST_DIR")
311                .to_string_lossy()
312                .into_owned()
313        });
314        let project = crate::project::ProjectRoot::new(repo).expect("project root");
315        let results = super::find_phantom_modules(&project, 200).expect("find_phantom_modules");
316        eprintln!("\n=== {} phantom mod declarations ===\n", results.len());
317        for r in &results {
318            eprintln!(
319                "  {} (vis={}) at {}:{}",
320                r.module_name, r.visibility, r.parent_file, r.line
321            );
322        }
323    }
324
325    #[test]
326    fn is_excluded_path_skips_test_dirs() {
327        assert!(is_excluded_path("crates/foo/tests/x.rs"));
328        assert!(is_excluded_path("crates/foo/src/x_tests.rs"));
329        assert!(!is_excluded_path("crates/foo/src/lib.rs"));
330        assert!(is_excluded_path(
331            "crates/codelens-engine/src/phantom_modules.rs"
332        ));
333    }
334}