Skip to content

Commit 79fe11c

Browse files
committed
Shuffle some things around
1 parent e963846 commit 79fe11c

File tree

2 files changed

+91
-74
lines changed

2 files changed

+91
-74
lines changed

crates/rust-analyzer/src/global_state.rs

+11-3
Original file line numberDiff line numberDiff line change
@@ -52,24 +52,31 @@ pub(crate) type ReqQueue = lsp_server::ReqQueue<(String, Instant), ReqHandler>;
5252
pub(crate) struct GlobalState {
5353
sender: Sender<lsp_server::Message>,
5454
req_queue: ReqQueue,
55+
5556
pub(crate) task_pool: Handle<TaskPool<Task>, Receiver<Task>>,
56-
pub(crate) loader: Handle<Box<dyn vfs::loader::Handle>, Receiver<vfs::loader::Message>>,
57+
5758
pub(crate) config: Arc<Config>,
5859
pub(crate) analysis_host: AnalysisHost,
5960
pub(crate) diagnostics: DiagnosticCollection,
6061
pub(crate) mem_docs: MemDocs,
62+
pub(crate) source_root_config: SourceRootConfig,
6163
pub(crate) semantic_tokens_cache: Arc<Mutex<FxHashMap<Url, SemanticTokens>>>,
64+
65+
// status
6266
pub(crate) shutdown_requested: bool,
6367
pub(crate) last_reported_status: Option<lsp_ext::ServerStatusParams>,
64-
pub(crate) source_root_config: SourceRootConfig,
6568

69+
// proc macros
6670
pub(crate) proc_macro_changed: bool,
6771
pub(crate) proc_macro_clients: Arc<[anyhow::Result<ProcMacroServer>]>,
6872

73+
// Flycheck
6974
pub(crate) flycheck: Arc<[FlycheckHandle]>,
7075
pub(crate) flycheck_sender: Sender<flycheck::Message>,
7176
pub(crate) flycheck_receiver: Receiver<flycheck::Message>,
7277

78+
// VFS
79+
pub(crate) loader: Handle<Box<dyn vfs::loader::Handle>, Receiver<vfs::loader::Message>>,
7380
pub(crate) vfs: Arc<RwLock<(vfs::Vfs, IntMap<FileId, LineEndings>)>>,
7481
pub(crate) vfs_config_version: u32,
7582
pub(crate) vfs_progress_config_version: u32,
@@ -102,11 +109,12 @@ pub(crate) struct GlobalState {
102109
/// the user just adds comments or whitespace to Cargo.toml, we do not want
103110
/// to invalidate any salsa caches.
104111
pub(crate) workspaces: Arc<Vec<ProjectWorkspace>>,
112+
113+
// op queues
105114
pub(crate) fetch_workspaces_queue: OpQueue<(), Option<Vec<anyhow::Result<ProjectWorkspace>>>>,
106115
pub(crate) fetch_build_data_queue:
107116
OpQueue<(), (Arc<Vec<ProjectWorkspace>>, Vec<anyhow::Result<WorkspaceBuildScripts>>)>,
108117
pub(crate) fetch_proc_macros_queue: OpQueue<Vec<ProcMacroPaths>, bool>,
109-
110118
pub(crate) prime_caches_queue: OpQueue,
111119
}
112120

crates/rust-analyzer/src/main_loop.rs

+80-71
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ pub(crate) enum PrimeCachesProgress {
7777

7878
impl fmt::Debug for Event {
7979
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80-
let debug_verbose_not = |not: &Notification, f: &mut fmt::Formatter<'_>| {
80+
let debug_non_verbose = |not: &Notification, f: &mut fmt::Formatter<'_>| {
8181
f.debug_struct("Notification").field("method", &not.method).finish()
8282
};
8383

@@ -86,7 +86,7 @@ impl fmt::Debug for Event {
8686
if notification_is::<lsp_types::notification::DidOpenTextDocument>(not)
8787
|| notification_is::<lsp_types::notification::DidChangeTextDocument>(not)
8888
{
89-
return debug_verbose_not(not, f);
89+
return debug_non_verbose(not, f);
9090
}
9191
}
9292
Event::Task(Task::Response(resp)) => {
@@ -112,38 +112,7 @@ impl GlobalState {
112112
self.update_status_or_notify();
113113

114114
if self.config.did_save_text_document_dynamic_registration() {
115-
let save_registration_options = lsp_types::TextDocumentSaveRegistrationOptions {
116-
include_text: Some(false),
117-
text_document_registration_options: lsp_types::TextDocumentRegistrationOptions {
118-
document_selector: Some(vec![
119-
lsp_types::DocumentFilter {
120-
language: None,
121-
scheme: None,
122-
pattern: Some("**/*.rs".into()),
123-
},
124-
lsp_types::DocumentFilter {
125-
language: None,
126-
scheme: None,
127-
pattern: Some("**/Cargo.toml".into()),
128-
},
129-
lsp_types::DocumentFilter {
130-
language: None,
131-
scheme: None,
132-
pattern: Some("**/Cargo.lock".into()),
133-
},
134-
]),
135-
},
136-
};
137-
138-
let registration = lsp_types::Registration {
139-
id: "textDocument/didSave".to_string(),
140-
method: "textDocument/didSave".to_string(),
141-
register_options: Some(serde_json::to_value(save_registration_options).unwrap()),
142-
};
143-
self.send_request::<lsp_types::request::RegisterCapability>(
144-
lsp_types::RegistrationParams { registrations: vec![registration] },
145-
|_, _| (),
146-
);
115+
self.register_did_save_capability();
147116
}
148117

149118
self.fetch_workspaces_queue.request_op("startup".to_string(), ());
@@ -152,17 +121,54 @@ impl GlobalState {
152121
}
153122

154123
while let Some(event) = self.next_event(&inbox) {
155-
if let Event::Lsp(lsp_server::Message::Notification(not)) = &event {
156-
if not.method == lsp_types::notification::Exit::METHOD {
157-
return Ok(());
158-
}
124+
if matches!(
125+
&event,
126+
Event::Lsp(lsp_server::Message::Notification(Notification { method, .. }))
127+
if method == lsp_types::notification::Exit::METHOD
128+
) {
129+
return Ok(());
159130
}
160-
self.handle_event(event)?
131+
self.handle_event(event)?;
161132
}
162133

163134
Err("client exited without proper shutdown sequence".into())
164135
}
165136

137+
fn register_did_save_capability(&mut self) {
138+
let save_registration_options = lsp_types::TextDocumentSaveRegistrationOptions {
139+
include_text: Some(false),
140+
text_document_registration_options: lsp_types::TextDocumentRegistrationOptions {
141+
document_selector: Some(vec![
142+
lsp_types::DocumentFilter {
143+
language: None,
144+
scheme: None,
145+
pattern: Some("**/*.rs".into()),
146+
},
147+
lsp_types::DocumentFilter {
148+
language: None,
149+
scheme: None,
150+
pattern: Some("**/Cargo.toml".into()),
151+
},
152+
lsp_types::DocumentFilter {
153+
language: None,
154+
scheme: None,
155+
pattern: Some("**/Cargo.lock".into()),
156+
},
157+
]),
158+
},
159+
};
160+
161+
let registration = lsp_types::Registration {
162+
id: "textDocument/didSave".to_string(),
163+
method: "textDocument/didSave".to_string(),
164+
register_options: Some(serde_json::to_value(save_registration_options).unwrap()),
165+
};
166+
self.send_request::<lsp_types::request::RegisterCapability>(
167+
lsp_types::RegistrationParams { registrations: vec![registration] },
168+
|_, _| (),
169+
);
170+
}
171+
166172
fn next_event(&self, inbox: &Receiver<lsp_server::Message>) -> Option<Event> {
167173
select! {
168174
recv(inbox) -> msg =>
@@ -184,20 +190,20 @@ impl GlobalState {
184190
// NOTE: don't count blocking select! call as a loop-turn time
185191
let _p = profile::span("GlobalState::handle_event");
186192

187-
let event_dbg = format!("{event:?}");
188-
tracing::debug!("{:?} handle_event({:?})", loop_start, event);
189-
let task_queue_len = self.task_pool.handle.len();
190-
if task_queue_len > 0 {
191-
tracing::info!("task queue len: {}", task_queue_len);
193+
let event_dbg_msg = format!("{event:?}");
194+
tracing::debug!("{:?} handle_event({})", loop_start, event_dbg_msg);
195+
if tracing::enabled!(tracing::Level::INFO) {
196+
let task_queue_len = self.task_pool.handle.len();
197+
if task_queue_len > 0 {
198+
tracing::info!("task queue len: {}", task_queue_len);
199+
}
192200
}
193201

194202
let was_quiescent = self.is_quiescent();
195203
match event {
196204
Event::Lsp(msg) => match msg {
197205
lsp_server::Message::Request(req) => self.on_new_request(loop_start, req),
198-
lsp_server::Message::Notification(not) => {
199-
self.on_notification(not)?;
200-
}
206+
lsp_server::Message::Notification(not) => self.on_notification(not)?,
201207
lsp_server::Message::Response(resp) => self.complete_request(resp),
202208
},
203209
Event::Task(task) => {
@@ -291,7 +297,8 @@ impl GlobalState {
291297
}
292298
}
293299

294-
if !was_quiescent || state_changed {
300+
let client_refresh = !was_quiescent || state_changed;
301+
if client_refresh {
295302
// Refresh semantic tokens if the client supports it.
296303
if self.config.semantic_tokens_refresh() {
297304
self.semantic_tokens_cache.lock().clear();
@@ -309,9 +316,9 @@ impl GlobalState {
309316
}
310317
}
311318

312-
if (!was_quiescent || state_changed || memdocs_added_or_removed)
313-
&& self.config.publish_diagnostics()
314-
{
319+
let update_diagnostics = (!was_quiescent || state_changed || memdocs_added_or_removed)
320+
&& self.config.publish_diagnostics();
321+
if update_diagnostics {
315322
self.update_diagnostics()
316323
}
317324
}
@@ -371,38 +378,40 @@ impl GlobalState {
371378
}
372379

373380
if let Some((cause, ())) = self.prime_caches_queue.should_start_op() {
374-
tracing::debug!(%cause, "will prime caches");
375-
let num_worker_threads = self.config.prime_caches_num_threads();
376-
377-
self.task_pool.handle.spawn_with_sender({
378-
let analysis = self.snapshot().analysis;
379-
move |sender| {
380-
sender.send(Task::PrimeCaches(PrimeCachesProgress::Begin)).unwrap();
381-
let res = analysis.parallel_prime_caches(num_worker_threads, |progress| {
382-
let report = PrimeCachesProgress::Report(progress);
383-
sender.send(Task::PrimeCaches(report)).unwrap();
384-
});
385-
sender
386-
.send(Task::PrimeCaches(PrimeCachesProgress::End {
387-
cancelled: res.is_err(),
388-
}))
389-
.unwrap();
390-
}
391-
});
381+
self.prime_caches(cause);
392382
}
393383

394384
self.update_status_or_notify();
395385

396386
let loop_duration = loop_start.elapsed();
397387
if loop_duration > Duration::from_millis(100) && was_quiescent {
398-
tracing::warn!("overly long loop turn took {loop_duration:?}: {event_dbg}");
388+
tracing::warn!("overly long loop turn took {loop_duration:?}: {event_dbg_msg}");
399389
self.poke_rust_analyzer_developer(format!(
400-
"overly long loop turn took {loop_duration:?}: {event_dbg}"
390+
"overly long loop turn took {loop_duration:?}: {event_dbg_msg}"
401391
));
402392
}
403393
Ok(())
404394
}
405395

396+
fn prime_caches(&mut self, cause: String) {
397+
tracing::debug!(%cause, "will prime caches");
398+
let num_worker_threads = self.config.prime_caches_num_threads();
399+
400+
self.task_pool.handle.spawn_with_sender({
401+
let analysis = self.snapshot().analysis;
402+
move |sender| {
403+
sender.send(Task::PrimeCaches(PrimeCachesProgress::Begin)).unwrap();
404+
let res = analysis.parallel_prime_caches(num_worker_threads, |progress| {
405+
let report = PrimeCachesProgress::Report(progress);
406+
sender.send(Task::PrimeCaches(report)).unwrap();
407+
});
408+
sender
409+
.send(Task::PrimeCaches(PrimeCachesProgress::End { cancelled: res.is_err() }))
410+
.unwrap();
411+
}
412+
});
413+
}
414+
406415
fn update_status_or_notify(&mut self) {
407416
let status = self.current_status();
408417
if self.last_reported_status.as_ref() != Some(&status) {

0 commit comments

Comments
 (0)