Skip to main content

rust_analyzer/
priming_scope.rs

1//! Scope computation for cache priming.
2
3use ide_db::{RootDatabase, base_db::Crate};
4use rustc_hash::FxHashSet;
5use triomphe::Arc;
6
7/// Close `seeds` under transitive dependencies.
8pub(crate) fn compute(db: &RootDatabase, seeds: impl IntoIterator<Item = Crate>) -> Arc<[Crate]> {
9    let mut closure: FxHashSet<Crate> = FxHashSet::default();
10    let mut worklist: Vec<Crate> = seeds.into_iter().collect();
11    while let Some(krate) = worklist.pop() {
12        if !closure.insert(krate) {
13            continue;
14        }
15        worklist.extend(krate.data(db).dependencies.iter().map(|dep| dep.crate_id));
16    }
17    closure.into_iter().collect()
18}
19
20#[cfg(test)]
21mod tests {
22    use ide_db::{
23        RootDatabase,
24        base_db::{
25            CrateGraphBuilder, CrateName, CrateOrigin, CrateWorkspaceData, CratesIdMap,
26            DependencyBuilder, Env, LangCrateOrigin, TargetKind,
27        },
28        span::{Edition, FileId},
29    };
30    use rustc_hash::FxHashMap;
31    use triomphe::Arc as TriompheArc;
32    use vfs::AbsPathBuf;
33
34    use super::*;
35
36    fn empty_ws_data() -> TriompheArc<CrateWorkspaceData> {
37        TriompheArc::new(CrateWorkspaceData { target: Err("".into()), toolchain: None })
38    }
39
40    /// Builds a synthetic crate graph in a fresh `RootDatabase` and returns
41    /// the resolved `Crate` IDs keyed by the symbolic names used in `crates`.
42    ///
43    /// `crates` is a list of `(name, origin, deps)`. The crate root file id
44    /// is derived from the crate's index. Dependencies must refer to crates
45    /// declared earlier in the list.
46    fn build(crates: &[(&str, CrateOrigin, &[&str])]) -> (RootDatabase, FxHashMap<String, Crate>) {
47        let mut db = RootDatabase::default();
48        let mut graph = CrateGraphBuilder::default();
49        let proc_macro_cwd =
50            TriompheArc::new(AbsPathBuf::assert_utf8(std::env::current_dir().unwrap()));
51
52        let mut ids = Vec::with_capacity(crates.len());
53        for (i, (name, origin, _)) in crates.iter().enumerate() {
54            let id = graph.add_crate_root(
55                FileId::from_raw((i + 1) as u32),
56                Edition::Edition2021,
57                None,
58                None,
59                Default::default(),
60                Default::default(),
61                Env::default(),
62                origin.clone(),
63                Vec::new(),
64                TargetKind::Lib { is_proc_macro: false },
65                proc_macro_cwd.clone(),
66                empty_ws_data(),
67            );
68            ids.push((name.to_string(), id));
69        }
70
71        for (i, (_, _, deps)) in crates.iter().enumerate() {
72            for dep_name in *deps {
73                let from = ids[i].1;
74                let to = ids
75                    .iter()
76                    .find(|(n, _)| n == dep_name)
77                    .unwrap_or_else(|| panic!("unknown dep `{dep_name}`"))
78                    .1;
79                graph
80                    .add_dep(from, DependencyBuilder::new(CrateName::new(dep_name).unwrap(), to))
81                    .unwrap();
82            }
83        }
84
85        let resolved: CratesIdMap = graph.set_in_db(&mut db);
86        let by_name = ids.into_iter().map(|(n, id)| (n, resolved[&id])).collect();
87        (db, by_name)
88    }
89
90    fn lang(name: &str) -> CrateOrigin {
91        CrateOrigin::Lang(LangCrateOrigin::from(name))
92    }
93
94    fn local() -> CrateOrigin {
95        CrateOrigin::Local { repo: None, name: None }
96    }
97
98    fn library(name: &str) -> CrateOrigin {
99        CrateOrigin::Library { repo: None, name: CrateName::new(name).unwrap().symbol().clone() }
100    }
101
102    fn primed(scope: &Arc<[Crate]>, by_name: &FxHashMap<String, Crate>) -> Vec<String> {
103        let lookup: FxHashMap<Crate, &str> =
104            by_name.iter().map(|(n, c)| (*c, n.as_str())).collect();
105        let mut names: Vec<String> = scope.iter().map(|c| lookup[c].to_owned()).collect();
106        names.sort();
107        names
108    }
109
110    #[test]
111    fn closes_seeds_under_deps() {
112        // core ← lib_a ← lib_b ← bin_c
113        //                    ↖ test_d
114        let (db, by) = build(&[
115            ("core", lang("core"), &[]),
116            ("lib_a", local(), &["core"]),
117            ("lib_b", local(), &["lib_a"]),
118            ("bin_c", local(), &["lib_b"]),
119            ("test_d", local(), &["lib_b"]),
120        ]);
121
122        let scope = compute(&db, [by["lib_a"], by["lib_b"]]);
123        assert_eq!(primed(&scope, &by), vec!["core", "lib_a", "lib_b"]);
124    }
125
126    #[test]
127    fn active_seed_pulls_transitive_deps() {
128        let (db, by) = build(&[
129            ("core", lang("core"), &[]),
130            ("lib_a", local(), &["core"]),
131            ("lib_b", local(), &["lib_a"]),
132            ("bin_c", local(), &["lib_b"]),
133        ]);
134
135        let scope = compute(&db, [by["bin_c"]]);
136        assert_eq!(primed(&scope, &by), vec!["bin_c", "core", "lib_a", "lib_b"]);
137    }
138
139    #[test]
140    fn does_not_pull_reverse_deps() {
141        // Seeding only the leaf must not warm crates that depend on it.
142        let (db, by) = build(&[
143            ("core", lang("core"), &[]),
144            ("lib_leaf", local(), &["core"]),
145            ("dependent_a", local(), &["lib_leaf"]),
146            ("dependent_b", local(), &["lib_leaf"]),
147        ]);
148
149        let scope = compute(&db, [by["lib_leaf"]]);
150        assert_eq!(primed(&scope, &by), vec!["core", "lib_leaf"]);
151    }
152
153    #[test]
154    fn pulls_library_dep_via_seeded_crate() {
155        // A `Library` (non-workspace-member) origin behaves like any other —
156        // dep walk is origin-agnostic, only the seed selection cares.
157        let (db, by) = build(&[
158            ("core", lang("core"), &[]),
159            ("ext", library("serde"), &["core"]),
160            ("lib_a", local(), &["ext"]),
161        ]);
162
163        let scope = compute(&db, [by["lib_a"]]);
164        assert_eq!(primed(&scope, &by), vec!["core", "ext", "lib_a"]);
165    }
166}