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::{FileId, PrimeCachesProgress};
12 use ide_db::base_db::VfsPath;
13 use lsp_server::{Connection, Notification, Request, Response};
14 use lsp_types::notification::Notification as _;
15 use project_model::BuildDataCollector;
20 dispatch::{NotificationDispatcher, RequestDispatcher},
21 document::DocumentData,
23 global_state::{file_id_to_url, url_to_file_id, GlobalState},
25 lsp_utils::{apply_document_changes, is_canceled, notification_is, Progress},
26 reload::{BuildDataProgress, ProjectWorkspaceProgress},
30 pub fn main_loop(config: Config, connection: Connection) -> Result<()> {
31 log::info!("initial config: {:#?}", config);
33 // Windows scheduler implements priority boosts: if thread waits for an
34 // event (like a condvar), and event fires, priority of the thread is
35 // temporary bumped. This optimization backfires in our case: each time the
36 // `main_loop` schedules a task to run on a threadpool, the worker threads
37 // gets a higher priority, and (on a machine with fewer cores) displaces the
38 // main loop! We work-around this by marking the main loop as a
39 // higher-priority thread.
41 // https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities
42 // https://docs.microsoft.com/en-us/windows/win32/procthread/priority-boosts
43 // https://github.com/rust-analyzer/rust-analyzer/issues/2835
46 use winapi::um::processthreadsapi::*;
47 let thread = GetCurrentThread();
48 let thread_priority_above_normal = 1;
49 SetThreadPriority(thread, thread_priority_above_normal);
52 GlobalState::new(connection.sender, config).run(connection.receiver)
56 Lsp(lsp_server::Message),
58 Vfs(vfs::loader::Message),
59 Flycheck(flycheck::Message),
63 pub(crate) enum Task {
65 Diagnostics(Vec<(FileId, Vec<lsp_types::Diagnostic>)>),
66 PrimeCaches(PrimeCachesProgress),
67 FetchWorkspace(ProjectWorkspaceProgress),
68 FetchBuildData(BuildDataProgress),
71 impl fmt::Debug for Event {
72 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
73 let debug_verbose_not = |not: &Notification, f: &mut fmt::Formatter| {
74 f.debug_struct("Notification").field("method", ¬.method).finish()
78 Event::Lsp(lsp_server::Message::Notification(not)) => {
79 if notification_is::<lsp_types::notification::DidOpenTextDocument>(not)
80 || notification_is::<lsp_types::notification::DidChangeTextDocument>(not)
82 return debug_verbose_not(not, f);
85 Event::Task(Task::Response(resp)) => {
87 .debug_struct("Response")
88 .field("id", &resp.id)
89 .field("error", &resp.error)
95 Event::Lsp(it) => fmt::Debug::fmt(it, f),
96 Event::Task(it) => fmt::Debug::fmt(it, f),
97 Event::Vfs(it) => fmt::Debug::fmt(it, f),
98 Event::Flycheck(it) => fmt::Debug::fmt(it, f),
104 fn run(mut self, inbox: Receiver<lsp_server::Message>) -> Result<()> {
105 if self.config.linked_projects().is_empty()
106 && self.config.notifications().cargo_toml_not_found
109 lsp_types::MessageType::Error,
110 "rust-analyzer failed to discover workspace".to_string(),
114 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 {
122 pattern: Some("**/*.rs".into()),
124 lsp_types::DocumentFilter {
127 pattern: Some("**/Cargo.toml".into()),
129 lsp_types::DocumentFilter {
132 pattern: Some("**/Cargo.lock".into()),
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()),
143 self.send_request::<lsp_types::request::RegisterCapability>(
144 lsp_types::RegistrationParams { registrations: vec![registration] },
149 self.fetch_workspaces_request();
150 self.fetch_workspaces_if_needed();
152 while let Some(event) = self.next_event(&inbox) {
153 if let Event::Lsp(lsp_server::Message::Notification(not)) = &event {
154 if not.method == lsp_types::notification::Exit::METHOD {
158 self.handle_event(event)?
161 Err("client exited without proper shutdown sequence")?
164 fn next_event(&self, inbox: &Receiver<lsp_server::Message>) -> Option<Event> {
166 recv(inbox) -> msg =>
167 msg.ok().map(Event::Lsp),
169 recv(self.task_pool.receiver) -> task =>
170 Some(Event::Task(task.unwrap())),
172 recv(self.loader.receiver) -> task =>
173 Some(Event::Vfs(task.unwrap())),
175 recv(self.flycheck_receiver) -> task =>
176 Some(Event::Flycheck(task.unwrap())),
180 fn handle_event(&mut self, event: Event) -> Result<()> {
181 let loop_start = Instant::now();
182 // NOTE: don't count blocking select! call as a loop-turn time
183 let _p = profile::span("GlobalState::handle_event");
185 log::info!("handle_event({:?})", event);
186 let task_queue_len = self.task_pool.handle.len();
187 if task_queue_len > 0 {
188 log::info!("task queue len: {}", task_queue_len);
191 let was_quiescent = self.is_quiescent();
193 Event::Lsp(msg) => match msg {
194 lsp_server::Message::Request(req) => self.on_request(loop_start, req)?,
195 lsp_server::Message::Notification(not) => {
196 self.on_notification(not)?;
198 lsp_server::Message::Response(resp) => self.complete_request(resp),
200 Event::Task(mut task) => {
201 let _p = profile::span("GlobalState::handle_event/task");
202 let mut prime_caches_progress = Vec::new();
205 Task::Response(response) => self.respond(response),
206 Task::Diagnostics(diagnostics_per_file) => {
207 for (file_id, diagnostics) in diagnostics_per_file {
208 self.diagnostics.set_native_diagnostics(file_id, diagnostics)
211 Task::PrimeCaches(progress) => match progress {
212 PrimeCachesProgress::Started => prime_caches_progress.push(progress),
213 PrimeCachesProgress::StartedOnCrate { .. } => {
214 match prime_caches_progress.last_mut() {
215 Some(last @ PrimeCachesProgress::StartedOnCrate { .. }) => {
216 // Coalesce subsequent update events.
219 _ => prime_caches_progress.push(progress),
222 PrimeCachesProgress::Finished => prime_caches_progress.push(progress),
224 Task::FetchWorkspace(progress) => {
225 let (state, msg) = match progress {
226 ProjectWorkspaceProgress::Begin => (Progress::Begin, None),
227 ProjectWorkspaceProgress::Report(msg) => {
228 (Progress::Report, Some(msg))
230 ProjectWorkspaceProgress::End(workspaces) => {
231 self.fetch_workspaces_completed(workspaces);
233 let old = Arc::clone(&self.workspaces);
234 self.switch_workspaces();
235 let workspaces_updated = !Arc::ptr_eq(&old, &self.workspaces);
237 if self.config.run_build_scripts() && workspaces_updated {
239 BuildDataCollector::new(self.config.wrap_rustc());
240 for ws in self.workspaces.iter() {
241 ws.collect_build_data_configs(&mut collector);
243 self.fetch_build_data_request(collector)
246 (Progress::End, None)
250 self.report_progress("Fetching", state, msg, None);
252 Task::FetchBuildData(progress) => {
253 let (state, msg) = match progress {
254 BuildDataProgress::Begin => (Some(Progress::Begin), None),
255 BuildDataProgress::Report(msg) => {
256 (Some(Progress::Report), Some(msg))
258 BuildDataProgress::End(build_data_result) => {
259 self.fetch_build_data_completed(build_data_result);
261 self.switch_workspaces();
263 (Some(Progress::End), None)
267 if let Some(state) = state {
268 self.report_progress("Loading", state, msg, None);
273 // Coalesce multiple task events into one loop turn
274 task = match self.task_pool.receiver.try_recv() {
280 for progress in prime_caches_progress {
281 let (state, message, fraction);
283 PrimeCachesProgress::Started => {
284 state = Progress::Begin;
288 PrimeCachesProgress::StartedOnCrate { on_crate, n_done, n_total } => {
289 state = Progress::Report;
290 message = Some(format!("{}/{} ({})", n_done, n_total, on_crate));
291 fraction = Progress::fraction(n_done, n_total);
293 PrimeCachesProgress::Finished => {
294 state = Progress::End;
298 self.prime_caches_queue.op_completed(());
302 self.report_progress("Indexing", state, message, Some(fraction));
305 Event::Vfs(mut task) => {
306 let _p = profile::span("GlobalState::handle_event/vfs");
309 vfs::loader::Message::Loaded { files } => {
310 let vfs = &mut self.vfs.write().0;
311 for (path, contents) in files {
312 let path = VfsPath::from(path);
313 if !self.mem_docs.contains_key(&path) {
314 vfs.set_file_contents(path, contents);
318 vfs::loader::Message::Progress { n_total, n_done, config_version } => {
319 always!(config_version <= self.vfs_config_version);
321 self.vfs_progress_config_version = config_version;
322 self.vfs_progress_n_total = n_total;
323 self.vfs_progress_n_done = n_done;
325 let state = if n_done == 0 {
327 } else if n_done < n_total {
330 assert_eq!(n_done, n_total);
333 self.report_progress(
336 Some(format!("{}/{}", n_done, n_total)),
337 Some(Progress::fraction(n_done, n_total)),
341 // Coalesce many VFS event into a single loop turn
342 task = match self.loader.receiver.try_recv() {
348 Event::Flycheck(mut task) => {
349 let _p = profile::span("GlobalState::handle_event/flycheck");
352 flycheck::Message::AddDiagnostic { workspace_root, diagnostic } => {
354 crate::diagnostics::to_proto::map_rust_diagnostic_to_lsp(
355 &self.config.diagnostics_map(),
359 for diag in diagnostics {
360 match url_to_file_id(&self.vfs.read().0, &diag.url) {
361 Ok(file_id) => self.diagnostics.add_check_diagnostic(
368 "File with cargo diagnostic not found in VFS: {}",
376 flycheck::Message::Progress { id, progress } => {
377 let (state, message) = match progress {
378 flycheck::Progress::DidStart => {
379 self.diagnostics.clear_check();
380 (Progress::Begin, None)
382 flycheck::Progress::DidCheckCrate(target) => {
383 (Progress::Report, Some(target))
385 flycheck::Progress::DidCancel => (Progress::End, None),
386 flycheck::Progress::DidFinish(result) => {
387 if let Err(err) = result {
388 log::error!("cargo check failed: {}", err)
390 (Progress::End, None)
394 // When we're running multiple flychecks, we have to include a disambiguator in
395 // the title, or the editor complains. Note that this is a user-facing string.
396 let title = if self.flycheck.len() == 1 {
397 "cargo check".to_string()
399 format!("cargo check (#{})", id + 1)
401 self.report_progress(&title, state, message, None);
404 // Coalesce many flycheck updates into a single loop turn
405 task = match self.flycheck_receiver.try_recv() {
413 let state_changed = self.process_changes();
415 if self.is_quiescent() && !was_quiescent {
416 for flycheck in &self.flycheck {
421 if self.is_quiescent() && (!was_quiescent || state_changed) {
422 self.update_file_notifications_on_threadpool();
424 // Refresh semantic tokens if the client supports it.
425 if self.config.semantic_tokens_refresh() {
426 self.semantic_tokens_cache.lock().clear();
427 self.send_request::<lsp_types::request::SemanticTokensRefesh>((), |_, _| ());
430 // Refresh code lens if the client supports it.
431 if self.config.code_lens_refresh() {
432 self.send_request::<lsp_types::request::CodeLensRefresh>((), |_, _| ());
436 if let Some(diagnostic_changes) = self.diagnostics.take_changes() {
437 for file_id in diagnostic_changes {
438 let url = file_id_to_url(&self.vfs.read().0, file_id);
439 let diagnostics = self.diagnostics.diagnostics_for(file_id).cloned().collect();
440 let version = from_proto::vfs_path(&url)
441 .map(|path| self.mem_docs.get(&path).map(|it| it.version))
442 .unwrap_or_default();
444 self.send_notification::<lsp_types::notification::PublishDiagnostics>(
445 lsp_types::PublishDiagnosticsParams { uri: url, diagnostics, version },
450 if self.config.cargo_autoreload() {
451 self.fetch_workspaces_if_needed();
453 self.fetch_build_data_if_needed();
455 self.report_new_status_if_needed();
457 let loop_duration = loop_start.elapsed();
458 if loop_duration > Duration::from_millis(100) {
459 log::warn!("overly long loop turn: {:?}", loop_duration);
460 if env::var("RA_PROFILE").is_ok() {
462 lsp_types::MessageType::Error,
463 format!("overly long loop turn: {:?}", loop_duration),
470 fn on_request(&mut self, request_received: Instant, req: Request) -> Result<()> {
471 self.register_request(&req, request_received);
473 if self.shutdown_requested {
474 self.respond(Response::new_err(
476 lsp_server::ErrorCode::InvalidRequest as i32,
477 "Shutdown already requested.".to_owned(),
483 // Avoid flashing a bunch of unresolved references during initial load.
484 if self.workspaces.is_empty() && !self.is_quiescent() {
485 self.respond(lsp_server::Response::new_err(
487 // FIXME: i32 should impl From<ErrorCode> (from() guarantees lossless conversion)
488 lsp_server::ErrorCode::ContentModified as i32,
489 "waiting for cargo metadata or cargo check".to_owned(),
494 RequestDispatcher { req: Some(req), global_state: self }
495 .on_sync::<lsp_ext::ReloadWorkspace>(|s, ()| {
496 s.fetch_workspaces_request();
497 s.fetch_workspaces_if_needed();
500 .on_sync::<lsp_ext::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
501 .on_sync::<lsp_ext::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
502 .on_sync::<lsp_types::request::Shutdown>(|s, ()| {
503 s.shutdown_requested = true;
506 .on_sync::<lsp_types::request::SelectionRangeRequest>(|s, p| {
507 handlers::handle_selection_range(s.snapshot(), p)
509 .on_sync::<lsp_ext::MatchingBrace>(|s, p| {
510 handlers::handle_matching_brace(s.snapshot(), p)
512 .on_sync::<lsp_ext::MemoryUsage>(|s, p| handlers::handle_memory_usage(s, p))?
513 .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)
514 .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)
515 .on::<lsp_ext::ViewHir>(handlers::handle_view_hir)
516 .on::<lsp_ext::ViewCrateGraph>(handlers::handle_view_crate_graph)
517 .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)
518 .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)
519 .on::<lsp_ext::Runnables>(handlers::handle_runnables)
520 .on::<lsp_ext::RelatedTests>(handlers::handle_related_tests)
521 .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)
522 .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)
523 .on::<lsp_ext::CodeActionResolveRequest>(handlers::handle_code_action_resolve)
524 .on::<lsp_ext::HoverRequest>(handlers::handle_hover)
525 .on::<lsp_ext::ExternalDocs>(handlers::handle_open_docs)
526 .on::<lsp_ext::OpenCargoToml>(handlers::handle_open_cargo_toml)
527 .on::<lsp_ext::MoveItem>(handlers::handle_move_item)
528 .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)
529 .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)
530 .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)
531 .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)
532 .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)
533 .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)
534 .on::<lsp_types::request::Completion>(handlers::handle_completion)
535 .on::<lsp_types::request::ResolveCompletionItem>(handlers::handle_completion_resolve)
536 .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)
537 .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)
538 .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)
539 .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)
540 .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)
541 .on::<lsp_types::request::Rename>(handlers::handle_rename)
542 .on::<lsp_types::request::References>(handlers::handle_references)
543 .on::<lsp_types::request::Formatting>(handlers::handle_formatting)
544 .on::<lsp_types::request::DocumentHighlightRequest>(handlers::handle_document_highlight)
545 .on::<lsp_types::request::CallHierarchyPrepare>(handlers::handle_call_hierarchy_prepare)
546 .on::<lsp_types::request::CallHierarchyIncomingCalls>(
547 handlers::handle_call_hierarchy_incoming,
549 .on::<lsp_types::request::CallHierarchyOutgoingCalls>(
550 handlers::handle_call_hierarchy_outgoing,
552 .on::<lsp_types::request::SemanticTokensFullRequest>(
553 handlers::handle_semantic_tokens_full,
555 .on::<lsp_types::request::SemanticTokensFullDeltaRequest>(
556 handlers::handle_semantic_tokens_full_delta,
558 .on::<lsp_types::request::SemanticTokensRangeRequest>(
559 handlers::handle_semantic_tokens_range,
561 .on::<lsp_types::request::WillRenameFiles>(handlers::handle_will_rename_files)
562 .on::<lsp_ext::Ssr>(handlers::handle_ssr)
566 fn on_notification(&mut self, not: Notification) -> Result<()> {
567 NotificationDispatcher { not: Some(not), global_state: self }
568 .on::<lsp_types::notification::Cancel>(|this, params| {
569 let id: lsp_server::RequestId = match params.id {
570 lsp_types::NumberOrString::Number(id) => id.into(),
571 lsp_types::NumberOrString::String(id) => id.into(),
576 .on::<lsp_types::notification::WorkDoneProgressCancel>(|_this, _params| {
577 // Just ignore this. It is OK to continue sending progress
578 // notifications for this token, as the client can't know when
579 // we accepted notification.
582 .on::<lsp_types::notification::DidOpenTextDocument>(|this, params| {
583 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
586 .insert(path.clone(), DocumentData::new(params.text_document.version))
589 log::error!("duplicate DidOpenTextDocument: {}", path)
595 .set_file_contents(path, Some(params.text_document.text.into_bytes()));
597 // If the VFS contents are unchanged, update diagnostics, since `handle_event`
598 // won't see any changes. This avoids missing diagnostics when opening a file.
600 // If the file *was* changed, `handle_event` will already recompute and send
601 // diagnostics. We can't do it here, since the *current* file contents might be
602 // unset in salsa, since the VFS change hasn't been applied to the database yet.
604 this.maybe_update_diagnostics();
609 .on::<lsp_types::notification::DidChangeTextDocument>(|this, params| {
610 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
611 let doc = match this.mem_docs.get_mut(&path) {
614 log::error!("expected DidChangeTextDocument: {}", path);
618 let vfs = &mut this.vfs.write().0;
619 let file_id = vfs.file_id(&path).unwrap();
620 let mut text = String::from_utf8(vfs.file_contents(file_id).to_vec()).unwrap();
621 apply_document_changes(&mut text, params.content_changes);
623 // The version passed in DidChangeTextDocument is the version after all edits are applied
624 // so we should apply it before the vfs is notified.
625 doc.version = params.text_document.version;
627 vfs.set_file_contents(path.clone(), Some(text.into_bytes()));
631 .on::<lsp_types::notification::DidCloseTextDocument>(|this, params| {
632 let mut version = None;
633 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
634 match this.mem_docs.remove(&path) {
635 Some(doc) => version = Some(doc.version),
636 None => log::error!("orphan DidCloseTextDocument: {}", path),
639 this.semantic_tokens_cache.lock().remove(¶ms.text_document.uri);
641 if let Some(path) = path.as_path() {
642 this.loader.handle.invalidate(path.to_path_buf());
646 // Clear the diagnostics for the previously known version of the file.
647 // This prevents stale "cargo check" diagnostics if the file is
648 // closed, "cargo check" is run and then the file is reopened.
649 this.send_notification::<lsp_types::notification::PublishDiagnostics>(
650 lsp_types::PublishDiagnosticsParams {
651 uri: params.text_document.uri,
652 diagnostics: Vec::new(),
658 .on::<lsp_types::notification::DidSaveTextDocument>(|this, params| {
659 for flycheck in &this.flycheck {
662 if let Ok(abs_path) = from_proto::abs_path(¶ms.text_document.uri) {
663 this.maybe_refresh(&[(abs_path, ChangeKind::Modify)]);
667 .on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| {
668 // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
669 // this notification's parameters should be ignored and the actual config queried separately.
670 this.send_request::<lsp_types::request::WorkspaceConfiguration>(
671 lsp_types::ConfigurationParams {
672 items: vec![lsp_types::ConfigurationItem {
674 section: Some("rust-analyzer".to_string()),
678 log::debug!("config update response: '{:?}", resp);
679 let Response { error, result, .. } = resp;
681 match (error, result) {
683 log::error!("failed to fetch the server settings: {:?}", err)
685 (None, Some(mut configs)) => {
686 if let Some(json) = configs.get_mut(0) {
687 // Note that json can be null according to the spec if the client can't
688 // provide a configuration. This is handled in Config::update below.
689 let mut config = Config::clone(&*this.config);
690 config.update(json.take());
691 this.update_configuration(config);
694 (None, None) => log::error!(
695 "received empty server settings response from the client"
703 .on::<lsp_types::notification::DidChangeWatchedFiles>(|this, params| {
704 for change in params.changes {
705 if let Ok(path) = from_proto::abs_path(&change.uri) {
706 this.loader.handle.invalidate(path);
714 fn update_file_notifications_on_threadpool(&mut self) {
715 self.maybe_update_diagnostics();
717 // Ensure that only one cache priming task can run at a time
718 self.prime_caches_queue.request_op(());
719 if self.prime_caches_queue.should_start_op().is_none() {
723 self.task_pool.handle.spawn_with_sender({
724 let snap = self.snapshot();
726 let cb = |progress| {
727 sender.send(Task::PrimeCaches(progress)).unwrap();
729 match snap.analysis.prime_caches(cb) {
731 Err(_canceled) => (),
736 fn maybe_update_diagnostics(&mut self) {
737 let subscriptions = self
740 .map(|path| self.vfs.read().0.file_id(&path).unwrap())
741 .collect::<Vec<_>>();
743 log::trace!("updating notifications for {:?}", subscriptions);
744 if self.config.publish_diagnostics() {
745 let snapshot = self.snapshot();
746 self.task_pool.handle.spawn(move || {
747 let diagnostics = subscriptions
749 .filter_map(|file_id| {
750 handlers::publish_diagnostics(&snapshot, file_id)
752 if !is_canceled(&*err) {
753 log::error!("failed to compute diagnostics: {:?}", err);
758 .map(|diags| (file_id, diags))
760 .collect::<Vec<_>>();
761 Task::Diagnostics(diagnostics)