Skip to main content

architecture_tests/
symbols.rs

1//! Syntax-level scan of Rust sources for names.
2
3use std::{
4    collections::BTreeSet,
5    fmt, fs, io,
6    path::{Path, PathBuf},
7};
8
9use proc_macro2::{Ident, TokenStream, TokenTree};
10use snafu::{ResultExt as _, Snafu};
11use syn::{
12    ext::IdentExt as _,
13    visit::{self, Visit},
14    Item, UseTree, Visibility,
15};
16
17/// An error reading or parsing sources.
18#[derive(Debug, Snafu)]
19#[snafu(context(suffix(Snafu)))]
20pub enum Error {
21    /// A directory or file couldn't be read.
22    #[snafu(display("failed to read {}: {source}", path.display()))]
23    Read {
24        /// The path being read.
25        path: PathBuf,
26        /// The underlying error.
27        source: io::Error,
28    },
29
30    /// A file couldn't be parsed as Rust.
31    #[snafu(display("failed to parse {}:{line}: {message}", path.display()))]
32    Parse {
33        /// The file.
34        path: PathBuf,
35        /// The 1-based line of the error.
36        line: usize,
37        /// The parse error message.
38        message: String,
39    },
40
41    /// The scanned directories hold no `.rs` file.
42    #[snafu(display("no `.rs` files under {}", display_paths(dirs)))]
43    NoSources {
44        /// The scanned directories.
45        dirs: Vec<PathBuf>,
46    },
47
48    /// The crate root given for alias derivation isn't among the scanned files.
49    #[snafu(display("crate root {} isn't a scanned file", path.display()))]
50    MissingCrateRoot {
51        /// The crate root.
52        path: PathBuf,
53    },
54
55    /// A glob import of a scanned name binds names that alias derivation can't see.
56    #[snafu(display(
57        "{}:{line}: glob import of a guarded name; import the names explicitly",
58        path.display()
59    ))]
60    GlobImport {
61        /// The file.
62        path: PathBuf,
63        /// The 1-based line of the glob.
64        line: usize,
65    },
66}
67
68fn display_paths(paths: &[PathBuf]) -> String {
69    let paths: Vec<_> = paths.iter().map(|path| path.display().to_string()).collect();
70    paths.join(", ")
71}
72
73/// The syntax containing a matched identifier.
74#[derive(Clone, Copy, Debug, Eq, PartialEq)]
75pub enum Form {
76    /// A path segment, with or without a leading `::`.
77    Path,
78    /// A name in a `use` tree, including the target of an `as` rename.
79    Use,
80    /// The crate or rename of an `extern crate` item.
81    ExternCrate,
82    /// An identifier token in a macro body or attribute argument.
83    Token,
84}
85
86impl fmt::Display for Form {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        f.write_str(match self {
89            Self::Path => "path",
90            Self::Use => "use",
91            Self::ExternCrate => "extern crate",
92            Self::Token => "token",
93        })
94    }
95}
96
97/// A matched identifier and its source location.
98#[derive(Clone, Debug, Eq, PartialEq)]
99pub struct Mention {
100    /// The file.
101    pub path: PathBuf,
102    /// The 1-based line.
103    pub line: usize,
104    /// The 1-based column.
105    pub column: usize,
106    /// The name.
107    pub name: String,
108    /// The syntax that names it.
109    pub form: Form,
110}
111
112impl fmt::Display for Mention {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        write!(
115            f,
116            "{}:{}:{}: {} `{}`",
117            self.path.display(),
118            self.line,
119            self.column,
120            self.form,
121            self.name
122        )
123    }
124}
125
126struct SourceFile {
127    path: PathBuf,
128    syntax: syn::File,
129}
130
131impl SourceFile {
132    fn parse(path: PathBuf, text: &str) -> Result<Self, Error> {
133        match syn::parse_file(text) {
134            Ok(syntax) => Ok(Self { path, syntax }),
135            Err(error) => ParseSnafu {
136                path,
137                line: error.span().start().line,
138                message: error.to_string(),
139            }
140            .fail(),
141        }
142    }
143
144    fn mentions(&self, names: &BTreeSet<String>) -> Vec<Mention> {
145        let mut finder = MentionFinder::new(&self.path, names);
146        finder.visit_file(&self.syntax);
147        finder.found
148    }
149
150    fn module_mentions(&self, root: &Path, modules: &BTreeSet<String>) -> Vec<Mention> {
151        let mut finder = ModuleFinder {
152            path: &self.path,
153            module: module_of(root, &self.path),
154            modules,
155            found: Vec::new(),
156        };
157        finder.visit_file(&self.syntax);
158        finder.found
159    }
160
161    /// Adds cross-file aliases to `out`, following private alias chains within this file.
162    /// [`SourceTree::aliases`] defines which bindings count across files.
163    fn exported_aliases(
164        &self, crate_root: bool, known: &BTreeSet<String>, out: &mut BTreeSet<String>,
165    ) -> Result<(), Error> {
166        let mut scope = known.clone();
167        loop {
168            let mut bindings = Bindings {
169                path: &self.path,
170                names: &scope,
171                exported: BTreeSet::new(),
172                private: BTreeSet::new(),
173            };
174            bindings.items(&self.syntax.items, crate_root)?;
175            let Bindings { exported, private, .. } = bindings;
176            let before = scope.len();
177            scope.extend(exported.iter().chain(&private).cloned());
178            if scope.len() == before {
179                out.extend(exported);
180                return Ok(());
181            }
182        }
183    }
184}
185
186/// The parsed `.rs` files under a set of directories.
187pub struct SourceTree {
188    files: Vec<SourceFile>,
189}
190
191impl SourceTree {
192    /// Reads and parses every `.rs` file under `dirs`, recursively.
193    ///
194    /// # Errors
195    ///
196    /// Returns an error if a directory or file can't be read, a file doesn't parse, or `dirs` hold no `.rs` file.
197    pub fn read(dirs: &[PathBuf]) -> Result<Self, Error> {
198        let mut paths = Vec::new();
199        for dir in dirs {
200            collect_rust_files(dir, &mut paths)?;
201        }
202        if paths.is_empty() {
203            return NoSourcesSnafu { dirs: dirs.to_vec() }.fail();
204        }
205        let files = paths
206            .into_iter()
207            .map(|path| {
208                let text = fs::read_to_string(&path).context(ReadSnafu { path: &path })?;
209                SourceFile::parse(path, &text)
210            })
211            .collect::<Result<_, _>>()?;
212        Ok(Self { files })
213    }
214
215    /// Returns every place in these files that names one of `names`.
216    ///
217    /// Comments, doc text, and string literals never count.
218    pub fn mentions(&self, names: &BTreeSet<String>) -> Vec<Mention> {
219        self.files.iter().flat_map(|file| file.mentions(names)).collect()
220    }
221
222    /// Returns every path in these files that names a top-level module in `modules` of the crate whose sources are
223    /// under `root`.
224    ///
225    /// Only paths that start at `crate`, `self` or `super` count, and `self` and `super` resolve from the file's
226    /// place under `root` and its inline modules. Unlike [`SourceTree::mentions`], a local variable or a field that
227    /// shares a module's name never matches. Paths in `use` items, types, expressions and macro tokens count.
228    pub fn module_mentions(&self, root: &Path, modules: &BTreeSet<String>) -> Vec<Mention> {
229        self.files
230            .iter()
231            .flat_map(|file| file.module_mentions(root, modules))
232            .collect()
233    }
234
235    /// Collects aliases of `names` from this tree.
236    ///
237    /// An alias binds a name through an item mentioning a guarded name or another alias. At file and inline-module
238    /// scope, the scan includes:
239    ///
240    /// - `use`, `type`, and `extern crate` items with visibility other than private or `pub(self)`
241    /// - private bindings of those kinds at the top level of `crate_root`, accessible to descendant modules
242    /// - `macro_rules!` definitions, regardless of visibility
243    ///
244    /// Private bindings elsewhere contribute only to same-file alias chains. Bindings inside blocks or macro
245    /// invocations aren't collected. Matches ignore Rust scope, so unrelated names can match.
246    ///
247    /// # Errors
248    ///
249    /// Returns an error if `crate_root` isn't scanned or an included `use` item glob-imports a path containing a
250    /// guarded name or alias. Glob-bound names can't be enumerated from the import syntax.
251    pub fn aliases(&self, crate_root: &Path, names: &BTreeSet<String>) -> Result<BTreeSet<String>, Error> {
252        if !self.files.iter().any(|file| file.path == crate_root) {
253            return MissingCrateRootSnafu { path: crate_root }.fail();
254        }
255        let mut known = names.clone();
256        loop {
257            let mut bound = BTreeSet::new();
258            for file in &self.files {
259                file.exported_aliases(file.path == crate_root, &known, &mut bound)?;
260            }
261            let before = known.len();
262            known.extend(bound);
263            if known.len() == before {
264                break;
265            }
266        }
267        Ok(known.difference(names).cloned().collect())
268    }
269}
270
271fn collect_rust_files(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), Error> {
272    let mut entries = fs::read_dir(dir)
273        .context(ReadSnafu { path: dir })?
274        .map(|entry| entry.map(|entry| entry.path()))
275        .collect::<Result<Vec<_>, _>>()
276        .context(ReadSnafu { path: dir })?;
277    entries.sort();
278    for path in entries {
279        if path.is_dir() {
280            collect_rust_files(&path, out)?;
281        } else if path.extension().is_some_and(|extension| extension == "rs") {
282            out.push(path);
283        }
284    }
285    Ok(())
286}
287
288struct MentionFinder<'a> {
289    path: &'a Path,
290    names: &'a BTreeSet<String>,
291    found: Vec<Mention>,
292}
293
294impl<'a> MentionFinder<'a> {
295    fn new(path: &'a Path, names: &'a BTreeSet<String>) -> Self {
296        Self {
297            path,
298            names,
299            found: Vec::new(),
300        }
301    }
302
303    fn check(&mut self, ident: &Ident, form: Form) {
304        let name = ident.unraw().to_string();
305        if self.names.contains(&name) {
306            let start = ident.span().start();
307            self.found.push(Mention {
308                path: self.path.to_path_buf(),
309                line: start.line,
310                column: start.column + 1,
311                name,
312                form,
313            });
314        }
315    }
316
317    fn tokens(&mut self, tokens: &TokenStream) {
318        for token in tokens.clone() {
319            match token {
320                TokenTree::Ident(ident) => self.check(&ident, Form::Token),
321                TokenTree::Group(group) => self.tokens(&group.stream()),
322                TokenTree::Punct(_) | TokenTree::Literal(_) => {}
323            }
324        }
325    }
326}
327
328impl<'ast> Visit<'ast> for MentionFinder<'_> {
329    fn visit_item_extern_crate(&mut self, i: &'ast syn::ItemExternCrate) {
330        self.check(&i.ident, Form::ExternCrate);
331        if let Some((_, rename)) = &i.rename {
332            self.check(rename, Form::ExternCrate);
333        }
334        visit::visit_item_extern_crate(self, i);
335    }
336
337    fn visit_path_segment(&mut self, i: &'ast syn::PathSegment) {
338        self.check(&i.ident, Form::Path);
339        visit::visit_path_segment(self, i);
340    }
341
342    // Macro bodies, attribute arguments, and unparsed syntax.
343    fn visit_token_stream(&mut self, i: &'ast TokenStream) {
344        self.tokens(i);
345    }
346
347    fn visit_use_name(&mut self, i: &'ast syn::UseName) {
348        self.check(&i.ident, Form::Use);
349    }
350
351    fn visit_use_path(&mut self, i: &'ast syn::UsePath) {
352        self.check(&i.ident, Form::Use);
353        visit::visit_use_path(self, i);
354    }
355
356    fn visit_use_rename(&mut self, i: &'ast syn::UseRename) {
357        self.check(&i.ident, Form::Use);
358        self.check(&i.rename, Form::Use);
359    }
360}
361
362/// The module path of a source file under `root`: empty for the crate root, the directory for `mod.rs`.
363fn module_of(root: &Path, path: &Path) -> Vec<String> {
364    let relative = path.strip_prefix(root).unwrap_or(path);
365    let mut module: Vec<String> = relative
366        .iter()
367        .map(|component| component.to_string_lossy().into_owned())
368        .collect();
369    match module.pop().as_deref() {
370        Some("main.rs" | "lib.rs") if module.is_empty() => {}
371        Some("mod.rs") | None => {}
372        Some(file) => module.push(file.trim_end_matches(".rs").to_string()),
373    }
374    module
375}
376
377struct ModuleFinder<'a> {
378    path: &'a Path,
379    module: Vec<String>,
380    modules: &'a BTreeSet<String>,
381    found: Vec<Mention>,
382}
383
384impl ModuleFinder<'_> {
385    /// Resolves a path that starts at `crate`, `self` or `super`, and records it if its top-level module is guarded.
386    fn check(&mut self, segments: &[Ident]) {
387        let Some((first, rest)) = segments.split_first() else {
388            return;
389        };
390        let mut base = match first.to_string().as_str() {
391            "crate" => Vec::new(),
392            "self" => self.module.clone(),
393            "super" => match self.module.split_last() {
394                Some((_, parent)) => parent.to_vec(),
395                None => return,
396            },
397            _ => return,
398        };
399        let mut reported = first;
400        for segment in rest {
401            match segment.to_string().as_str() {
402                "super" => {
403                    if base.pop().is_none() {
404                        return;
405                    }
406                }
407                "self" => {}
408                _ => {
409                    if base.is_empty() {
410                        base.push(segment.unraw().to_string());
411                        reported = segment;
412                    }
413                    break;
414                }
415            }
416        }
417        let Some(top) = base.first().filter(|top| self.modules.contains(*top)) else {
418            return;
419        };
420        let start = reported.span().start();
421        self.found.push(Mention {
422            path: self.path.to_path_buf(),
423            line: start.line,
424            column: start.column + 1,
425            name: top.clone(),
426            form: Form::Path,
427        });
428    }
429
430    fn use_tree(&mut self, tree: &UseTree, prefix: &mut Vec<Ident>) {
431        match tree {
432            UseTree::Path(path) => {
433                prefix.push(path.ident.clone());
434                self.use_tree(&path.tree, prefix);
435                prefix.pop();
436            }
437            UseTree::Name(name) => self.use_leaf(prefix, &name.ident),
438            UseTree::Rename(rename) => self.use_leaf(prefix, &rename.ident),
439            UseTree::Glob(_) => self.check(prefix),
440            UseTree::Group(group) => {
441                for tree in &group.items {
442                    self.use_tree(tree, prefix);
443                }
444            }
445        }
446    }
447
448    fn use_leaf(&mut self, prefix: &mut Vec<Ident>, ident: &Ident) {
449        prefix.push(ident.clone());
450        self.check(prefix);
451        prefix.pop();
452    }
453
454    /// Checks every `a::b::c` run of identifiers in a token stream.
455    fn tokens(&mut self, tokens: &TokenStream) {
456        let tokens: Vec<TokenTree> = tokens.clone().into_iter().collect();
457        let mut i = 0;
458        while i < tokens.len() {
459            match &tokens[i] {
460                TokenTree::Ident(ident) => {
461                    let mut segments = vec![ident.clone()];
462                    while let (Some(TokenTree::Punct(a)), Some(TokenTree::Punct(b)), Some(TokenTree::Ident(next))) =
463                        (tokens.get(i + 1), tokens.get(i + 2), tokens.get(i + 3))
464                    {
465                        if a.as_char() != ':' || b.as_char() != ':' {
466                            break;
467                        }
468                        segments.push(next.clone());
469                        i += 3;
470                    }
471                    self.check(&segments);
472                }
473                TokenTree::Group(group) => self.tokens(&group.stream()),
474                TokenTree::Punct(_) | TokenTree::Literal(_) => {}
475            }
476            i += 1;
477        }
478    }
479}
480
481impl<'ast> Visit<'ast> for ModuleFinder<'_> {
482    fn visit_item_mod(&mut self, i: &'ast syn::ItemMod) {
483        if i.content.is_some() {
484            self.module.push(i.ident.unraw().to_string());
485            visit::visit_item_mod(self, i);
486            self.module.pop();
487        }
488    }
489
490    fn visit_item_use(&mut self, i: &'ast syn::ItemUse) {
491        self.use_tree(&i.tree, &mut Vec::new());
492    }
493
494    fn visit_path(&mut self, i: &'ast syn::Path) {
495        let segments: Vec<Ident> = i.segments.iter().map(|segment| segment.ident.clone()).collect();
496        self.check(&segments);
497        visit::visit_path(self, i);
498    }
499
500    // Macro bodies, attribute arguments, and unparsed syntax.
501    fn visit_token_stream(&mut self, i: &'ast TokenStream) {
502        self.tokens(i);
503    }
504}
505
506/// Alias bindings split by whether the scan propagates them across files.
507struct Bindings<'a> {
508    path: &'a Path,
509    names: &'a BTreeSet<String>,
510    exported: BTreeSet<String>,
511    private: BTreeSet<String>,
512}
513
514impl Bindings<'_> {
515    fn items(&mut self, items: &[Item], export_private: bool) -> Result<(), Error> {
516        for item in items {
517            match item {
518                Item::Use(item) => {
519                    let exported = export_private || is_visible(&item.vis);
520                    self.use_tree(&item.tree, None, exported)?;
521                }
522                Item::Type(item) => {
523                    let mut finder = MentionFinder::new(self.path, self.names);
524                    finder.visit_item_type(item);
525                    if !finder.found.is_empty() {
526                        self.bind(&item.ident, export_private || is_visible(&item.vis));
527                    }
528                }
529                Item::ExternCrate(item) => {
530                    if self.names_ident(&item.ident) {
531                        let ident = item.rename.as_ref().map_or(&item.ident, |(_, rename)| rename);
532                        self.bind(ident, export_private || is_visible(&item.vis));
533                    }
534                }
535                Item::Macro(item) => {
536                    if let Some(ident) = &item.ident {
537                        let mut finder = MentionFinder::new(self.path, self.names);
538                        finder.visit_macro(&item.mac);
539                        if !finder.found.is_empty() {
540                            self.bind(ident, true);
541                        }
542                    }
543                }
544                Item::Mod(item) => {
545                    if let Some((_, items)) = &item.content {
546                        self.items(items, false)?;
547                    }
548                }
549                _ => {}
550            }
551        }
552        Ok(())
553    }
554
555    /// Collects bindings imported through guarded paths. `prefix` holds the preceding segment (for `self` imports)
556    /// and whether any segment so far names a guarded identifier.
557    fn use_tree(&mut self, tree: &UseTree, prefix: Option<(&Ident, bool)>, exported: bool) -> Result<(), Error> {
558        let named = prefix.is_some_and(|(_, named)| named);
559        match tree {
560            UseTree::Path(path) => {
561                let named = named || self.names_ident(&path.ident);
562                self.use_tree(&path.tree, Some((&path.ident, named)), exported)?;
563            }
564            UseTree::Name(name) => {
565                if named || self.names_ident(&name.ident) {
566                    match prefix {
567                        Some((parent, _)) if name.ident == "self" => self.bind(parent, exported),
568                        _ => self.bind(&name.ident, exported),
569                    }
570                }
571            }
572            UseTree::Rename(rename) => {
573                if (named || self.names_ident(&rename.ident)) && rename.rename != "_" {
574                    self.bind(&rename.rename, exported);
575                }
576            }
577            UseTree::Glob(glob) => {
578                if named && exported {
579                    return GlobImportSnafu {
580                        path: self.path,
581                        line: glob.star_token.spans[0].start().line,
582                    }
583                    .fail();
584                }
585            }
586            UseTree::Group(group) => {
587                for tree in &group.items {
588                    self.use_tree(tree, prefix, exported)?;
589                }
590            }
591        }
592        Ok(())
593    }
594
595    fn names_ident(&self, ident: &Ident) -> bool {
596        self.names.contains(&ident.unraw().to_string())
597    }
598
599    fn bind(&mut self, ident: &Ident, exported: bool) {
600        let name = ident.unraw().to_string();
601        if exported {
602            self.exported.insert(name);
603        } else {
604            self.private.insert(name);
605        }
606    }
607}
608
609/// Whether the scan treats visibility as non-private: neither inherited nor `pub(self)`.
610fn is_visible(vis: &Visibility) -> bool {
611    match vis {
612        Visibility::Public(_) => true,
613        Visibility::Restricted(restricted) => !restricted.path.is_ident("self"),
614        Visibility::Inherited => false,
615    }
616}
617
618#[cfg(test)]
619mod tests {
620    use super::*;
621
622    fn names(names: &[&str]) -> BTreeSet<String> {
623        names.iter().map(|name| name.to_string()).collect()
624    }
625
626    fn file(path: &str, text: &str) -> SourceFile {
627        SourceFile::parse(PathBuf::from(path), text).unwrap_or_else(|error| panic!("{error}"))
628    }
629
630    fn found(text: &str) -> Vec<(usize, Form, String)> {
631        file("lib.rs", text)
632            .mentions(&names(&["guarded", "Alias"]))
633            .into_iter()
634            .map(|mention| (mention.line, mention.form, mention.name))
635            .collect()
636    }
637
638    #[test]
639    fn mentions_match_every_naming_form() {
640        let cases = [
641            ("rename", "use guarded::Thing as Other;", Form::Use, "guarded"),
642            ("rename target", "use other::Thing as Alias;", Form::Use, "Alias"),
643            ("leading `::`", "fn f() { ::guarded::run(); }", Form::Path, "guarded"),
644            ("glob", "use guarded::*;", Form::Use, "guarded"),
645            ("group", "use other::{a, guarded::b};", Form::Use, "guarded"),
646            ("group leaf", "use other::{a, Alias};", Form::Use, "Alias"),
647            (
648                "type position",
649                "struct S { field: Vec<guarded::T> }",
650                Form::Path,
651                "guarded",
652            ),
653            ("alias", "fn f(value: Alias) {}", Form::Path, "Alias"),
654            ("raw identifier", "fn f(value: r#Alias) {}", Form::Path, "Alias"),
655            (
656                "non-root segment",
657                "type T = crate::config::Alias;",
658                Form::Path,
659                "Alias",
660            ),
661            (
662                "macro token",
663                "fn f() { println!(\"{}\", guarded::VALUE); }",
664                Form::Token,
665                "guarded",
666            ),
667            (
668                "macro_rules body",
669                "macro_rules! m { () => { Alias::new() } }",
670                Form::Token,
671                "Alias",
672            ),
673            (
674                "attribute token",
675                "#[derive(guarded::Derive)] struct S;",
676                Form::Token,
677                "guarded",
678            ),
679            (
680                "extern crate",
681                "extern crate guarded as other;",
682                Form::ExternCrate,
683                "guarded",
684            ),
685            (
686                "extern crate rename",
687                "extern crate other as Alias;",
688                Form::ExternCrate,
689                "Alias",
690            ),
691            (
692                "test code",
693                "#[cfg(test)] mod tests { use guarded::X; }",
694                Form::Use,
695                "guarded",
696            ),
697        ];
698        for (case, text, form, name) in cases {
699            assert_eq!(found(text), [(1, form, name.to_string())], "{case}: {text}");
700        }
701    }
702
703    #[test]
704    fn mentions_ignore_comments_doc_text_strings_and_longer_names() {
705        let text = r#"
706            //! Module docs name guarded::Thing.
707            // A comment names guarded::Thing.
708            /* A block comment names Alias. */
709            /// Item docs name [`guarded::Thing`].
710            #[serde(with = "guarded::serde")]
711            #[doc = "Alias"]
712            struct S {
713                field: guarded_other::Thing,
714            }
715
716            fn f() -> &'static str {
717                println!("guarded::Thing");
718                "Alias"
719            }
720        "#;
721        assert_eq!(found(text), []);
722    }
723
724    #[test]
725    fn mentions_report_line_and_column() {
726        let mentions = file("dir/lib.rs", "fn f() {}\n\nfn g(value: Alias) {}\n").mentions(&names(&["Alias"]));
727        let lines: Vec<_> = mentions.iter().map(Mention::to_string).collect();
728        assert_eq!(lines, ["dir/lib.rs:3:13: path `Alias`"]);
729    }
730
731    #[test]
732    fn module_mentions_resolve_paths_from_the_file_and_ignore_other_names() {
733        let modules = names(&["guarded"]);
734        let cases = [
735            ("src/a.rs", "use crate::guarded::X;", 1),
736            ("src/a.rs", "use crate::{other, guarded::{X, Y}};", 2),
737            ("src/a.rs", "fn f() { crate::guarded::run(); }", 1),
738            ("src/a.rs", "fn f() { assert!(crate::guarded::ok()); }", 1),
739            ("src/a.rs", "use super::guarded;", 1),
740            ("src/a/b.rs", "use super::guarded;", 0),
741            ("src/a/b.rs", "use super::super::guarded;", 1),
742            ("src/a/mod.rs", "use super::guarded::X;", 1),
743            ("src/a.rs", "mod tests { use super::super::guarded::X; }", 1),
744            ("src/guarded/a.rs", "use super::Thing;", 1),
745            ("src/a.rs", "fn f(guarded: u8) -> u8 { let x = guarded; x }", 0),
746            ("src/a.rs", "use other::guarded::X;", 0),
747        ];
748        for (path, text, expected) in cases {
749            let found = file(path, text).module_mentions(Path::new("src"), &modules);
750            assert_eq!(found.len(), expected, "{path}: {text}: {found:?}");
751            assert!(found.iter().all(|mention| mention.name == "guarded"), "{found:?}");
752        }
753    }
754
755    fn tree(files: &[(&str, &str)]) -> SourceTree {
756        SourceTree {
757            files: files.iter().map(|(path, text)| file(path, text)).collect(),
758        }
759    }
760
761    fn aliases(files: &[(&str, &str)]) -> Result<BTreeSet<String>, Error> {
762        tree(files).aliases(Path::new("main.rs"), &names(&["guarded"]))
763    }
764
765    #[test]
766    fn aliases_include_root_imports_exported_items_and_their_file_private_sources() {
767        let main = r#"
768            extern crate guarded as renamed_crate;
769            use guarded::{RootName, nested::Original as RootRename, nested::{self}};
770            use guarded as _;
771            type RootType = Vec<guarded::Thing>;
772            use other::Unrelated;
773
774            mod inline {
775                use guarded::InlinePrivate;
776                pub(crate) use guarded::InlineVisible;
777                pub(crate) type InlineViaPrivate = InlinePrivate;
778            }
779        "#;
780        let other = r#"
781            pub(crate) type ViaPrivateChain = PrivateType;
782            use guarded::OtherPrivate;
783            pub(self) use guarded::OtherSelf;
784            type PrivateType = Option<OtherSelf>;
785            pub(crate) type ViaPrivate = Vec<OtherPrivate>;
786            pub(crate) use guarded::OtherVisible;
787            pub type OtherType = guarded::Thing;
788            pub(crate) use crate::RootName as Transitive;
789            pub(crate) type TransitiveType = Option<Transitive>;
790            macro_rules! guarded_macro { () => { guarded::make() } }
791            fn body() {
792                pub use guarded::InBody;
793            }
794        "#;
795        let unrelated = r#"
796            pub(crate) type SameNameElsewhere = OtherPrivate;
797        "#;
798
799        let expected = names(&[
800            "InlineViaPrivate",
801            "InlineVisible",
802            "OtherType",
803            "OtherVisible",
804            "RootName",
805            "RootRename",
806            "RootType",
807            "Transitive",
808            "TransitiveType",
809            "ViaPrivate",
810            "ViaPrivateChain",
811            "guarded_macro",
812            "nested",
813            "renamed_crate",
814        ]);
815        assert_eq!(
816            aliases(&[("main.rs", main), ("other.rs", other), ("unrelated.rs", unrelated)]).unwrap(),
817            expected
818        );
819    }
820
821    #[test]
822    fn aliases_reject_glob_imports_of_guarded_paths() {
823        let result = aliases(&[("main.rs", "use std::fmt;\nuse guarded::prelude::*;")]);
824        assert!(
825            matches!(&result, Err(Error::GlobImport { path, line: 2 }) if path == Path::new("main.rs")),
826            "{:?}",
827            result.map_err(|error| error.to_string())
828        );
829
830        let private_elsewhere = aliases(&[("main.rs", ""), ("other.rs", "use guarded::*;")]);
831        assert_eq!(private_elsewhere.unwrap(), BTreeSet::new());
832    }
833
834    #[test]
835    fn aliases_require_the_crate_root_among_the_files() {
836        assert!(matches!(
837            aliases(&[("lib.rs", "")]),
838            Err(Error::MissingCrateRoot { path }) if path == Path::new("main.rs")
839        ));
840    }
841
842    #[test]
843    fn read_parses_nested_rust_files_only() {
844        let dir = tempfile::tempdir().unwrap();
845        fs::create_dir_all(dir.path().join("a/b")).unwrap();
846        fs::write(dir.path().join("a/b/deep.rs"), "use guarded::X;").unwrap();
847        fs::write(dir.path().join("top.rs"), "fn f() {}").unwrap();
848        fs::write(dir.path().join("README.md"), "use guarded::X; not Rust").unwrap();
849
850        let tree = SourceTree::read(&[dir.path().to_path_buf()]).unwrap();
851        let paths: Vec<_> = tree.files.iter().map(|file| file.path.clone()).collect();
852        assert_eq!(paths, [dir.path().join("a/b/deep.rs"), dir.path().join("top.rs")]);
853        let mentions: Vec<_> = tree
854            .mentions(&names(&["guarded"]))
855            .into_iter()
856            .map(|m| m.path)
857            .collect();
858        assert_eq!(mentions, [dir.path().join("a/b/deep.rs")]);
859    }
860
861    #[test]
862    fn read_fails_without_rust_files() {
863        let dir = tempfile::tempdir().unwrap();
864        fs::write(dir.path().join("README.md"), "").unwrap();
865
866        assert!(matches!(
867            SourceTree::read(&[dir.path().to_path_buf()]),
868            Err(Error::NoSources { dirs }) if dirs == [dir.path().to_path_buf()]
869        ));
870        assert!(matches!(
871            SourceTree::read(&[dir.path().join("missing")]),
872            Err(Error::Read { path, .. }) if path == dir.path().join("missing")
873        ));
874    }
875
876    #[test]
877    fn read_fails_on_a_file_that_does_not_parse() {
878        let dir = tempfile::tempdir().unwrap();
879        fs::write(dir.path().join("good.rs"), "fn f() {}").unwrap();
880        fs::write(dir.path().join("bad.rs"), "fn f() {}\nfn g( {}\n").unwrap();
881
882        match SourceTree::read(&[dir.path().to_path_buf()]) {
883            Err(Error::Parse { path, line, .. }) => {
884                assert_eq!(path, dir.path().join("bad.rs"));
885                assert_eq!(line, 2);
886            }
887            Err(error) => panic!("unexpected error: {error}"),
888            Ok(_) => panic!("a file that doesn't parse must fail the read"),
889        }
890    }
891}