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();
246 (*self.workspaces).clone().into_iter().map(Ok).collect();
247 self.switch_workspaces(workspaces, Some(collector));
248 (Some(Progress::End), None)
251 if let Some(state) = state {
252 self.report_progress("loading", state, msg, None);
256 // Coalesce multiple task events into one loop turn
257 task = match self.task_pool.receiver.try_recv() {
263 for progress in prime_caches_progress {
264 let (state, message, fraction);
266 PrimeCachesProgress::Started => {
267 state = Progress::Begin;
271 PrimeCachesProgress::StartedOnCrate { on_crate, n_done, n_total } => {
272 state = Progress::Report;
273 message = Some(format!("{}/{} ({})", n_done, n_total, on_crate));
274 fraction = Progress::fraction(n_done, n_total);
276 PrimeCachesProgress::Finished => {
277 state = Progress::End;
283 self.report_progress("indexing", state, message, Some(fraction));
286 Event::Vfs(mut task) => {
287 let _p = profile::span("GlobalState::handle_event/vfs");
290 vfs::loader::Message::Loaded { files } => {
291 let vfs = &mut self.vfs.write().0;
292 for (path, contents) in files {
293 let path = VfsPath::from(path);
294 if !self.mem_docs.contains_key(&path) {
295 vfs.set_file_contents(path, contents);
299 vfs::loader::Message::Progress { n_total, n_done, config_version } => {
300 always!(config_version <= self.vfs_config_version);
302 new_status = Status::Invalid;
304 let state = if n_done == 0 {
305 new_status = Status::Loading;
307 } else if n_done < n_total {
310 assert_eq!(n_done, n_total);
311 new_status = Status::Ready {
312 partial: self.config.run_build_scripts()
313 && self.workspace_build_data.is_none()
314 || config_version < self.vfs_config_version,
318 self.report_progress(
321 Some(format!("{}/{}", n_done, n_total)),
322 Some(Progress::fraction(n_done, n_total)),
327 // Coalesce many VFS event into a single loop turn
328 task = match self.loader.receiver.try_recv() {
334 Event::Flycheck(mut task) => {
335 let _p = profile::span("GlobalState::handle_event/flycheck");
338 flycheck::Message::AddDiagnostic { workspace_root, diagnostic } => {
340 crate::diagnostics::to_proto::map_rust_diagnostic_to_lsp(
341 &self.config.diagnostics_map(),
345 for diag in diagnostics {
346 match url_to_file_id(&self.vfs.read().0, &diag.url) {
347 Ok(file_id) => self.diagnostics.add_check_diagnostic(
354 "File with cargo diagnostic not found in VFS: {}",
362 flycheck::Message::Progress { id, progress } => {
363 let (state, message) = match progress {
364 flycheck::Progress::DidStart => {
365 self.diagnostics.clear_check();
366 (Progress::Begin, None)
368 flycheck::Progress::DidCheckCrate(target) => {
369 (Progress::Report, Some(target))
371 flycheck::Progress::DidCancel => (Progress::End, None),
372 flycheck::Progress::DidFinish(result) => {
373 if let Err(err) = result {
374 log::error!("cargo check failed: {}", err)
376 (Progress::End, None)
380 // When we're running multiple flychecks, we have to include a disambiguator in
381 // the title, or the editor complains. Note that this is a user-facing string.
382 let title = if self.flycheck.len() == 1 {
383 "cargo check".to_string()
385 format!("cargo check (#{})", id + 1)
387 self.report_progress(&title, state, message, None);
390 // Coalesce many flycheck updates into a single loop turn
391 task = match self.flycheck_receiver.try_recv() {
399 let state_changed = self.process_changes();
400 let prev_status = self.status;
401 if prev_status != new_status {
402 self.transition(new_status);
404 let is_ready = matches!(self.status, Status::Ready { .. });
405 if prev_status == Status::Loading && is_ready {
406 for flycheck in &self.flycheck {
411 if is_ready && (state_changed || prev_status == Status::Loading) {
412 self.update_file_notifications_on_threadpool();
414 // Refresh semantic tokens if the client supports it.
415 if self.config.semantic_tokens_refresh() {
416 self.semantic_tokens_cache.lock().clear();
417 self.send_request::<lsp_types::request::SemanticTokensRefesh>((), |_, _| ());
420 // Refresh code lens if the client supports it.
421 if self.config.code_lens_refresh() {
422 self.send_request::<lsp_types::request::CodeLensRefresh>((), |_, _| ());
426 if let Some(diagnostic_changes) = self.diagnostics.take_changes() {
427 for file_id in diagnostic_changes {
428 let url = file_id_to_url(&self.vfs.read().0, file_id);
429 let diagnostics = self.diagnostics.diagnostics_for(file_id).cloned().collect();
430 let version = from_proto::vfs_path(&url)
431 .map(|path| self.mem_docs.get(&path).map(|it| it.version))
432 .unwrap_or_default();
434 self.send_notification::<lsp_types::notification::PublishDiagnostics>(
435 lsp_types::PublishDiagnosticsParams { uri: url, diagnostics, version },
440 self.fetch_workspaces_if_needed();
441 self.fetch_build_data_if_needed();
443 let loop_duration = loop_start.elapsed();
444 if loop_duration > Duration::from_millis(100) {
445 log::warn!("overly long loop turn: {:?}", loop_duration);
446 if env::var("RA_PROFILE").is_ok() {
448 lsp_types::MessageType::Error,
449 format!("overly long loop turn: {:?}", loop_duration),
456 fn on_request(&mut self, request_received: Instant, req: Request) -> Result<()> {
457 self.register_request(&req, request_received);
459 if self.shutdown_requested {
460 self.respond(Response::new_err(
462 lsp_server::ErrorCode::InvalidRequest as i32,
463 "Shutdown already requested.".to_owned(),
469 if self.status == Status::Loading && req.method != "shutdown" {
470 self.respond(lsp_server::Response::new_err(
472 // FIXME: i32 should impl From<ErrorCode> (from() guarantees lossless conversion)
473 lsp_server::ErrorCode::ContentModified as i32,
474 "Rust Analyzer is still loading...".to_owned(),
479 RequestDispatcher { req: Some(req), global_state: self }
480 .on_sync::<lsp_ext::ReloadWorkspace>(|s, ()| Ok(s.fetch_workspaces_request()))?
481 .on_sync::<lsp_ext::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
482 .on_sync::<lsp_ext::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
483 .on_sync::<lsp_types::request::Shutdown>(|s, ()| {
484 s.shutdown_requested = true;
487 .on_sync::<lsp_types::request::SelectionRangeRequest>(|s, p| {
488 handlers::handle_selection_range(s.snapshot(), p)
490 .on_sync::<lsp_ext::MatchingBrace>(|s, p| {
491 handlers::handle_matching_brace(s.snapshot(), p)
493 .on_sync::<lsp_ext::MemoryUsage>(|s, p| handlers::handle_memory_usage(s, p))?
494 .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)
495 .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)
496 .on::<lsp_ext::ViewHir>(handlers::handle_view_hir)
497 .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)
498 .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)
499 .on::<lsp_ext::Runnables>(handlers::handle_runnables)
500 .on::<lsp_ext::RelatedTests>(handlers::handle_related_tests)
501 .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)
502 .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)
503 .on::<lsp_ext::CodeActionResolveRequest>(handlers::handle_code_action_resolve)
504 .on::<lsp_ext::HoverRequest>(handlers::handle_hover)
505 .on::<lsp_ext::ExternalDocs>(handlers::handle_open_docs)
506 .on::<lsp_ext::OpenCargoToml>(handlers::handle_open_cargo_toml)
507 .on::<lsp_ext::MoveItem>(handlers::handle_move_item)
508 .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)
509 .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)
510 .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)
511 .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)
512 .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)
513 .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)
514 .on::<lsp_types::request::Completion>(handlers::handle_completion)
515 .on::<lsp_types::request::ResolveCompletionItem>(handlers::handle_completion_resolve)
516 .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)
517 .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)
518 .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)
519 .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)
520 .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)
521 .on::<lsp_types::request::Rename>(handlers::handle_rename)
522 .on::<lsp_types::request::References>(handlers::handle_references)
523 .on::<lsp_types::request::Formatting>(handlers::handle_formatting)
524 .on::<lsp_types::request::DocumentHighlightRequest>(handlers::handle_document_highlight)
525 .on::<lsp_types::request::CallHierarchyPrepare>(handlers::handle_call_hierarchy_prepare)
526 .on::<lsp_types::request::CallHierarchyIncomingCalls>(
527 handlers::handle_call_hierarchy_incoming,
529 .on::<lsp_types::request::CallHierarchyOutgoingCalls>(
530 handlers::handle_call_hierarchy_outgoing,
532 .on::<lsp_types::request::SemanticTokensFullRequest>(
533 handlers::handle_semantic_tokens_full,
535 .on::<lsp_types::request::SemanticTokensFullDeltaRequest>(
536 handlers::handle_semantic_tokens_full_delta,
538 .on::<lsp_types::request::SemanticTokensRangeRequest>(
539 handlers::handle_semantic_tokens_range,
541 .on::<lsp_types::request::WillRenameFiles>(handlers::handle_will_rename_files)
542 .on::<lsp_ext::Ssr>(handlers::handle_ssr)
546 fn on_notification(&mut self, not: Notification) -> Result<()> {
547 NotificationDispatcher { not: Some(not), global_state: self }
548 .on::<lsp_types::notification::Cancel>(|this, params| {
549 let id: lsp_server::RequestId = match params.id {
550 lsp_types::NumberOrString::Number(id) => id.into(),
551 lsp_types::NumberOrString::String(id) => id.into(),
556 .on::<lsp_types::notification::DidOpenTextDocument>(|this, params| {
557 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
560 .insert(path.clone(), DocumentData::new(params.text_document.version))
563 log::error!("duplicate DidOpenTextDocument: {}", path)
569 .set_file_contents(path, Some(params.text_document.text.into_bytes()));
571 // If the VFS contents are unchanged, update diagnostics, since `handle_event`
572 // won't see any changes. This avoids missing diagnostics when opening a file.
574 // If the file *was* changed, `handle_event` will already recompute and send
575 // diagnostics. We can't do it here, since the *current* file contents might be
576 // unset in salsa, since the VFS change hasn't been applied to the database yet.
578 this.maybe_update_diagnostics();
583 .on::<lsp_types::notification::DidChangeTextDocument>(|this, params| {
584 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
585 let doc = match this.mem_docs.get_mut(&path) {
588 log::error!("expected DidChangeTextDocument: {}", path);
592 let vfs = &mut this.vfs.write().0;
593 let file_id = vfs.file_id(&path).unwrap();
594 let mut text = String::from_utf8(vfs.file_contents(file_id).to_vec()).unwrap();
595 apply_document_changes(&mut text, params.content_changes);
597 // The version passed in DidChangeTextDocument is the version after all edits are applied
598 // so we should apply it before the vfs is notified.
599 doc.version = params.text_document.version;
601 vfs.set_file_contents(path.clone(), Some(text.into_bytes()));
605 .on::<lsp_types::notification::DidCloseTextDocument>(|this, params| {
606 let mut version = None;
607 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
608 match this.mem_docs.remove(&path) {
609 Some(doc) => version = Some(doc.version),
610 None => log::error!("orphan DidCloseTextDocument: {}", path),
613 this.semantic_tokens_cache.lock().remove(¶ms.text_document.uri);
615 if let Some(path) = path.as_path() {
616 this.loader.handle.invalidate(path.to_path_buf());
620 // Clear the diagnostics for the previously known version of the file.
621 // This prevents stale "cargo check" diagnostics if the file is
622 // closed, "cargo check" is run and then the file is reopened.
623 this.send_notification::<lsp_types::notification::PublishDiagnostics>(
624 lsp_types::PublishDiagnosticsParams {
625 uri: params.text_document.uri,
626 diagnostics: Vec::new(),
632 .on::<lsp_types::notification::DidSaveTextDocument>(|this, params| {
633 for flycheck in &this.flycheck {
636 if let Ok(abs_path) = from_proto::abs_path(¶ms.text_document.uri) {
637 this.maybe_refresh(&[(abs_path, ChangeKind::Modify)]);
641 .on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| {
642 // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
643 // this notification's parameters should be ignored and the actual config queried separately.
644 this.send_request::<lsp_types::request::WorkspaceConfiguration>(
645 lsp_types::ConfigurationParams {
646 items: vec![lsp_types::ConfigurationItem {
648 section: Some("rust-analyzer".to_string()),
652 log::debug!("config update response: '{:?}", resp);
653 let Response { error, result, .. } = resp;
655 match (error, result) {
657 log::error!("failed to fetch the server settings: {:?}", err)
659 (None, Some(mut configs)) => {
660 if let Some(json) = configs.get_mut(0) {
661 // Note that json can be null according to the spec if the client can't
662 // provide a configuration. This is handled in Config::update below.
663 let mut config = Config::clone(&*this.config);
664 config.update(json.take());
665 this.update_configuration(config);
668 (None, None) => log::error!(
669 "received empty server settings response from the client"
677 .on::<lsp_types::notification::DidChangeWatchedFiles>(|this, params| {
678 for change in params.changes {
679 if let Ok(path) = from_proto::abs_path(&change.uri) {
680 this.loader.handle.invalidate(path);
688 fn update_file_notifications_on_threadpool(&mut self) {
689 self.maybe_update_diagnostics();
690 self.task_pool.handle.spawn_with_sender({
691 let snap = self.snapshot();
694 .prime_caches(|progress| {
695 sender.send(Task::PrimeCaches(progress)).unwrap();
697 .unwrap_or_else(|_: Canceled| {
698 // Pretend that we're done, so that the progress bar is removed. Otherwise
699 // the editor may complain about it already existing.
700 sender.send(Task::PrimeCaches(PrimeCachesProgress::Finished)).unwrap()
705 fn maybe_update_diagnostics(&mut self) {
706 let subscriptions = self
709 .map(|path| self.vfs.read().0.file_id(&path).unwrap())
710 .collect::<Vec<_>>();
712 log::trace!("updating notifications for {:?}", subscriptions);
713 if self.config.publish_diagnostics() {
714 let snapshot = self.snapshot();
715 self.task_pool.handle.spawn(move || {
716 let diagnostics = subscriptions
718 .filter_map(|file_id| {
719 handlers::publish_diagnostics(&snapshot, file_id)
721 if !is_canceled(&*err) {
722 log::error!("failed to compute diagnostics: {:?}", err);
727 .map(|diags| (file_id, diags))
729 .collect::<Vec<_>>();
730 Task::Diagnostics(diagnostics)