Skip to main content

stern4rust/finding/parsing/
module_declaration_finder.rs

1// Copyright 2025 Umberto Gotti <umberto.gotti@umbertogotti.dev>
2// Licensed under the MIT License
3// SPDX-License-Identifier: MIT
4
5use syn::Item;
6use syn::parse_file;
7
8use crate::source_file::SourceFile;
9
10// The module names a registry declares.
11//
12// `pub` is not required here, though `module-registry` requires it in `src/`
13// and this rule is about a different question: a private `mod name;` compiles
14// that file just as well, and being compiled is the whole concern. Demanding
15// `pub` in this rule would report a file that is reached as though it were not.
16//
17// An inline `mod name { ... }` is not counted. It declares no file, so it
18// cannot be what reaches one.
19pub struct ModuleDeclarationFinder;
20
21impl ModuleDeclarationFinder {
22    // None means the file does not parse. readable-source reports that, and
23    // guessing at the declarations of a file nobody can parse would be worse
24    // than saying nothing.
25    pub fn find(file: &SourceFile) -> Option<Vec<String>> {
26        let syntax = parse_file(&file.contents()).ok()?;
27        Some(
28            syntax
29                .items
30                .iter()
31                .filter_map(|item| match item {
32                    Item::Mod(module) if module.content.is_none() => Some(module.ident.to_string()),
33                    _ => None,
34                })
35                .collect(),
36        )
37    }
38}