1 //! The main loop of `rust-analyzer` responsible for dispatching LSP
2 //! requests/replies and notifications back to the client.
6 time::{Duration, Instant},
9 use always_assert::always;
10 use crossbeam_channel::{select, Receiver};
11 use ide::PrimeCachesProgress;
12 use ide::{Canceled, FileId};
13 use ide_db::base_db::VfsPath;
14 use lsp_server::{Connection, Notification, Request, Response};
15 use lsp_types::notification::Notification as _;
16 use project_model::BuildDataCollector;
21 dispatch::{NotificationDispatcher, RequestDispatcher},
22 document::DocumentData,
24 global_state::{file_id_to_url, url_to_file_id, GlobalState},
26 lsp_utils::{apply_document_changes, is_canceled, notification_is, Progress},
27 reload::{BuildDataProgress, ProjectWorkspaceProgress},
31 pub fn main_loop(config: Config, connection: Connection) -> Result<()> {
32 log::info!("initial config: {:#?}", config);
34 // Windows scheduler implements priority boosts: if thread waits for an
35 // event (like a condvar), and event fires, priority of the thread is
36 // temporary bumped. This optimization backfires in our case: each time the
37 // `main_loop` schedules a task to run on a threadpool, the worker threads
38 // gets a higher priority, and (on a machine with fewer cores) displaces the
39 // main loop! We work-around this by marking the main loop as a
40 // higher-priority thread.
42 // https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities
43 // https://docs.microsoft.com/en-us/windows/win32/procthread/priority-boosts
44 // https://github.com/rust-analyzer/rust-analyzer/issues/2835
47 use winapi::um::processthreadsapi::*;
48 let thread = GetCurrentThread();
49 let thread_priority_above_normal = 1;
50 SetThreadPriority(thread, thread_priority_above_normal);
53 GlobalState::new(connection.sender, config).run(connection.receiver)
57 Lsp(lsp_server::Message),
59 Vfs(vfs::loader::Message),
60 Flycheck(flycheck::Message),
64 pub(crate) enum Task {
66 Diagnostics(Vec<(FileId, Vec<lsp_types::Diagnostic>)>),
67 PrimeCaches(PrimeCachesProgress),
68 FetchWorkspace(ProjectWorkspaceProgress),
69 FetchBuildData(BuildDataProgress),
72 impl fmt::Debug for Event {
73 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
74 let debug_verbose_not = |not: &Notification, f: &mut fmt::Formatter| {
75 f.debug_struct("Notification").field("method", ¬.method).finish()
79 Event::Lsp(lsp_server::Message::Notification(not)) => {
80 if notification_is::<lsp_types::notification::DidOpenTextDocument>(not)
81 || notification_is::<lsp_types::notification::DidChangeTextDocument>(not)
83 return debug_verbose_not(not, f);
86 Event::Task(Task::Response(resp)) => {
88 .debug_struct("Response")
89 .field("id", &resp.id)
90 .field("error", &resp.error)
96 Event::Lsp(it) => fmt::Debug::fmt(it, f),
97 Event::Task(it) => fmt::Debug::fmt(it, f),
98 Event::Vfs(it) => fmt::Debug::fmt(it, f),
99 Event::Flycheck(it) => fmt::Debug::fmt(it, f),
105 fn run(mut self, inbox: Receiver<lsp_server::Message>) -> Result<()> {
106 if self.config.linked_projects().is_empty()
107 && self.config.notifications().cargo_toml_not_found
110 lsp_types::MessageType::Error,
111 "rust-analyzer failed to discover workspace".to_string(),
115 if self.config.did_save_text_document_dynamic_registration() {
116 let save_registration_options = lsp_types::TextDocumentSaveRegistrationOptions {
117 include_text: Some(false),
118 text_document_registration_options: lsp_types::TextDocumentRegistrationOptions {
119 document_selector: Some(vec![
120 lsp_types::DocumentFilter {
123 pattern: Some("**/*.rs".into()),
125 lsp_types::DocumentFilter {
128 pattern: Some("**/Cargo.toml".into()),
130 lsp_types::DocumentFilter {
133 pattern: Some("**/Cargo.lock".into()),
139 let registration = lsp_types::Registration {
140 id: "textDocument/didSave".to_string(),
141 method: "textDocument/didSave".to_string(),
142 register_options: Some(serde_json::to_value(save_registration_options).unwrap()),
144 self.send_request::<lsp_types::request::RegisterCapability>(
145 lsp_types::RegistrationParams { registrations: vec![registration] },
150 self.fetch_workspaces_request();
151 self.fetch_workspaces_if_needed();
153 while let Some(event) = self.next_event(&inbox) {
154 if let Event::Lsp(lsp_server::Message::Notification(not)) = &event {
155 if not.method == lsp_types::notification::Exit::METHOD {
159 self.handle_event(event)?
162 Err("client exited without proper shutdown sequence")?
165 fn next_event(&self, inbox: &Receiver<lsp_server::Message>) -> Option<Event> {
167 recv(inbox) -> msg =>
168 msg.ok().map(Event::Lsp),
170 recv(self.task_pool.receiver) -> task =>
171 Some(Event::Task(task.unwrap())),
173 recv(self.loader.receiver) -> task =>
174 Some(Event::Vfs(task.unwrap())),
176 recv(self.flycheck_receiver) -> task =>
177 Some(Event::Flycheck(task.unwrap())),
181 fn handle_event(&mut self, event: Event) -> Result<()> {
182 let loop_start = Instant::now();
183 // NOTE: don't count blocking select! call as a loop-turn time
184 let _p = profile::span("GlobalState::handle_event");
186 log::info!("handle_event({:?})", event);
187 let task_queue_len = self.task_pool.handle.len();
188 if task_queue_len > 0 {
189 log::info!("task queue len: {}", task_queue_len);
192 let was_quiescent = self.is_quiescent();
194 Event::Lsp(msg) => match msg {
195 lsp_server::Message::Request(req) => self.on_request(loop_start, req)?,
196 lsp_server::Message::Notification(not) => {
197 self.on_notification(not)?;
199 lsp_server::Message::Response(resp) => self.complete_request(resp),
201 Event::Task(mut task) => {
202 let _p = profile::span("GlobalState::handle_event/task");
203 let mut prime_caches_progress = Vec::new();
206 Task::Response(response) => self.respond(response),
207 Task::Diagnostics(diagnostics_per_file) => {
208 for (file_id, diagnostics) in diagnostics_per_file {
209 self.diagnostics.set_native_diagnostics(file_id, diagnostics)
212 Task::PrimeCaches(progress) => match progress {
213 PrimeCachesProgress::Started => prime_caches_progress.push(progress),
214 PrimeCachesProgress::StartedOnCrate { .. } => {
215 match prime_caches_progress.last_mut() {
216 Some(last @ PrimeCachesProgress::StartedOnCrate { .. }) => {
217 // Coalesce subsequent update events.
220 _ => prime_caches_progress.push(progress),
223 PrimeCachesProgress::Finished => prime_caches_progress.push(progress),
225 Task::FetchWorkspace(progress) => {
226 let (state, msg) = match progress {
227 ProjectWorkspaceProgress::Begin => (Progress::Begin, None),
228 ProjectWorkspaceProgress::Report(msg) => {
229 (Progress::Report, Some(msg))
231 ProjectWorkspaceProgress::End(workspaces) => {
232 self.fetch_workspaces_completed(workspaces);
234 let old = Arc::clone(&self.workspaces);
235 self.switch_workspaces();
236 let workspaces_updated = !Arc::ptr_eq(&old, &self.workspaces);
238 if self.config.run_build_scripts() && workspaces_updated {
240 BuildDataCollector::new(self.config.wrap_rustc());
241 for ws in self.workspaces.iter() {
242 ws.collect_build_data_configs(&mut collector);
244 self.fetch_build_data_request(collector)
247 (Progress::End, None)
251 self.report_progress("fetching", state, msg, None);
253 Task::FetchBuildData(progress) => {
254 let (state, msg) = match progress {
255 BuildDataProgress::Begin => (Some(Progress::Begin), None),
256 BuildDataProgress::Report(msg) => {
257 (Some(Progress::Report), Some(msg))
259 BuildDataProgress::End(build_data_result) => {
260 self.fetch_build_data_completed(build_data_result);
262 self.switch_workspaces();
264 (Some(Progress::End), None)
268 if let Some(state) = state {
269 self.report_progress("loading", state, msg, None);
274 // Coalesce multiple task events into one loop turn
275 task = match self.task_pool.receiver.try_recv() {
281 for progress in prime_caches_progress {
282 let (state, message, fraction);
284 PrimeCachesProgress::Started => {
285 state = Progress::Begin;
289 PrimeCachesProgress::StartedOnCrate { on_crate, n_done, n_total } => {
290 state = Progress::Report;
291 message = Some(format!("{}/{} ({})", n_done, n_total, on_crate));
292 fraction = Progress::fraction(n_done, n_total);
294 PrimeCachesProgress::Finished => {
295 state = Progress::End;
301 self.report_progress("indexing", state, message, Some(fraction));
304 Event::Vfs(mut task) => {
305 let _p = profile::span("GlobalState::handle_event/vfs");
308 vfs::loader::Message::Loaded { files } => {
309 let vfs = &mut self.vfs.write().0;
310 for (path, contents) in files {
311 let path = VfsPath::from(path);
312 if !self.mem_docs.contains_key(&path) {
313 vfs.set_file_contents(path, contents);
317 vfs::loader::Message::Progress { n_total, n_done, config_version } => {
318 always!(config_version <= self.vfs_config_version);
320 self.vfs_progress_config_version = config_version;
321 self.vfs_progress_n_total = n_total;
322 self.vfs_progress_n_done = n_done;
324 let state = if n_done == 0 {
326 } else if n_done < n_total {
329 assert_eq!(n_done, n_total);
332 self.report_progress(
335 Some(format!("{}/{}", n_done, n_total)),
336 Some(Progress::fraction(n_done, n_total)),
340 // Coalesce many VFS event into a single loop turn
341 task = match self.loader.receiver.try_recv() {
347 Event::Flycheck(mut task) => {
348 let _p = profile::span("GlobalState::handle_event/flycheck");
351 flycheck::Message::AddDiagnostic { workspace_root, diagnostic } => {
353 crate::diagnostics::to_proto::map_rust_diagnostic_to_lsp(
354 &self.config.diagnostics_map(),
358 for diag in diagnostics {
359 match url_to_file_id(&self.vfs.read().0, &diag.url) {
360 Ok(file_id) => self.diagnostics.add_check_diagnostic(
367 "File with cargo diagnostic not found in VFS: {}",
375 flycheck::Message::Progress { id, progress } => {
376 let (state, message) = match progress {
377 flycheck::Progress::DidStart => {
378 self.diagnostics.clear_check();
379 (Progress::Begin, None)
381 flycheck::Progress::DidCheckCrate(target) => {
382 (Progress::Report, Some(target))
384 flycheck::Progress::DidCancel => (Progress::End, None),
385 flycheck::Progress::DidFinish(result) => {
386 if let Err(err) = result {
387 log::error!("cargo check failed: {}", err)
389 (Progress::End, None)
393 // When we're running multiple flychecks, we have to include a disambiguator in
394 // the title, or the editor complains. Note that this is a user-facing string.
395 let title = if self.flycheck.len() == 1 {
396 "cargo check".to_string()
398 format!("cargo check (#{})", id + 1)
400 self.report_progress(&title, state, message, None);
403 // Coalesce many flycheck updates into a single loop turn
404 task = match self.flycheck_receiver.try_recv() {
412 let state_changed = self.process_changes();
414 if self.is_quiescent() && !was_quiescent {
415 for flycheck in &self.flycheck {
420 if self.is_quiescent() && (!was_quiescent || state_changed) {
421 self.update_file_notifications_on_threadpool();
423 // Refresh semantic tokens if the client supports it.
424 if self.config.semantic_tokens_refresh() {
425 self.semantic_tokens_cache.lock().clear();
426 self.send_request::<lsp_types::request::SemanticTokensRefesh>((), |_, _| ());
429 // Refresh code lens if the client supports it.
430 if self.config.code_lens_refresh() {
431 self.send_request::<lsp_types::request::CodeLensRefresh>((), |_, _| ());
435 if let Some(diagnostic_changes) = self.diagnostics.take_changes() {
436 for file_id in diagnostic_changes {
437 let url = file_id_to_url(&self.vfs.read().0, file_id);
438 let diagnostics = self.diagnostics.diagnostics_for(file_id).cloned().collect();
439 let version = from_proto::vfs_path(&url)
440 .map(|path| self.mem_docs.get(&path).map(|it| it.version))
441 .unwrap_or_default();
443 self.send_notification::<lsp_types::notification::PublishDiagnostics>(
444 lsp_types::PublishDiagnosticsParams { uri: url, diagnostics, version },
449 if self.config.cargo_autoreload() {
450 self.fetch_workspaces_if_needed();
452 self.fetch_build_data_if_needed();
454 self.report_new_status_if_needed();
456 let loop_duration = loop_start.elapsed();
457 if loop_duration > Duration::from_millis(100) {
458 log::warn!("overly long loop turn: {:?}", loop_duration);
459 if env::var("RA_PROFILE").is_ok() {
461 lsp_types::MessageType::Error,
462 format!("overly long loop turn: {:?}", loop_duration),
469 fn on_request(&mut self, request_received: Instant, req: Request) -> Result<()> {
470 self.register_request(&req, request_received);
472 if self.shutdown_requested {
473 self.respond(Response::new_err(
475 lsp_server::ErrorCode::InvalidRequest as i32,
476 "Shutdown already requested.".to_owned(),
482 // Avoid flashing a bunch of unresolved references during initial load.
483 if self.workspaces.is_empty() && !self.is_quiescent() {
484 self.respond(lsp_server::Response::new_err(
486 // FIXME: i32 should impl From<ErrorCode> (from() guarantees lossless conversion)
487 lsp_server::ErrorCode::ContentModified as i32,
488 "waiting for cargo metadata or cargo check".to_owned(),
493 RequestDispatcher { req: Some(req), global_state: self }
494 .on_sync::<lsp_ext::ReloadWorkspace>(|s, ()| {
495 s.fetch_workspaces_request();
496 s.fetch_workspaces_if_needed();
499 .on_sync::<lsp_ext::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
500 .on_sync::<lsp_ext::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
501 .on_sync::<lsp_types::request::Shutdown>(|s, ()| {
502 s.shutdown_requested = true;
505 .on_sync::<lsp_types::request::SelectionRangeRequest>(|s, p| {
506 handlers::handle_selection_range(s.snapshot(), p)
508 .on_sync::<lsp_ext::MatchingBrace>(|s, p| {
509 handlers::handle_matching_brace(s.snapshot(), p)
511 .on_sync::<lsp_ext::MemoryUsage>(|s, p| handlers::handle_memory_usage(s, p))?
512 .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)
513 .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)
514 .on::<lsp_ext::ViewHir>(handlers::handle_view_hir)
515 .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)
516 .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)
517 .on::<lsp_ext::Runnables>(handlers::handle_runnables)
518 .on::<lsp_ext::RelatedTests>(handlers::handle_related_tests)
519 .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)
520 .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)
521 .on::<lsp_ext::CodeActionResolveRequest>(handlers::handle_code_action_resolve)
522 .on::<lsp_ext::HoverRequest>(handlers::handle_hover)
523 .on::<lsp_ext::ExternalDocs>(handlers::handle_open_docs)
524 .on::<lsp_ext::OpenCargoToml>(handlers::handle_open_cargo_toml)
525 .on::<lsp_ext::MoveItem>(handlers::handle_move_item)
526 .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)
527 .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)
528 .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)
529 .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)
530 .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)
531 .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)
532 .on::<lsp_types::request::Completion>(handlers::handle_completion)
533 .on::<lsp_types::request::ResolveCompletionItem>(handlers::handle_completion_resolve)
534 .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)
535 .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)
536 .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)
537 .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)
538 .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)
539 .on::<lsp_types::request::Rename>(handlers::handle_rename)
540 .on::<lsp_types::request::References>(handlers::handle_references)
541 .on::<lsp_types::request::Formatting>(handlers::handle_formatting)
542 .on::<lsp_types::request::DocumentHighlightRequest>(handlers::handle_document_highlight)
543 .on::<lsp_types::request::CallHierarchyPrepare>(handlers::handle_call_hierarchy_prepare)
544 .on::<lsp_types::request::CallHierarchyIncomingCalls>(
545 handlers::handle_call_hierarchy_incoming,
547 .on::<lsp_types::request::CallHierarchyOutgoingCalls>(
548 handlers::handle_call_hierarchy_outgoing,
550 .on::<lsp_types::request::SemanticTokensFullRequest>(
551 handlers::handle_semantic_tokens_full,
553 .on::<lsp_types::request::SemanticTokensFullDeltaRequest>(
554 handlers::handle_semantic_tokens_full_delta,
556 .on::<lsp_types::request::SemanticTokensRangeRequest>(
557 handlers::handle_semantic_tokens_range,
559 .on::<lsp_types::request::WillRenameFiles>(handlers::handle_will_rename_files)
560 .on::<lsp_ext::Ssr>(handlers::handle_ssr)
564 fn on_notification(&mut self, not: Notification) -> Result<()> {
565 NotificationDispatcher { not: Some(not), global_state: self }
566 .on::<lsp_types::notification::Cancel>(|this, params| {
567 let id: lsp_server::RequestId = match params.id {
568 lsp_types::NumberOrString::Number(id) => id.into(),
569 lsp_types::NumberOrString::String(id) => id.into(),
574 .on::<lsp_types::notification::DidOpenTextDocument>(|this, params| {
575 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
578 .insert(path.clone(), DocumentData::new(params.text_document.version))
581 log::error!("duplicate DidOpenTextDocument: {}", path)
587 .set_file_contents(path, Some(params.text_document.text.into_bytes()));
589 // If the VFS contents are unchanged, update diagnostics, since `handle_event`
590 // won't see any changes. This avoids missing diagnostics when opening a file.
592 // If the file *was* changed, `handle_event` will already recompute and send
593 // diagnostics. We can't do it here, since the *current* file contents might be
594 // unset in salsa, since the VFS change hasn't been applied to the database yet.
596 this.maybe_update_diagnostics();
601 .on::<lsp_types::notification::DidChangeTextDocument>(|this, params| {
602 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
603 let doc = match this.mem_docs.get_mut(&path) {
606 log::error!("expected DidChangeTextDocument: {}", path);
610 let vfs = &mut this.vfs.write().0;
611 let file_id = vfs.file_id(&path).unwrap();
612 let mut text = String::from_utf8(vfs.file_contents(file_id).to_vec()).unwrap();
613 apply_document_changes(&mut text, params.content_changes);
615 // The version passed in DidChangeTextDocument is the version after all edits are applied
616 // so we should apply it before the vfs is notified.
617 doc.version = params.text_document.version;
619 vfs.set_file_contents(path.clone(), Some(text.into_bytes()));
623 .on::<lsp_types::notification::DidCloseTextDocument>(|this, params| {
624 let mut version = None;
625 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
626 match this.mem_docs.remove(&path) {
627 Some(doc) => version = Some(doc.version),
628 None => log::error!("orphan DidCloseTextDocument: {}", path),
631 this.semantic_tokens_cache.lock().remove(¶ms.text_document.uri);
633 if let Some(path) = path.as_path() {
634 this.loader.handle.invalidate(path.to_path_buf());
638 // Clear the diagnostics for the previously known version of the file.
639 // This prevents stale "cargo check" diagnostics if the file is
640 // closed, "cargo check" is run and then the file is reopened.
641 this.send_notification::<lsp_types::notification::PublishDiagnostics>(
642 lsp_types::PublishDiagnosticsParams {
643 uri: params.text_document.uri,
644 diagnostics: Vec::new(),
650 .on::<lsp_types::notification::DidSaveTextDocument>(|this, params| {
651 for flycheck in &this.flycheck {
654 if let Ok(abs_path) = from_proto::abs_path(¶ms.text_document.uri) {
655 this.maybe_refresh(&[(abs_path, ChangeKind::Modify)]);
659 .on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| {
660 // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
661 // this notification's parameters should be ignored and the actual config queried separately.
662 this.send_request::<lsp_types::request::WorkspaceConfiguration>(
663 lsp_types::ConfigurationParams {
664 items: vec![lsp_types::ConfigurationItem {
666 section: Some("rust-analyzer".to_string()),
670 log::debug!("config update response: '{:?}", resp);
671 let Response { error, result, .. } = resp;
673 match (error, result) {
675 log::error!("failed to fetch the server settings: {:?}", err)
677 (None, Some(mut configs)) => {
678 if let Some(json) = configs.get_mut(0) {
679 // Note that json can be null according to the spec if the client can't
680 // provide a configuration. This is handled in Config::update below.
681 let mut config = Config::clone(&*this.config);
682 config.update(json.take());
683 this.update_configuration(config);
686 (None, None) => log::error!(
687 "received empty server settings response from the client"
695 .on::<lsp_types::notification::DidChangeWatchedFiles>(|this, params| {
696 for change in params.changes {
697 if let Ok(path) = from_proto::abs_path(&change.uri) {
698 this.loader.handle.invalidate(path);
706 fn update_file_notifications_on_threadpool(&mut self) {
707 self.maybe_update_diagnostics();
708 self.task_pool.handle.spawn_with_sender({
709 let snap = self.snapshot();
712 .prime_caches(|progress| {
713 sender.send(Task::PrimeCaches(progress)).unwrap();
715 .unwrap_or_else(|_: Canceled| {
716 // Pretend that we're done, so that the progress bar is removed. Otherwise
717 // the editor may complain about it already existing.
718 sender.send(Task::PrimeCaches(PrimeCachesProgress::Finished)).unwrap()
723 fn maybe_update_diagnostics(&mut self) {
724 let subscriptions = self
727 .map(|path| self.vfs.read().0.file_id(&path).unwrap())
728 .collect::<Vec<_>>();
730 log::trace!("updating notifications for {:?}", subscriptions);
731 if self.config.publish_diagnostics() {
732 let snapshot = self.snapshot();
733 self.task_pool.handle.spawn(move || {
734 let diagnostics = subscriptions
736 .filter_map(|file_id| {
737 handlers::publish_diagnostics(&snapshot, file_id)
739 if !is_canceled(&*err) {
740 log::error!("failed to compute diagnostics: {:?}", err);
745 .map(|diags| (file_id, diags))
747 .collect::<Vec<_>>();
748 Task::Diagnostics(diagnostics)