]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/ide/src/prime_caches.rs
Rollup merge of #99293 - jo3bingham:issue-98720-fix, r=jyn514
[rust.git] / src / tools / rust-analyzer / crates / ide / src / prime_caches.rs
1 //! rust-analyzer is lazy and doesn't compute anything unless asked. This
2 //! sometimes is counter productive when, for example, the first goto definition
3 //! request takes longer to compute. This modules implemented prepopulation of
4 //! various caches, it's not really advanced at the moment.
5 mod topologic_sort;
6
7 use std::time::Duration;
8
9 use hir::db::DefDatabase;
10 use ide_db::{
11     base_db::{
12         salsa::{Database, ParallelDatabase, Snapshot},
13         Cancelled, CrateGraph, CrateId, SourceDatabase, SourceDatabaseExt,
14     },
15     FxHashSet, FxIndexMap,
16 };
17
18 use crate::RootDatabase;
19
20 /// We're indexing many crates.
21 #[derive(Debug)]
22 pub struct ParallelPrimeCachesProgress {
23     /// the crates that we are currently priming.
24     pub crates_currently_indexing: Vec<String>,
25     /// the total number of crates we want to prime.
26     pub crates_total: usize,
27     /// the total number of crates that have finished priming
28     pub crates_done: usize,
29 }
30
31 pub(crate) fn parallel_prime_caches(
32     db: &RootDatabase,
33     num_worker_threads: u8,
34     cb: &(dyn Fn(ParallelPrimeCachesProgress) + Sync),
35 ) {
36     let _p = profile::span("prime_caches");
37
38     let graph = db.crate_graph();
39     let mut crates_to_prime = {
40         let crate_ids = compute_crates_to_prime(db, &graph);
41
42         let mut builder = topologic_sort::TopologicalSortIter::builder();
43
44         for &crate_id in &crate_ids {
45             let crate_data = &graph[crate_id];
46             let dependencies = crate_data
47                 .dependencies
48                 .iter()
49                 .map(|d| d.crate_id)
50                 .filter(|i| crate_ids.contains(i));
51
52             builder.add(crate_id, dependencies);
53         }
54
55         builder.build()
56     };
57
58     enum ParallelPrimeCacheWorkerProgress {
59         BeginCrate { crate_id: CrateId, crate_name: String },
60         EndCrate { crate_id: CrateId },
61     }
62
63     let (work_sender, progress_receiver) = {
64         let (progress_sender, progress_receiver) = crossbeam_channel::unbounded();
65         let (work_sender, work_receiver) = crossbeam_channel::unbounded();
66         let prime_caches_worker = move |db: Snapshot<RootDatabase>| {
67             while let Ok((crate_id, crate_name)) = work_receiver.recv() {
68                 progress_sender
69                     .send(ParallelPrimeCacheWorkerProgress::BeginCrate { crate_id, crate_name })?;
70
71                 // This also computes the DefMap
72                 db.import_map(crate_id);
73
74                 progress_sender.send(ParallelPrimeCacheWorkerProgress::EndCrate { crate_id })?;
75             }
76
77             Ok::<_, crossbeam_channel::SendError<_>>(())
78         };
79
80         for _ in 0..num_worker_threads {
81             let worker = prime_caches_worker.clone();
82             let db = db.snapshot();
83             std::thread::spawn(move || Cancelled::catch(|| worker(db)));
84         }
85
86         (work_sender, progress_receiver)
87     };
88
89     let crates_total = crates_to_prime.pending();
90     let mut crates_done = 0;
91
92     // an index map is used to preserve ordering so we can sort the progress report in order of
93     // "longest crate to index" first
94     let mut crates_currently_indexing =
95         FxIndexMap::with_capacity_and_hasher(num_worker_threads as _, Default::default());
96
97     while crates_done < crates_total {
98         db.unwind_if_cancelled();
99
100         for crate_id in &mut crates_to_prime {
101             work_sender
102                 .send((
103                     crate_id,
104                     graph[crate_id].display_name.as_deref().unwrap_or_default().to_string(),
105                 ))
106                 .ok();
107         }
108
109         // recv_timeout is somewhat a hack, we need a way to from this thread check to see if the current salsa revision
110         // is cancelled on a regular basis. workers will only exit if they are processing a task that is cancelled, or
111         // if this thread exits, and closes the work channel.
112         let worker_progress = match progress_receiver.recv_timeout(Duration::from_millis(10)) {
113             Ok(p) => p,
114             Err(crossbeam_channel::RecvTimeoutError::Timeout) => {
115                 continue;
116             }
117             Err(crossbeam_channel::RecvTimeoutError::Disconnected) => {
118                 // our workers may have died from a cancelled task, so we'll check and re-raise here.
119                 db.unwind_if_cancelled();
120                 break;
121             }
122         };
123         match worker_progress {
124             ParallelPrimeCacheWorkerProgress::BeginCrate { crate_id, crate_name } => {
125                 crates_currently_indexing.insert(crate_id, crate_name);
126             }
127             ParallelPrimeCacheWorkerProgress::EndCrate { crate_id } => {
128                 crates_currently_indexing.remove(&crate_id);
129                 crates_to_prime.mark_done(crate_id);
130                 crates_done += 1;
131             }
132         };
133
134         let progress = ParallelPrimeCachesProgress {
135             crates_currently_indexing: crates_currently_indexing.values().cloned().collect(),
136             crates_done,
137             crates_total,
138         };
139
140         cb(progress);
141     }
142 }
143
144 fn compute_crates_to_prime(db: &RootDatabase, graph: &CrateGraph) -> FxHashSet<CrateId> {
145     // We're only interested in the workspace crates and the `ImportMap`s of their direct
146     // dependencies, though in practice the latter also compute the `DefMap`s.
147     // We don't prime transitive dependencies because they're generally not visible in
148     // the current workspace.
149     graph
150         .iter()
151         .filter(|&id| {
152             let file_id = graph[id].root_file_id;
153             let root_id = db.file_source_root(file_id);
154             !db.source_root(root_id).is_library
155         })
156         .flat_map(|id| graph[id].dependencies.iter().map(|krate| krate.crate_id))
157         .collect()
158 }