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 crossbeam_channel::{select, Receiver};
9 use ide::PrimeCachesProgress;
10 use ide::{Canceled, FileId};
11 use ide_db::base_db::VfsPath;
12 use lsp_server::{Connection, Notification, Request, Response};
13 use lsp_types::notification::Notification as _;
18 dispatch::{NotificationDispatcher, RequestDispatcher},
19 document::DocumentData,
21 global_state::{file_id_to_url, url_to_file_id, GlobalState, Status},
23 lsp_utils::{apply_document_changes, is_canceled, notification_is, Progress},
24 reload::ProjectWorkspaceProgress,
28 pub fn main_loop(config: Config, connection: Connection) -> Result<()> {
29 log::info!("initial config: {:#?}", config);
31 // Windows scheduler implements priority boosts: if thread waits for an
32 // event (like a condvar), and event fires, priority of the thread is
33 // temporary bumped. This optimization backfires in our case: each time the
34 // `main_loop` schedules a task to run on a threadpool, the worker threads
35 // gets a higher priority, and (on a machine with fewer cores) displaces the
36 // main loop! We work-around this by marking the main loop as a
37 // higher-priority thread.
39 // https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities
40 // https://docs.microsoft.com/en-us/windows/win32/procthread/priority-boosts
41 // https://github.com/rust-analyzer/rust-analyzer/issues/2835
44 use winapi::um::processthreadsapi::*;
45 let thread = GetCurrentThread();
46 let thread_priority_above_normal = 1;
47 SetThreadPriority(thread, thread_priority_above_normal);
50 GlobalState::new(connection.sender, config).run(connection.receiver)
54 Lsp(lsp_server::Message),
56 Vfs(vfs::loader::Message),
57 Flycheck(flycheck::Message),
61 pub(crate) enum Task {
63 Diagnostics(Vec<(FileId, Vec<lsp_types::Diagnostic>)>),
64 PrimeCaches(PrimeCachesProgress),
65 FetchWorkspace(ProjectWorkspaceProgress),
68 impl fmt::Debug for Event {
69 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70 let debug_verbose_not = |not: &Notification, f: &mut fmt::Formatter| {
71 f.debug_struct("Notification").field("method", ¬.method).finish()
75 Event::Lsp(lsp_server::Message::Notification(not)) => {
76 if notification_is::<lsp_types::notification::DidOpenTextDocument>(not)
77 || notification_is::<lsp_types::notification::DidChangeTextDocument>(not)
79 return debug_verbose_not(not, f);
82 Event::Task(Task::Response(resp)) => {
84 .debug_struct("Response")
85 .field("id", &resp.id)
86 .field("error", &resp.error)
92 Event::Lsp(it) => fmt::Debug::fmt(it, f),
93 Event::Task(it) => fmt::Debug::fmt(it, f),
94 Event::Vfs(it) => fmt::Debug::fmt(it, f),
95 Event::Flycheck(it) => fmt::Debug::fmt(it, f),
101 fn run(mut self, inbox: Receiver<lsp_server::Message>) -> Result<()> {
102 if self.config.linked_projects().is_empty()
103 && self.config.notifications().cargo_toml_not_found
106 lsp_types::MessageType::Error,
107 "rust-analyzer failed to discover workspace".to_string(),
111 if self.config.did_save_text_document_dynamic_registration() {
112 let save_registration_options = lsp_types::TextDocumentSaveRegistrationOptions {
113 include_text: Some(false),
114 text_document_registration_options: lsp_types::TextDocumentRegistrationOptions {
115 document_selector: Some(vec![
116 lsp_types::DocumentFilter {
119 pattern: Some("**/*.rs".into()),
121 lsp_types::DocumentFilter {
124 pattern: Some("**/Cargo.toml".into()),
126 lsp_types::DocumentFilter {
129 pattern: Some("**/Cargo.lock".into()),
135 let registration = lsp_types::Registration {
136 id: "textDocument/didSave".to_string(),
137 method: "textDocument/didSave".to_string(),
138 register_options: Some(serde_json::to_value(save_registration_options).unwrap()),
140 self.send_request::<lsp_types::request::RegisterCapability>(
141 lsp_types::RegistrationParams { registrations: vec![registration] },
146 self.fetch_workspaces_request();
147 self.fetch_workspaces_if_needed();
149 while let Some(event) = self.next_event(&inbox) {
150 if let Event::Lsp(lsp_server::Message::Notification(not)) = &event {
151 if not.method == lsp_types::notification::Exit::METHOD {
155 self.handle_event(event)?
158 Err("client exited without proper shutdown sequence")?
161 fn next_event(&self, inbox: &Receiver<lsp_server::Message>) -> Option<Event> {
163 recv(inbox) -> msg =>
164 msg.ok().map(Event::Lsp),
166 recv(self.task_pool.receiver) -> task =>
167 Some(Event::Task(task.unwrap())),
169 recv(self.loader.receiver) -> task =>
170 Some(Event::Vfs(task.unwrap())),
172 recv(self.flycheck_receiver) -> task =>
173 Some(Event::Flycheck(task.unwrap())),
177 fn handle_event(&mut self, event: Event) -> Result<()> {
178 let loop_start = Instant::now();
179 // NOTE: don't count blocking select! call as a loop-turn time
180 let _p = profile::span("GlobalState::handle_event");
182 log::info!("handle_event({:?})", event);
183 let task_queue_len = self.task_pool.handle.len();
184 if task_queue_len > 0 {
185 log::info!("task queue len: {}", task_queue_len);
188 let prev_status = self.status;
190 Event::Lsp(msg) => match msg {
191 lsp_server::Message::Request(req) => self.on_request(loop_start, req)?,
192 lsp_server::Message::Notification(not) => {
193 self.on_notification(not)?;
195 lsp_server::Message::Response(resp) => self.complete_request(resp),
197 Event::Task(mut task) => {
198 let _p = profile::span("GlobalState::handle_event/task");
199 let mut prime_caches_progress = Vec::new();
202 Task::Response(response) => self.respond(response),
203 Task::Diagnostics(diagnostics_per_file) => {
204 for (file_id, diagnostics) in diagnostics_per_file {
205 self.diagnostics.set_native_diagnostics(file_id, diagnostics)
208 Task::PrimeCaches(progress) => match progress {
209 PrimeCachesProgress::Started => prime_caches_progress.push(progress),
210 PrimeCachesProgress::StartedOnCrate { .. } => {
211 match prime_caches_progress.last_mut() {
212 Some(last @ PrimeCachesProgress::StartedOnCrate { .. }) => {
213 // Coalesce subsequent update events.
216 _ => prime_caches_progress.push(progress),
219 PrimeCachesProgress::Finished => prime_caches_progress.push(progress),
221 Task::FetchWorkspace(progress) => {
222 let (state, msg) = match progress {
223 ProjectWorkspaceProgress::Begin => (Progress::Begin, None),
224 ProjectWorkspaceProgress::Report(msg) => {
225 (Progress::Report, Some(msg))
227 ProjectWorkspaceProgress::End(workspaces) => {
228 self.fetch_workspaces_completed();
229 self.switch_workspaces(workspaces);
230 (Progress::End, None)
233 self.report_progress("fetching", state, msg, None);
236 // Coalesce multiple task events into one loop turn
237 task = match self.task_pool.receiver.try_recv() {
243 for progress in prime_caches_progress {
244 let (state, message, fraction);
246 PrimeCachesProgress::Started => {
247 state = Progress::Begin;
251 PrimeCachesProgress::StartedOnCrate { on_crate, n_done, n_total } => {
252 state = Progress::Report;
253 message = Some(format!("{}/{} ({})", n_done, n_total, on_crate));
254 fraction = Progress::fraction(n_done, n_total);
256 PrimeCachesProgress::Finished => {
257 state = Progress::End;
263 self.report_progress("indexing", state, message, Some(fraction));
266 Event::Vfs(mut task) => {
267 let _p = profile::span("GlobalState::handle_event/vfs");
270 vfs::loader::Message::Loaded { files } => {
271 let vfs = &mut self.vfs.write().0;
272 for (path, contents) in files {
273 let path = VfsPath::from(path);
274 if !self.mem_docs.contains_key(&path) {
275 vfs.set_file_contents(path, contents);
279 vfs::loader::Message::Progress { n_total, n_done } => {
281 self.transition(Status::Invalid);
283 let state = if n_done == 0 {
284 self.transition(Status::Loading);
286 } else if n_done < n_total {
289 assert_eq!(n_done, n_total);
290 self.transition(Status::Ready);
293 self.report_progress(
296 Some(format!("{}/{}", n_done, n_total)),
297 Some(Progress::fraction(n_done, n_total)),
302 // Coalesce many VFS event into a single loop turn
303 task = match self.loader.receiver.try_recv() {
309 Event::Flycheck(mut task) => {
310 let _p = profile::span("GlobalState::handle_event/flycheck");
313 flycheck::Message::AddDiagnostic { workspace_root, diagnostic } => {
315 crate::diagnostics::to_proto::map_rust_diagnostic_to_lsp(
316 &self.config.diagnostics_map(),
320 for diag in diagnostics {
321 match url_to_file_id(&self.vfs.read().0, &diag.url) {
322 Ok(file_id) => self.diagnostics.add_check_diagnostic(
329 "File with cargo diagnostic not found in VFS: {}",
337 flycheck::Message::Progress { id, progress } => {
338 let (state, message) = match progress {
339 flycheck::Progress::DidStart => {
340 self.diagnostics.clear_check();
341 (Progress::Begin, None)
343 flycheck::Progress::DidCheckCrate(target) => {
344 (Progress::Report, Some(target))
346 flycheck::Progress::DidCancel => (Progress::End, None),
347 flycheck::Progress::DidFinish(result) => {
348 if let Err(err) = result {
349 log::error!("cargo check failed: {}", err)
351 (Progress::End, None)
355 // When we're running multiple flychecks, we have to include a disambiguator in
356 // the title, or the editor complains. Note that this is a user-facing string.
357 let title = if self.flycheck.len() == 1 {
358 "cargo check".to_string()
360 format!("cargo check (#{})", id + 1)
362 self.report_progress(&title, state, message, None);
365 // Coalesce many flycheck updates into a single loop turn
366 task = match self.flycheck_receiver.try_recv() {
374 let state_changed = self.process_changes();
375 if prev_status == Status::Loading && self.status == Status::Ready {
376 for flycheck in &self.flycheck {
381 if self.status == Status::Ready && (state_changed || prev_status == Status::Loading) {
382 self.update_file_notifications_on_threadpool();
384 // Refresh semantic tokens if the client supports it.
385 if self.config.semantic_tokens_refresh() {
386 self.semantic_tokens_cache.lock().clear();
387 self.send_request::<lsp_types::request::SemanticTokensRefesh>((), |_, _| ());
390 // Refresh code lens if the client supports it.
391 if self.config.code_lens_refresh() {
392 self.send_request::<lsp_types::request::CodeLensRefresh>((), |_, _| ());
396 if let Some(diagnostic_changes) = self.diagnostics.take_changes() {
397 for file_id in diagnostic_changes {
398 let url = file_id_to_url(&self.vfs.read().0, file_id);
399 let diagnostics = self.diagnostics.diagnostics_for(file_id).cloned().collect();
400 let version = from_proto::vfs_path(&url)
401 .map(|path| self.mem_docs.get(&path).map(|it| it.version))
402 .unwrap_or_default();
404 self.send_notification::<lsp_types::notification::PublishDiagnostics>(
405 lsp_types::PublishDiagnosticsParams { uri: url, diagnostics, version },
410 self.fetch_workspaces_if_needed();
412 let loop_duration = loop_start.elapsed();
413 if loop_duration > Duration::from_millis(100) {
414 log::warn!("overly long loop turn: {:?}", loop_duration);
415 if env::var("RA_PROFILE").is_ok() {
417 lsp_types::MessageType::Error,
418 format!("overly long loop turn: {:?}", loop_duration),
425 fn on_request(&mut self, request_received: Instant, req: Request) -> Result<()> {
426 self.register_request(&req, request_received);
428 if self.shutdown_requested {
429 self.respond(Response::new_err(
431 lsp_server::ErrorCode::InvalidRequest as i32,
432 "Shutdown already requested.".to_owned(),
438 if self.status == Status::Loading && req.method != "shutdown" {
439 self.respond(lsp_server::Response::new_err(
441 // FIXME: i32 should impl From<ErrorCode> (from() guarantees lossless conversion)
442 lsp_server::ErrorCode::ContentModified as i32,
443 "Rust Analyzer is still loading...".to_owned(),
448 RequestDispatcher { req: Some(req), global_state: self }
449 .on_sync::<lsp_ext::ReloadWorkspace>(|s, ()| Ok(s.fetch_workspaces_request()))?
450 .on_sync::<lsp_ext::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
451 .on_sync::<lsp_ext::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
452 .on_sync::<lsp_types::request::Shutdown>(|s, ()| {
453 s.shutdown_requested = true;
456 .on_sync::<lsp_types::request::SelectionRangeRequest>(|s, p| {
457 handlers::handle_selection_range(s.snapshot(), p)
459 .on_sync::<lsp_ext::MatchingBrace>(|s, p| {
460 handlers::handle_matching_brace(s.snapshot(), p)
462 .on_sync::<lsp_ext::MemoryUsage>(|s, p| handlers::handle_memory_usage(s, p))?
463 .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)
464 .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)
465 .on::<lsp_ext::ViewHir>(handlers::handle_view_hir)
466 .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)
467 .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)
468 .on::<lsp_ext::Runnables>(handlers::handle_runnables)
469 .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)
470 .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)
471 .on::<lsp_ext::CodeActionResolveRequest>(handlers::handle_code_action_resolve)
472 .on::<lsp_ext::HoverRequest>(handlers::handle_hover)
473 .on::<lsp_ext::ExternalDocs>(handlers::handle_open_docs)
474 .on::<lsp_ext::OpenCargoToml>(handlers::handle_open_cargo_toml)
475 .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)
476 .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)
477 .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)
478 .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)
479 .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)
480 .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)
481 .on::<lsp_types::request::Completion>(handlers::handle_completion)
482 .on::<lsp_types::request::ResolveCompletionItem>(handlers::handle_completion_resolve)
483 .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)
484 .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)
485 .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)
486 .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)
487 .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)
488 .on::<lsp_types::request::Rename>(handlers::handle_rename)
489 .on::<lsp_types::request::References>(handlers::handle_references)
490 .on::<lsp_types::request::Formatting>(handlers::handle_formatting)
491 .on::<lsp_types::request::DocumentHighlightRequest>(handlers::handle_document_highlight)
492 .on::<lsp_types::request::CallHierarchyPrepare>(handlers::handle_call_hierarchy_prepare)
493 .on::<lsp_types::request::CallHierarchyIncomingCalls>(
494 handlers::handle_call_hierarchy_incoming,
496 .on::<lsp_types::request::CallHierarchyOutgoingCalls>(
497 handlers::handle_call_hierarchy_outgoing,
499 .on::<lsp_types::request::SemanticTokensFullRequest>(
500 handlers::handle_semantic_tokens_full,
502 .on::<lsp_types::request::SemanticTokensFullDeltaRequest>(
503 handlers::handle_semantic_tokens_full_delta,
505 .on::<lsp_types::request::SemanticTokensRangeRequest>(
506 handlers::handle_semantic_tokens_range,
508 .on::<lsp_types::request::WillRenameFiles>(handlers::handle_will_rename_files)
509 .on::<lsp_ext::Ssr>(handlers::handle_ssr)
513 fn on_notification(&mut self, not: Notification) -> Result<()> {
514 NotificationDispatcher { not: Some(not), global_state: self }
515 .on::<lsp_types::notification::Cancel>(|this, params| {
516 let id: lsp_server::RequestId = match params.id {
517 lsp_types::NumberOrString::Number(id) => id.into(),
518 lsp_types::NumberOrString::String(id) => id.into(),
523 .on::<lsp_types::notification::DidOpenTextDocument>(|this, params| {
524 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
527 .insert(path.clone(), DocumentData::new(params.text_document.version))
530 log::error!("duplicate DidOpenTextDocument: {}", path)
536 .set_file_contents(path, Some(params.text_document.text.into_bytes()));
538 // If the VFS contents are unchanged, update diagnostics, since `handle_event`
539 // won't see any changes. This avoids missing diagnostics when opening a file.
541 // If the file *was* changed, `handle_event` will already recompute and send
542 // diagnostics. We can't do it here, since the *current* file contents might be
543 // unset in salsa, since the VFS change hasn't been applied to the database yet.
545 this.maybe_update_diagnostics();
550 .on::<lsp_types::notification::DidChangeTextDocument>(|this, params| {
551 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
552 let doc = match this.mem_docs.get_mut(&path) {
555 log::error!("expected DidChangeTextDocument: {}", path);
559 let vfs = &mut this.vfs.write().0;
560 let file_id = vfs.file_id(&path).unwrap();
561 let mut text = String::from_utf8(vfs.file_contents(file_id).to_vec()).unwrap();
562 apply_document_changes(&mut text, params.content_changes);
564 // The version passed in DidChangeTextDocument is the version after all edits are applied
565 // so we should apply it before the vfs is notified.
566 doc.version = params.text_document.version;
568 vfs.set_file_contents(path.clone(), Some(text.into_bytes()));
572 .on::<lsp_types::notification::DidCloseTextDocument>(|this, params| {
573 let mut version = None;
574 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
575 match this.mem_docs.remove(&path) {
576 Some(doc) => version = Some(doc.version),
577 None => log::error!("orphan DidCloseTextDocument: {}", path),
580 this.semantic_tokens_cache.lock().remove(¶ms.text_document.uri);
582 if let Some(path) = path.as_path() {
583 this.loader.handle.invalidate(path.to_path_buf());
587 // Clear the diagnostics for the previously known version of the file.
588 // This prevents stale "cargo check" diagnostics if the file is
589 // closed, "cargo check" is run and then the file is reopened.
590 this.send_notification::<lsp_types::notification::PublishDiagnostics>(
591 lsp_types::PublishDiagnosticsParams {
592 uri: params.text_document.uri,
593 diagnostics: Vec::new(),
599 .on::<lsp_types::notification::DidSaveTextDocument>(|this, params| {
600 for flycheck in &this.flycheck {
603 if let Ok(abs_path) = from_proto::abs_path(¶ms.text_document.uri) {
604 this.maybe_refresh(&[(abs_path, ChangeKind::Modify)]);
608 .on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| {
609 // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
610 // this notification's parameters should be ignored and the actual config queried separately.
611 this.send_request::<lsp_types::request::WorkspaceConfiguration>(
612 lsp_types::ConfigurationParams {
613 items: vec![lsp_types::ConfigurationItem {
615 section: Some("rust-analyzer".to_string()),
619 log::debug!("config update response: '{:?}", resp);
620 let Response { error, result, .. } = resp;
622 match (error, result) {
624 log::error!("failed to fetch the server settings: {:?}", err)
626 (None, Some(mut configs)) => {
627 if let Some(json) = configs.get_mut(0) {
628 // Note that json can be null according to the spec if the client can't
629 // provide a configuration. This is handled in Config::update below.
630 let mut config = Config::clone(&*this.config);
631 config.update(json.take());
632 this.update_configuration(config);
635 (None, None) => log::error!(
636 "received empty server settings response from the client"
644 .on::<lsp_types::notification::DidChangeWatchedFiles>(|this, params| {
645 for change in params.changes {
646 if let Ok(path) = from_proto::abs_path(&change.uri) {
647 this.loader.handle.invalidate(path);
655 fn update_file_notifications_on_threadpool(&mut self) {
656 self.maybe_update_diagnostics();
657 self.task_pool.handle.spawn_with_sender({
658 let snap = self.snapshot();
661 .prime_caches(|progress| {
662 sender.send(Task::PrimeCaches(progress)).unwrap();
664 .unwrap_or_else(|_: Canceled| {
665 // Pretend that we're done, so that the progress bar is removed. Otherwise
666 // the editor may complain about it already existing.
667 sender.send(Task::PrimeCaches(PrimeCachesProgress::Finished)).unwrap()
672 fn maybe_update_diagnostics(&mut self) {
673 let subscriptions = self
676 .map(|path| self.vfs.read().0.file_id(&path).unwrap())
677 .collect::<Vec<_>>();
679 log::trace!("updating notifications for {:?}", subscriptions);
680 if self.config.publish_diagnostics() {
681 let snapshot = self.snapshot();
682 self.task_pool.handle.spawn(move || {
683 let diagnostics = subscriptions
685 .filter_map(|file_id| {
686 handlers::publish_diagnostics(&snapshot, file_id)
688 if !is_canceled(&*err) {
689 log::error!("failed to compute diagnostics: {:?}", err);
694 .map(|diags| (file_id, diags))
696 .collect::<Vec<_>>();
697 Task::Diagnostics(diagnostics)