Skip to content

Commit 1ba7a38

Browse files
authored
Merge pull request rust-lang#19084 from Veykril/push-muworpzpzqup
Split cache priming into distinct phases
2 parents 93b72ce + a373fb2 commit 1ba7a38

File tree

14 files changed

+126
-66
lines changed

14 files changed

+126
-66
lines changed

src/tools/rust-analyzer/crates/base-db/src/input.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,9 @@ impl fmt::Display for CrateName {
129129
}
130130

131131
impl ops::Deref for CrateName {
132-
type Target = str;
133-
fn deref(&self) -> &str {
134-
self.0.as_str()
132+
type Target = Symbol;
133+
fn deref(&self) -> &Symbol {
134+
&self.0
135135
}
136136
}
137137

@@ -230,8 +230,8 @@ impl fmt::Display for CrateDisplayName {
230230
}
231231

232232
impl ops::Deref for CrateDisplayName {
233-
type Target = str;
234-
fn deref(&self) -> &str {
233+
type Target = Symbol;
234+
fn deref(&self) -> &Symbol {
235235
&self.crate_name
236236
}
237237
}

src/tools/rust-analyzer/crates/hir-def/src/import_map.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -519,7 +519,7 @@ mod tests {
519519
crate_graph[krate]
520520
.display_name
521521
.as_ref()
522-
.is_some_and(|it| &**it.crate_name() == crate_name)
522+
.is_some_and(|it| it.crate_name().as_str() == crate_name)
523523
})
524524
.expect("could not find crate");
525525

src/tools/rust-analyzer/crates/hir-def/src/nameres.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -337,7 +337,7 @@ impl DefMap {
337337
pub(crate) fn crate_def_map_query(db: &dyn DefDatabase, crate_id: CrateId) -> Arc<DefMap> {
338338
let crate_graph = db.crate_graph();
339339
let krate = &crate_graph[crate_id];
340-
let name = krate.display_name.as_deref().unwrap_or_default();
340+
let name = krate.display_name.as_deref().map(Symbol::as_str).unwrap_or_default();
341341
let _p = tracing::info_span!("crate_def_map_query", ?name).entered();
342342

343343
let module_data = ModuleData::new(

src/tools/rust-analyzer/crates/hir-expand/src/name.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,6 @@ impl AsName for ast::FieldKind {
262262

263263
impl AsName for base_db::Dependency {
264264
fn as_name(&self) -> Name {
265-
Name::new_root(&self.name)
265+
Name::new_symbol_root((*self.name).clone())
266266
}
267267
}

src/tools/rust-analyzer/crates/hir-expand/src/prettify_macro_expansion_.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,9 @@ pub fn prettify_macro_expansion(
4141
} else if let Some(dep) =
4242
target_crate.dependencies.iter().find(|dep| dep.crate_id == macro_def_crate)
4343
{
44-
make::tokens::ident(&dep.name)
44+
make::tokens::ident(dep.name.as_str())
4545
} else if let Some(crate_name) = &crate_graph[macro_def_crate].display_name {
46-
make::tokens::ident(crate_name.crate_name())
46+
make::tokens::ident(crate_name.crate_name().as_str())
4747
} else {
4848
return dollar_crate.clone();
4949
}

src/tools/rust-analyzer/crates/ide-db/src/prime_caches.rs

+89-34
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,13 @@ mod topologic_sort;
66

77
use std::time::Duration;
88

9-
use hir::db::DefDatabase;
9+
use hir::{db::DefDatabase, Symbol};
10+
use itertools::Itertools;
1011

1112
use crate::{
1213
base_db::{
1314
ra_salsa::{Database, ParallelDatabase, Snapshot},
14-
Cancelled, CrateId, SourceDatabase, SourceRootDatabase,
15+
Cancelled, CrateId, SourceDatabase,
1516
},
1617
symbol_index::SymbolsDatabase,
1718
FxIndexMap, RootDatabase,
@@ -21,11 +22,12 @@ use crate::{
2122
#[derive(Debug)]
2223
pub struct ParallelPrimeCachesProgress {
2324
/// the crates that we are currently priming.
24-
pub crates_currently_indexing: Vec<String>,
25+
pub crates_currently_indexing: Vec<Symbol>,
2526
/// the total number of crates we want to prime.
2627
pub crates_total: usize,
2728
/// the total number of crates that have finished priming
2829
pub crates_done: usize,
30+
pub work_type: &'static str,
2931
}
3032

3133
pub fn parallel_prime_caches(
@@ -47,41 +49,32 @@ pub fn parallel_prime_caches(
4749
};
4850

4951
enum ParallelPrimeCacheWorkerProgress {
50-
BeginCrate { crate_id: CrateId, crate_name: String },
52+
BeginCrate { crate_id: CrateId, crate_name: Symbol },
5153
EndCrate { crate_id: CrateId },
5254
}
5355

56+
// We split off def map computation from other work,
57+
// as the def map is the relevant one. Once the defmaps are computed
58+
// the project is ready to go, the other indices are just nice to have for some IDE features.
59+
#[derive(PartialOrd, Ord, PartialEq, Eq, Copy, Clone)]
60+
enum PrimingPhase {
61+
DefMap,
62+
ImportMap,
63+
CrateSymbols,
64+
}
65+
5466
let (work_sender, progress_receiver) = {
5567
let (progress_sender, progress_receiver) = crossbeam_channel::unbounded();
5668
let (work_sender, work_receiver) = crossbeam_channel::unbounded();
57-
let graph = graph.clone();
58-
let local_roots = db.local_roots();
5969
let prime_caches_worker = move |db: Snapshot<RootDatabase>| {
60-
while let Ok((crate_id, crate_name)) = work_receiver.recv() {
70+
while let Ok((crate_id, crate_name, kind)) = work_receiver.recv() {
6171
progress_sender
6272
.send(ParallelPrimeCacheWorkerProgress::BeginCrate { crate_id, crate_name })?;
6373

64-
// Compute the DefMap and possibly ImportMap
65-
let file_id = graph[crate_id].root_file_id;
66-
let root_id = db.file_source_root(file_id);
67-
if db.source_root(root_id).is_library {
68-
db.crate_def_map(crate_id);
69-
} else {
70-
// This also computes the DefMap
71-
db.import_map(crate_id);
72-
}
73-
74-
// Compute the symbol search index.
75-
// This primes the cache for `ide_db::symbol_index::world_symbols()`.
76-
//
77-
// We do this for workspace crates only (members of local_roots), because doing it
78-
// for all dependencies could be *very* unnecessarily slow in a large project.
79-
//
80-
// FIXME: We should do it unconditionally if the configuration is set to default to
81-
// searching dependencies (rust-analyzer.workspace.symbol.search.scope), but we
82-
// would need to pipe that configuration information down here.
83-
if local_roots.contains(&root_id) {
84-
db.crate_symbols(crate_id.into());
74+
match kind {
75+
PrimingPhase::DefMap => _ = db.crate_def_map(crate_id),
76+
PrimingPhase::ImportMap => _ = db.import_map(crate_id),
77+
PrimingPhase::CrateSymbols => _ = db.crate_symbols(crate_id.into()),
8578
}
8679

8780
progress_sender.send(ParallelPrimeCacheWorkerProgress::EndCrate { crate_id })?;
@@ -112,16 +105,34 @@ pub fn parallel_prime_caches(
112105
let mut crates_currently_indexing =
113106
FxIndexMap::with_capacity_and_hasher(num_worker_threads, Default::default());
114107

108+
let mut additional_phases = vec![];
109+
115110
while crates_done < crates_total {
116111
db.unwind_if_cancelled();
117112

118113
for crate_id in &mut crates_to_prime {
119-
work_sender
120-
.send((
121-
crate_id,
122-
graph[crate_id].display_name.as_deref().unwrap_or_default().to_owned(),
123-
))
124-
.ok();
114+
let krate = &graph[crate_id];
115+
let name = krate
116+
.display_name
117+
.as_deref()
118+
.cloned()
119+
.unwrap_or_else(|| Symbol::integer(crate_id.into_raw().into_u32() as usize));
120+
if krate.origin.is_lang() {
121+
additional_phases.push((crate_id, name.clone(), PrimingPhase::ImportMap));
122+
} else if krate.origin.is_local() {
123+
// Compute the symbol search index.
124+
// This primes the cache for `ide_db::symbol_index::world_symbols()`.
125+
//
126+
// We do this for workspace crates only (members of local_roots), because doing it
127+
// for all dependencies could be *very* unnecessarily slow in a large project.
128+
//
129+
// FIXME: We should do it unconditionally if the configuration is set to default to
130+
// searching dependencies (rust-analyzer.workspace.symbol.search.scope), but we
131+
// would need to pipe that configuration information down here.
132+
additional_phases.push((crate_id, name.clone(), PrimingPhase::CrateSymbols));
133+
}
134+
135+
work_sender.send((crate_id, name, PrimingPhase::DefMap)).ok();
125136
}
126137

127138
// recv_timeout is somewhat a hack, we need a way to from this thread check to see if the current salsa revision
@@ -153,6 +164,50 @@ pub fn parallel_prime_caches(
153164
crates_currently_indexing: crates_currently_indexing.values().cloned().collect(),
154165
crates_done,
155166
crates_total,
167+
work_type: "Indexing",
168+
};
169+
170+
cb(progress);
171+
}
172+
173+
let mut crates_done = 0;
174+
let crates_total = additional_phases.len();
175+
for w in additional_phases.into_iter().sorted_by_key(|&(_, _, phase)| phase) {
176+
work_sender.send(w).ok();
177+
}
178+
179+
while crates_done < crates_total {
180+
db.unwind_if_cancelled();
181+
182+
// recv_timeout is somewhat a hack, we need a way to from this thread check to see if the current salsa revision
183+
// is cancelled on a regular basis. workers will only exit if they are processing a task that is cancelled, or
184+
// if this thread exits, and closes the work channel.
185+
let worker_progress = match progress_receiver.recv_timeout(Duration::from_millis(10)) {
186+
Ok(p) => p,
187+
Err(crossbeam_channel::RecvTimeoutError::Timeout) => {
188+
continue;
189+
}
190+
Err(crossbeam_channel::RecvTimeoutError::Disconnected) => {
191+
// our workers may have died from a cancelled task, so we'll check and re-raise here.
192+
db.unwind_if_cancelled();
193+
break;
194+
}
195+
};
196+
match worker_progress {
197+
ParallelPrimeCacheWorkerProgress::BeginCrate { crate_id, crate_name } => {
198+
crates_currently_indexing.insert(crate_id, crate_name);
199+
}
200+
ParallelPrimeCacheWorkerProgress::EndCrate { crate_id } => {
201+
crates_currently_indexing.swap_remove(&crate_id);
202+
crates_done += 1;
203+
}
204+
};
205+
206+
let progress = ParallelPrimeCachesProgress {
207+
crates_currently_indexing: crates_currently_indexing.values().cloned().collect(),
208+
crates_done,
209+
crates_total,
210+
work_type: "Populating symbols",
156211
};
157212

158213
cb(progress);

src/tools/rust-analyzer/crates/ide/src/view_crate_graph.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,8 @@ impl<'a> dot::Labeller<'a, CrateId, Edge<'a>> for DotCrateGraph {
8484
}
8585

8686
fn node_label(&'a self, n: &CrateId) -> LabelText<'a> {
87-
let name = self.graph[*n].display_name.as_ref().map_or("(unnamed crate)", |name| name);
87+
let name =
88+
self.graph[*n].display_name.as_ref().map_or("(unnamed crate)", |name| name.as_str());
8889
LabelText::LabelStr(name.into())
8990
}
9091
}

src/tools/rust-analyzer/crates/intern/src/symbol/symbols.rs

+1
Original file line numberDiff line numberDiff line change
@@ -481,6 +481,7 @@ define_symbols! {
481481
u64,
482482
u8,
483483
unadjusted,
484+
unknown,
484485
Unknown,
485486
unpin,
486487
unreachable_2015,

src/tools/rust-analyzer/crates/project-model/src/project_json.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -508,5 +508,5 @@ fn serialize_crate_name<S>(name: &CrateName, se: S) -> Result<S::Ok, S::Error>
508508
where
509509
S: serde::Serializer,
510510
{
511-
se.serialize_str(name)
511+
se.serialize_str(name.as_str())
512512
}

src/tools/rust-analyzer/crates/project-model/src/tests.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ fn rust_project_is_proc_macro_has_proc_macro_dep() {
230230
let crate_data = &crate_graph[crate_id];
231231
// Assert that the project crate with `is_proc_macro` has a dependency
232232
// on the proc_macro sysroot crate.
233-
crate_data.dependencies.iter().find(|&dep| dep.name.deref() == "proc_macro").unwrap();
233+
crate_data.dependencies.iter().find(|&dep| *dep.name.deref() == sym::proc_macro).unwrap();
234234
}
235235

236236
#[test]

src/tools/rust-analyzer/crates/rust-analyzer/src/cli/diagnostics.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
use project_model::{CargoConfig, RustLibSource};
55
use rustc_hash::FxHashSet;
66

7-
use hir::{db::HirDatabase, Crate, HirFileIdExt, Module};
7+
use hir::{db::HirDatabase, sym, Crate, HirFileIdExt, Module};
88
use ide::{AnalysisHost, AssistResolveStrategy, Diagnostic, DiagnosticsConfig, Severity};
99
use ide_db::{base_db::SourceRootDatabase, LineIndexDatabase};
1010
use load_cargo::{load_workspace_at, LoadCargoConfig, ProcMacroServerChoice};
@@ -60,7 +60,7 @@ impl flags::Diagnostics {
6060
let file_id = module.definition_source_file_id(db).original_file(db);
6161
if !visited_files.contains(&file_id) {
6262
let crate_name =
63-
module.krate().display_name(db).as_deref().unwrap_or("unknown").to_owned();
63+
module.krate().display_name(db).as_deref().unwrap_or(&sym::unknown).to_owned();
6464
println!(
6565
"processing crate: {crate_name}, module: {}",
6666
_vfs.file_path(file_id.into())

src/tools/rust-analyzer/crates/rust-analyzer/src/cli/unresolved_references.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
//! Reports references in code that the IDE layer cannot resolve.
2-
use hir::{db::HirDatabase, AnyDiagnostic, Crate, HirFileIdExt as _, Module, Semantics};
2+
use hir::{db::HirDatabase, sym, AnyDiagnostic, Crate, HirFileIdExt as _, Module, Semantics};
33
use ide::{AnalysisHost, RootDatabase, TextRange};
44
use ide_db::{
55
base_db::{SourceDatabase, SourceRootDatabase},
@@ -66,7 +66,7 @@ impl flags::UnresolvedReferences {
6666
let file_id = module.definition_source_file_id(db).original_file(db);
6767
if !visited_files.contains(&file_id) {
6868
let crate_name =
69-
module.krate().display_name(db).as_deref().unwrap_or("unknown").to_owned();
69+
module.krate().display_name(db).as_deref().unwrap_or(&sym::unknown).to_owned();
7070
let file_path = vfs.file_path(file_id.into());
7171
eprintln!("processing crate: {crate_name}, module: {file_path}",);
7272

src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs

+17-6
Original file line numberDiff line numberDiff line change
@@ -325,26 +325,30 @@ impl GlobalState {
325325
}
326326

327327
for progress in prime_caches_progress {
328-
let (state, message, fraction);
328+
let (state, message, fraction, title);
329329
match progress {
330330
PrimeCachesProgress::Begin => {
331331
state = Progress::Begin;
332332
message = None;
333333
fraction = 0.0;
334+
title = "Indexing";
334335
}
335336
PrimeCachesProgress::Report(report) => {
336337
state = Progress::Report;
338+
title = report.work_type;
337339

338-
message = match &report.crates_currently_indexing[..] {
340+
message = match &*report.crates_currently_indexing {
339341
[crate_name] => Some(format!(
340-
"{}/{} ({crate_name})",
341-
report.crates_done, report.crates_total
342+
"{}/{} ({})",
343+
report.crates_done,
344+
report.crates_total,
345+
crate_name.as_str(),
342346
)),
343347
[crate_name, rest @ ..] => Some(format!(
344348
"{}/{} ({} + {} more)",
345349
report.crates_done,
346350
report.crates_total,
347-
crate_name,
351+
crate_name.as_str(),
348352
rest.len()
349353
)),
350354
_ => None,
@@ -356,6 +360,7 @@ impl GlobalState {
356360
state = Progress::End;
357361
message = None;
358362
fraction = 1.0;
363+
title = "Indexing";
359364

360365
self.prime_caches_queue.op_completed(());
361366
if cancelled {
@@ -365,7 +370,13 @@ impl GlobalState {
365370
}
366371
};
367372

368-
self.report_progress("Indexing", state, message, Some(fraction), None);
373+
self.report_progress(
374+
title,
375+
state,
376+
message,
377+
Some(fraction),
378+
Some("rustAnalyzer/cachePriming".to_owned()),
379+
);
369380
}
370381
}
371382
Event::Vfs(message) => {

src/tools/rust-analyzer/crates/test-fixture/src/lib.rs

+1-9
Original file line numberDiff line numberDiff line change
@@ -258,15 +258,7 @@ impl ChangeFixture {
258258
let to_id = crates[&to];
259259
let sysroot = crate_graph[to_id].origin.is_lang();
260260
crate_graph
261-
.add_dep(
262-
from_id,
263-
Dependency::with_prelude(
264-
CrateName::new(&to).unwrap(),
265-
to_id,
266-
prelude,
267-
sysroot,
268-
),
269-
)
261+
.add_dep(from_id, Dependency::with_prelude(to.clone(), to_id, prelude, sysroot))
270262
.unwrap();
271263
}
272264
}

0 commit comments

Comments
 (0)