1 //! The main loop of `rust-analyzer` responsible for dispatching LSP
2 //! requests/replies and notifications back to the client.
5 time::{Duration, Instant},
8 use always_assert::always;
9 use crossbeam_channel::{select, Receiver};
10 use ide::PrimeCachesProgress;
11 use ide::{Canceled, FileId};
12 use ide_db::base_db::VfsPath;
13 use lsp_server::{Connection, Notification, Request, Response};
14 use lsp_types::notification::Notification as _;
19 dispatch::{NotificationDispatcher, RequestDispatcher},
20 document::DocumentData,
22 global_state::{file_id_to_url, url_to_file_id, GlobalState, Status},
24 lsp_utils::{apply_document_changes, is_canceled, notification_is, Progress},
25 reload::{BuildDataProgress, ProjectWorkspaceProgress},
29 pub fn main_loop(config: Config, connection: Connection) -> Result<()> {
30 log::info!("initial config: {:#?}", config);
32 // Windows scheduler implements priority boosts: if thread waits for an
33 // event (like a condvar), and event fires, priority of the thread is
34 // temporary bumped. This optimization backfires in our case: each time the
35 // `main_loop` schedules a task to run on a threadpool, the worker threads
36 // gets a higher priority, and (on a machine with fewer cores) displaces the
37 // main loop! We work-around this by marking the main loop as a
38 // higher-priority thread.
40 // https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities
41 // https://docs.microsoft.com/en-us/windows/win32/procthread/priority-boosts
42 // https://github.com/rust-analyzer/rust-analyzer/issues/2835
45 use winapi::um::processthreadsapi::*;
46 let thread = GetCurrentThread();
47 let thread_priority_above_normal = 1;
48 SetThreadPriority(thread, thread_priority_above_normal);
51 GlobalState::new(connection.sender, config).run(connection.receiver)
55 Lsp(lsp_server::Message),
57 Vfs(vfs::loader::Message),
58 Flycheck(flycheck::Message),
62 pub(crate) enum Task {
64 Diagnostics(Vec<(FileId, Vec<lsp_types::Diagnostic>)>),
65 PrimeCaches(PrimeCachesProgress),
66 FetchWorkspace(ProjectWorkspaceProgress),
67 FetchBuildData(BuildDataProgress),
70 impl fmt::Debug for Event {
71 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
72 let debug_verbose_not = |not: &Notification, f: &mut fmt::Formatter| {
73 f.debug_struct("Notification").field("method", ¬.method).finish()
77 Event::Lsp(lsp_server::Message::Notification(not)) => {
78 if notification_is::<lsp_types::notification::DidOpenTextDocument>(not)
79 || notification_is::<lsp_types::notification::DidChangeTextDocument>(not)
81 return debug_verbose_not(not, f);
84 Event::Task(Task::Response(resp)) => {
86 .debug_struct("Response")
87 .field("id", &resp.id)
88 .field("error", &resp.error)
94 Event::Lsp(it) => fmt::Debug::fmt(it, f),
95 Event::Task(it) => fmt::Debug::fmt(it, f),
96 Event::Vfs(it) => fmt::Debug::fmt(it, f),
97 Event::Flycheck(it) => fmt::Debug::fmt(it, f),
103 fn run(mut self, inbox: Receiver<lsp_server::Message>) -> Result<()> {
104 if self.config.linked_projects().is_empty()
105 && self.config.notifications().cargo_toml_not_found
108 lsp_types::MessageType::Error,
109 "rust-analyzer failed to discover workspace".to_string(),
113 if self.config.did_save_text_document_dynamic_registration() {
114 let save_registration_options = lsp_types::TextDocumentSaveRegistrationOptions {
115 include_text: Some(false),
116 text_document_registration_options: lsp_types::TextDocumentRegistrationOptions {
117 document_selector: Some(vec![
118 lsp_types::DocumentFilter {
121 pattern: Some("**/*.rs".into()),
123 lsp_types::DocumentFilter {
126 pattern: Some("**/Cargo.toml".into()),
128 lsp_types::DocumentFilter {
131 pattern: Some("**/Cargo.lock".into()),
137 let registration = lsp_types::Registration {
138 id: "textDocument/didSave".to_string(),
139 method: "textDocument/didSave".to_string(),
140 register_options: Some(serde_json::to_value(save_registration_options).unwrap()),
142 self.send_request::<lsp_types::request::RegisterCapability>(
143 lsp_types::RegistrationParams { registrations: vec![registration] },
148 self.fetch_workspaces_request();
149 self.fetch_workspaces_if_needed();
151 while let Some(event) = self.next_event(&inbox) {
152 if let Event::Lsp(lsp_server::Message::Notification(not)) = &event {
153 if not.method == lsp_types::notification::Exit::METHOD {
157 self.handle_event(event)?
160 Err("client exited without proper shutdown sequence")?
163 fn next_event(&self, inbox: &Receiver<lsp_server::Message>) -> Option<Event> {
165 recv(inbox) -> msg =>
166 msg.ok().map(Event::Lsp),
168 recv(self.task_pool.receiver) -> task =>
169 Some(Event::Task(task.unwrap())),
171 recv(self.loader.receiver) -> task =>
172 Some(Event::Vfs(task.unwrap())),
174 recv(self.flycheck_receiver) -> task =>
175 Some(Event::Flycheck(task.unwrap())),
179 fn handle_event(&mut self, event: Event) -> Result<()> {
180 let loop_start = Instant::now();
181 // NOTE: don't count blocking select! call as a loop-turn time
182 let _p = profile::span("GlobalState::handle_event");
184 log::info!("handle_event({:?})", event);
185 let task_queue_len = self.task_pool.handle.len();
186 if task_queue_len > 0 {
187 log::info!("task queue len: {}", task_queue_len);
190 let mut new_status = self.status;
192 Event::Lsp(msg) => match msg {
193 lsp_server::Message::Request(req) => self.on_request(loop_start, req)?,
194 lsp_server::Message::Notification(not) => {
195 self.on_notification(not)?;
197 lsp_server::Message::Response(resp) => self.complete_request(resp),
199 Event::Task(mut task) => {
200 let _p = profile::span("GlobalState::handle_event/task");
201 let mut prime_caches_progress = Vec::new();
204 Task::Response(response) => self.respond(response),
205 Task::Diagnostics(diagnostics_per_file) => {
206 for (file_id, diagnostics) in diagnostics_per_file {
207 self.diagnostics.set_native_diagnostics(file_id, diagnostics)
210 Task::PrimeCaches(progress) => match progress {
211 PrimeCachesProgress::Started => prime_caches_progress.push(progress),
212 PrimeCachesProgress::StartedOnCrate { .. } => {
213 match prime_caches_progress.last_mut() {
214 Some(last @ PrimeCachesProgress::StartedOnCrate { .. }) => {
215 // Coalesce subsequent update events.
218 _ => prime_caches_progress.push(progress),
221 PrimeCachesProgress::Finished => prime_caches_progress.push(progress),
223 Task::FetchWorkspace(progress) => {
224 let (state, msg) = match progress {
225 ProjectWorkspaceProgress::Begin => (Progress::Begin, None),
226 ProjectWorkspaceProgress::Report(msg) => {
227 (Progress::Report, Some(msg))
229 ProjectWorkspaceProgress::End(workspaces) => {
230 self.fetch_workspaces_completed();
231 self.switch_workspaces(workspaces, None);
232 (Progress::End, None)
235 self.report_progress("fetching", state, msg, None);
237 Task::FetchBuildData(progress) => {
238 let (state, msg) = match progress {
239 BuildDataProgress::Begin => (Some(Progress::Begin), None),
240 BuildDataProgress::Report(msg) => {
241 (Some(Progress::Report), Some(msg))
243 BuildDataProgress::End(collector) => {
244 self.fetch_build_data_completed();
245 let workspaces = (*self.workspaces)
250 self.switch_workspaces(workspaces, Some(collector));
251 (Some(Progress::End), None)
254 if let Some(state) = state {
255 self.report_progress("loading", state, msg, None);
259 // Coalesce multiple task events into one loop turn
260 task = match self.task_pool.receiver.try_recv() {
266 for progress in prime_caches_progress {
267 let (state, message, fraction);
269 PrimeCachesProgress::Started => {
270 state = Progress::Begin;
274 PrimeCachesProgress::StartedOnCrate { on_crate, n_done, n_total } => {
275 state = Progress::Report;
276 message = Some(format!("{}/{} ({})", n_done, n_total, on_crate));
277 fraction = Progress::fraction(n_done, n_total);
279 PrimeCachesProgress::Finished => {
280 state = Progress::End;
286 self.report_progress("indexing", state, message, Some(fraction));
289 Event::Vfs(mut task) => {
290 let _p = profile::span("GlobalState::handle_event/vfs");
293 vfs::loader::Message::Loaded { files } => {
294 let vfs = &mut self.vfs.write().0;
295 for (path, contents) in files {
296 let path = VfsPath::from(path);
297 if !self.mem_docs.contains_key(&path) {
298 vfs.set_file_contents(path, contents);
302 vfs::loader::Message::Progress { n_total, n_done, config_version } => {
303 always!(config_version <= self.vfs_config_version);
305 new_status = Status::Invalid;
307 let state = if n_done == 0 {
308 new_status = Status::Loading;
310 } else if n_done < n_total {
313 assert_eq!(n_done, n_total);
314 new_status = Status::Ready {
315 partial: self.config.load_out_dirs_from_check()
316 && self.workspace_build_data.is_none()
317 || config_version < self.vfs_config_version,
321 self.report_progress(
324 Some(format!("{}/{}", n_done, n_total)),
325 Some(Progress::fraction(n_done, n_total)),
330 // Coalesce many VFS event into a single loop turn
331 task = match self.loader.receiver.try_recv() {
337 Event::Flycheck(mut task) => {
338 let _p = profile::span("GlobalState::handle_event/flycheck");
341 flycheck::Message::AddDiagnostic { workspace_root, diagnostic } => {
343 crate::diagnostics::to_proto::map_rust_diagnostic_to_lsp(
344 &self.config.diagnostics_map(),
348 for diag in diagnostics {
349 match url_to_file_id(&self.vfs.read().0, &diag.url) {
350 Ok(file_id) => self.diagnostics.add_check_diagnostic(
357 "File with cargo diagnostic not found in VFS: {}",
365 flycheck::Message::Progress { id, progress } => {
366 let (state, message) = match progress {
367 flycheck::Progress::DidStart => {
368 self.diagnostics.clear_check();
369 (Progress::Begin, None)
371 flycheck::Progress::DidCheckCrate(target) => {
372 (Progress::Report, Some(target))
374 flycheck::Progress::DidCancel => (Progress::End, None),
375 flycheck::Progress::DidFinish(result) => {
376 if let Err(err) = result {
377 log::error!("cargo check failed: {}", err)
379 (Progress::End, None)
383 // When we're running multiple flychecks, we have to include a disambiguator in
384 // the title, or the editor complains. Note that this is a user-facing string.
385 let title = if self.flycheck.len() == 1 {
386 "cargo check".to_string()
388 format!("cargo check (#{})", id + 1)
390 self.report_progress(&title, state, message, None);
393 // Coalesce many flycheck updates into a single loop turn
394 task = match self.flycheck_receiver.try_recv() {
402 let state_changed = self.process_changes();
403 let prev_status = self.status;
404 if prev_status != new_status {
405 self.transition(new_status);
407 let is_ready = matches!(self.status, Status::Ready { .. });
408 if prev_status == Status::Loading && is_ready {
409 for flycheck in &self.flycheck {
414 if is_ready && (state_changed || prev_status == Status::Loading) {
415 self.update_file_notifications_on_threadpool();
417 // Refresh semantic tokens if the client supports it.
418 if self.config.semantic_tokens_refresh() {
419 self.semantic_tokens_cache.lock().clear();
420 self.send_request::<lsp_types::request::SemanticTokensRefesh>((), |_, _| ());
423 // Refresh code lens if the client supports it.
424 if self.config.code_lens_refresh() {
425 self.send_request::<lsp_types::request::CodeLensRefresh>((), |_, _| ());
429 if let Some(diagnostic_changes) = self.diagnostics.take_changes() {
430 for file_id in diagnostic_changes {
431 let url = file_id_to_url(&self.vfs.read().0, file_id);
432 let diagnostics = self.diagnostics.diagnostics_for(file_id).cloned().collect();
433 let version = from_proto::vfs_path(&url)
434 .map(|path| self.mem_docs.get(&path).map(|it| it.version))
435 .unwrap_or_default();
437 self.send_notification::<lsp_types::notification::PublishDiagnostics>(
438 lsp_types::PublishDiagnosticsParams { uri: url, diagnostics, version },
443 self.fetch_workspaces_if_needed();
444 self.fetch_build_data_if_needed();
446 let loop_duration = loop_start.elapsed();
447 if loop_duration > Duration::from_millis(100) {
448 log::warn!("overly long loop turn: {:?}", loop_duration);
449 if env::var("RA_PROFILE").is_ok() {
451 lsp_types::MessageType::Error,
452 format!("overly long loop turn: {:?}", loop_duration),
459 fn on_request(&mut self, request_received: Instant, req: Request) -> Result<()> {
460 self.register_request(&req, request_received);
462 if self.shutdown_requested {
463 self.respond(Response::new_err(
465 lsp_server::ErrorCode::InvalidRequest as i32,
466 "Shutdown already requested.".to_owned(),
472 if self.status == Status::Loading && req.method != "shutdown" {
473 self.respond(lsp_server::Response::new_err(
475 // FIXME: i32 should impl From<ErrorCode> (from() guarantees lossless conversion)
476 lsp_server::ErrorCode::ContentModified as i32,
477 "Rust Analyzer is still loading...".to_owned(),
482 RequestDispatcher { req: Some(req), global_state: self }
483 .on_sync::<lsp_ext::ReloadWorkspace>(|s, ()| Ok(s.fetch_workspaces_request()))?
484 .on_sync::<lsp_ext::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
485 .on_sync::<lsp_ext::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
486 .on_sync::<lsp_types::request::Shutdown>(|s, ()| {
487 s.shutdown_requested = true;
490 .on_sync::<lsp_types::request::SelectionRangeRequest>(|s, p| {
491 handlers::handle_selection_range(s.snapshot(), p)
493 .on_sync::<lsp_ext::MatchingBrace>(|s, p| {
494 handlers::handle_matching_brace(s.snapshot(), p)
496 .on_sync::<lsp_ext::MemoryUsage>(|s, p| handlers::handle_memory_usage(s, p))?
497 .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)
498 .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)
499 .on::<lsp_ext::ViewHir>(handlers::handle_view_hir)
500 .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)
501 .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)
502 .on::<lsp_ext::Runnables>(handlers::handle_runnables)
503 .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)
504 .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)
505 .on::<lsp_ext::CodeActionResolveRequest>(handlers::handle_code_action_resolve)
506 .on::<lsp_ext::HoverRequest>(handlers::handle_hover)
507 .on::<lsp_ext::ExternalDocs>(handlers::handle_open_docs)
508 .on::<lsp_ext::OpenCargoToml>(handlers::handle_open_cargo_toml)
509 .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)
510 .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)
511 .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)
512 .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)
513 .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)
514 .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)
515 .on::<lsp_types::request::Completion>(handlers::handle_completion)
516 .on::<lsp_types::request::ResolveCompletionItem>(handlers::handle_completion_resolve)
517 .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)
518 .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)
519 .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)
520 .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)
521 .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)
522 .on::<lsp_types::request::Rename>(handlers::handle_rename)
523 .on::<lsp_types::request::References>(handlers::handle_references)
524 .on::<lsp_types::request::Formatting>(handlers::handle_formatting)
525 .on::<lsp_types::request::DocumentHighlightRequest>(handlers::handle_document_highlight)
526 .on::<lsp_types::request::CallHierarchyPrepare>(handlers::handle_call_hierarchy_prepare)
527 .on::<lsp_types::request::CallHierarchyIncomingCalls>(
528 handlers::handle_call_hierarchy_incoming,
530 .on::<lsp_types::request::CallHierarchyOutgoingCalls>(
531 handlers::handle_call_hierarchy_outgoing,
533 .on::<lsp_types::request::SemanticTokensFullRequest>(
534 handlers::handle_semantic_tokens_full,
536 .on::<lsp_types::request::SemanticTokensFullDeltaRequest>(
537 handlers::handle_semantic_tokens_full_delta,
539 .on::<lsp_types::request::SemanticTokensRangeRequest>(
540 handlers::handle_semantic_tokens_range,
542 .on::<lsp_types::request::WillRenameFiles>(handlers::handle_will_rename_files)
543 .on::<lsp_ext::Ssr>(handlers::handle_ssr)
547 fn on_notification(&mut self, not: Notification) -> Result<()> {
548 NotificationDispatcher { not: Some(not), global_state: self }
549 .on::<lsp_types::notification::Cancel>(|this, params| {
550 let id: lsp_server::RequestId = match params.id {
551 lsp_types::NumberOrString::Number(id) => id.into(),
552 lsp_types::NumberOrString::String(id) => id.into(),
557 .on::<lsp_types::notification::DidOpenTextDocument>(|this, params| {
558 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
561 .insert(path.clone(), DocumentData::new(params.text_document.version))
564 log::error!("duplicate DidOpenTextDocument: {}", path)
570 .set_file_contents(path, Some(params.text_document.text.into_bytes()));
572 // If the VFS contents are unchanged, update diagnostics, since `handle_event`
573 // won't see any changes. This avoids missing diagnostics when opening a file.
575 // If the file *was* changed, `handle_event` will already recompute and send
576 // diagnostics. We can't do it here, since the *current* file contents might be
577 // unset in salsa, since the VFS change hasn't been applied to the database yet.
579 this.maybe_update_diagnostics();
584 .on::<lsp_types::notification::DidChangeTextDocument>(|this, params| {
585 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
586 let doc = match this.mem_docs.get_mut(&path) {
589 log::error!("expected DidChangeTextDocument: {}", path);
593 let vfs = &mut this.vfs.write().0;
594 let file_id = vfs.file_id(&path).unwrap();
595 let mut text = String::from_utf8(vfs.file_contents(file_id).to_vec()).unwrap();
596 apply_document_changes(&mut text, params.content_changes);
598 // The version passed in DidChangeTextDocument is the version after all edits are applied
599 // so we should apply it before the vfs is notified.
600 doc.version = params.text_document.version;
602 vfs.set_file_contents(path.clone(), Some(text.into_bytes()));
606 .on::<lsp_types::notification::DidCloseTextDocument>(|this, params| {
607 let mut version = None;
608 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
609 match this.mem_docs.remove(&path) {
610 Some(doc) => version = Some(doc.version),
611 None => log::error!("orphan DidCloseTextDocument: {}", path),
614 this.semantic_tokens_cache.lock().remove(¶ms.text_document.uri);
616 if let Some(path) = path.as_path() {
617 this.loader.handle.invalidate(path.to_path_buf());
621 // Clear the diagnostics for the previously known version of the file.
622 // This prevents stale "cargo check" diagnostics if the file is
623 // closed, "cargo check" is run and then the file is reopened.
624 this.send_notification::<lsp_types::notification::PublishDiagnostics>(
625 lsp_types::PublishDiagnosticsParams {
626 uri: params.text_document.uri,
627 diagnostics: Vec::new(),
633 .on::<lsp_types::notification::DidSaveTextDocument>(|this, params| {
634 for flycheck in &this.flycheck {
637 if let Ok(abs_path) = from_proto::abs_path(¶ms.text_document.uri) {
638 this.maybe_refresh(&[(abs_path, ChangeKind::Modify)]);
642 .on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| {
643 // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
644 // this notification's parameters should be ignored and the actual config queried separately.
645 this.send_request::<lsp_types::request::WorkspaceConfiguration>(
646 lsp_types::ConfigurationParams {
647 items: vec![lsp_types::ConfigurationItem {
649 section: Some("rust-analyzer".to_string()),
653 log::debug!("config update response: '{:?}", resp);
654 let Response { error, result, .. } = resp;
656 match (error, result) {
658 log::error!("failed to fetch the server settings: {:?}", err)
660 (None, Some(mut configs)) => {
661 if let Some(json) = configs.get_mut(0) {
662 // Note that json can be null according to the spec if the client can't
663 // provide a configuration. This is handled in Config::update below.
664 let mut config = Config::clone(&*this.config);
665 config.update(json.take());
666 this.update_configuration(config);
669 (None, None) => log::error!(
670 "received empty server settings response from the client"
678 .on::<lsp_types::notification::DidChangeWatchedFiles>(|this, params| {
679 for change in params.changes {
680 if let Ok(path) = from_proto::abs_path(&change.uri) {
681 this.loader.handle.invalidate(path);
689 fn update_file_notifications_on_threadpool(&mut self) {
690 self.maybe_update_diagnostics();
691 self.task_pool.handle.spawn_with_sender({
692 let snap = self.snapshot();
695 .prime_caches(|progress| {
696 sender.send(Task::PrimeCaches(progress)).unwrap();
698 .unwrap_or_else(|_: Canceled| {
699 // Pretend that we're done, so that the progress bar is removed. Otherwise
700 // the editor may complain about it already existing.
701 sender.send(Task::PrimeCaches(PrimeCachesProgress::Finished)).unwrap()
706 fn maybe_update_diagnostics(&mut self) {
707 let subscriptions = self
710 .map(|path| self.vfs.read().0.file_id(&path).unwrap())
711 .collect::<Vec<_>>();
713 log::trace!("updating notifications for {:?}", subscriptions);
714 if self.config.publish_diagnostics() {
715 let snapshot = self.snapshot();
716 self.task_pool.handle.spawn(move || {
717 let diagnostics = subscriptions
719 .filter_map(|file_id| {
720 handlers::publish_diagnostics(&snapshot, file_id)
722 if !is_canceled(&*err) {
723 log::error!("failed to compute diagnostics: {:?}", err);
728 .map(|diags| (file_id, diags))
730 .collect::<Vec<_>>();
731 Task::Diagnostics(diagnostics)