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 _;
14 use project_model::ProjectWorkspace;
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},
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 Workspaces(Vec<anyhow::Result<ProjectWorkspace>>),
65 PrimeCaches(PrimeCachesProgress),
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() && self.config.notifications.cargo_toml_not_found
105 lsp_types::MessageType::Error,
106 "rust-analyzer failed to discover workspace".to_string(),
110 let save_registration_options = lsp_types::TextDocumentSaveRegistrationOptions {
111 include_text: Some(false),
112 text_document_registration_options: lsp_types::TextDocumentRegistrationOptions {
113 document_selector: Some(vec![
114 lsp_types::DocumentFilter {
117 pattern: Some("**/*.rs".into()),
119 lsp_types::DocumentFilter {
122 pattern: Some("**/Cargo.toml".into()),
124 lsp_types::DocumentFilter {
127 pattern: Some("**/Cargo.lock".into()),
133 let registration = lsp_types::Registration {
134 id: "textDocument/didSave".to_string(),
135 method: "textDocument/didSave".to_string(),
136 register_options: Some(serde_json::to_value(save_registration_options).unwrap()),
138 self.send_request::<lsp_types::request::RegisterCapability>(
139 lsp_types::RegistrationParams { registrations: vec![registration] },
143 self.fetch_workspaces();
145 while let Some(event) = self.next_event(&inbox) {
146 if let Event::Lsp(lsp_server::Message::Notification(not)) = &event {
147 if not.method == lsp_types::notification::Exit::METHOD {
151 self.handle_event(event)?
154 Err("client exited without proper shutdown sequence")?
157 fn next_event(&self, inbox: &Receiver<lsp_server::Message>) -> Option<Event> {
159 recv(inbox) -> msg =>
160 msg.ok().map(Event::Lsp),
162 recv(self.task_pool.receiver) -> task =>
163 Some(Event::Task(task.unwrap())),
165 recv(self.loader.receiver) -> task =>
166 Some(Event::Vfs(task.unwrap())),
168 recv(self.flycheck_receiver) -> task =>
169 Some(Event::Flycheck(task.unwrap())),
173 fn handle_event(&mut self, event: Event) -> Result<()> {
174 let loop_start = Instant::now();
175 // NOTE: don't count blocking select! call as a loop-turn time
176 let _p = profile::span("GlobalState::handle_event");
178 log::info!("handle_event({:?})", event);
179 let task_queue_len = self.task_pool.handle.len();
180 if task_queue_len > 0 {
181 log::info!("task queue len: {}", task_queue_len);
184 let prev_status = self.status;
186 Event::Lsp(msg) => match msg {
187 lsp_server::Message::Request(req) => self.on_request(loop_start, req)?,
188 lsp_server::Message::Notification(not) => {
189 self.on_notification(not)?;
191 lsp_server::Message::Response(resp) => self.complete_request(resp),
193 Event::Task(mut task) => {
194 let _p = profile::span("GlobalState::handle_event/task");
195 let mut prime_caches_progress = Vec::new();
198 Task::Response(response) => self.respond(response),
199 Task::Diagnostics(diagnostics_per_file) => {
200 for (file_id, diagnostics) in diagnostics_per_file {
201 self.diagnostics.set_native_diagnostics(file_id, diagnostics)
204 Task::Workspaces(workspaces) => self.switch_workspaces(workspaces),
205 Task::PrimeCaches(progress) => match progress {
206 PrimeCachesProgress::Started => prime_caches_progress.push(progress),
207 PrimeCachesProgress::StartedOnCrate { .. } => {
208 match prime_caches_progress.last_mut() {
209 Some(last @ PrimeCachesProgress::StartedOnCrate { .. }) => {
210 // Coalesce subsequent update events.
213 _ => prime_caches_progress.push(progress),
216 PrimeCachesProgress::Finished => prime_caches_progress.push(progress),
219 // Coalesce multiple task events into one loop turn
220 task = match self.task_pool.receiver.try_recv() {
226 for progress in prime_caches_progress {
227 let (state, message, fraction);
229 PrimeCachesProgress::Started => {
230 state = Progress::Begin;
234 PrimeCachesProgress::StartedOnCrate { on_crate, n_done, n_total } => {
235 state = Progress::Report;
236 message = Some(format!("{}/{} ({})", n_done, n_total, on_crate));
237 fraction = Progress::fraction(n_done, n_total);
239 PrimeCachesProgress::Finished => {
240 state = Progress::End;
246 self.report_progress("indexing", state, message, Some(fraction));
249 Event::Vfs(mut task) => {
250 let _p = profile::span("GlobalState::handle_event/vfs");
253 vfs::loader::Message::Loaded { files } => {
254 let vfs = &mut self.vfs.write().0;
255 for (path, contents) in files {
256 let path = VfsPath::from(path);
257 if !self.mem_docs.contains_key(&path) {
258 vfs.set_file_contents(path, contents);
262 vfs::loader::Message::Progress { n_total, n_done } => {
264 self.transition(Status::Invalid);
266 let state = if n_done == 0 {
267 self.transition(Status::Loading);
269 } else if n_done < n_total {
272 assert_eq!(n_done, n_total);
273 self.transition(Status::Ready);
276 self.report_progress(
279 Some(format!("{}/{}", n_done, n_total)),
280 Some(Progress::fraction(n_done, n_total)),
285 // Coalesce many VFS event into a single loop turn
286 task = match self.loader.receiver.try_recv() {
292 Event::Flycheck(mut task) => {
293 let _p = profile::span("GlobalState::handle_event/flycheck");
296 flycheck::Message::AddDiagnostic { workspace_root, diagnostic } => {
298 crate::diagnostics::to_proto::map_rust_diagnostic_to_lsp(
299 &self.config.diagnostics_map,
303 for diag in diagnostics {
304 match url_to_file_id(&self.vfs.read().0, &diag.url) {
305 Ok(file_id) => self.diagnostics.add_check_diagnostic(
312 "File with cargo diagnostic not found in VFS: {}",
320 flycheck::Message::Progress { id, progress } => {
321 let (state, message) = match progress {
322 flycheck::Progress::DidStart => {
323 self.diagnostics.clear_check();
324 (Progress::Begin, None)
326 flycheck::Progress::DidCheckCrate(target) => {
327 (Progress::Report, Some(target))
329 flycheck::Progress::DidCancel => (Progress::End, None),
330 flycheck::Progress::DidFinish(result) => {
331 if let Err(err) = result {
332 log::error!("cargo check failed: {}", err)
334 (Progress::End, None)
338 // When we're running multiple flychecks, we have to include a disambiguator in
339 // the title, or the editor complains. Note that this is a user-facing string.
340 let title = if self.flycheck.len() == 1 {
341 "cargo check".to_string()
343 format!("cargo check (#{})", id + 1)
345 self.report_progress(&title, state, message, None);
348 // Coalesce many flycheck updates into a single loop turn
349 task = match self.flycheck_receiver.try_recv() {
357 let state_changed = self.process_changes();
358 if prev_status == Status::Loading && self.status == Status::Ready {
359 for flycheck in &self.flycheck {
364 if self.status == Status::Ready && (state_changed || prev_status == Status::Loading) {
365 self.update_file_notifications_on_threadpool();
367 // Refresh semantic tokens if the client supports it.
368 if self.config.semantic_tokens_refresh {
369 self.semantic_tokens_cache.lock().clear();
370 self.send_request::<lsp_types::request::SemanticTokensRefesh>((), |_, _| ());
373 // Refresh code lens if the client supports it.
374 if self.config.code_lens_refresh {
375 self.send_request::<lsp_types::request::CodeLensRefresh>((), |_, _| ());
379 if let Some(diagnostic_changes) = self.diagnostics.take_changes() {
380 for file_id in diagnostic_changes {
381 let url = file_id_to_url(&self.vfs.read().0, file_id);
382 let diagnostics = self.diagnostics.diagnostics_for(file_id).cloned().collect();
383 let version = from_proto::vfs_path(&url)
384 .map(|path| self.mem_docs.get(&path).map(|it| it.version))
385 .unwrap_or_default();
387 self.send_notification::<lsp_types::notification::PublishDiagnostics>(
388 lsp_types::PublishDiagnosticsParams { uri: url, diagnostics, version },
393 let loop_duration = loop_start.elapsed();
394 if loop_duration > Duration::from_millis(100) {
395 log::warn!("overly long loop turn: {:?}", loop_duration);
396 if env::var("RA_PROFILE").is_ok() {
398 lsp_types::MessageType::Error,
399 format!("overly long loop turn: {:?}", loop_duration),
406 fn on_request(&mut self, request_received: Instant, req: Request) -> Result<()> {
407 self.register_request(&req, request_received);
409 if self.shutdown_requested {
410 self.respond(Response::new_err(
412 lsp_server::ErrorCode::InvalidRequest as i32,
413 "Shutdown already requested.".to_owned(),
419 if self.status == Status::Loading && req.method != "shutdown" {
420 self.respond(lsp_server::Response::new_err(
422 // FIXME: i32 should impl From<ErrorCode> (from() guarantees lossless conversion)
423 lsp_server::ErrorCode::ContentModified as i32,
424 "Rust Analyzer is still loading...".to_owned(),
429 RequestDispatcher { req: Some(req), global_state: self }
430 .on_sync::<lsp_ext::ReloadWorkspace>(|s, ()| Ok(s.fetch_workspaces()))?
431 .on_sync::<lsp_ext::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
432 .on_sync::<lsp_ext::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
433 .on_sync::<lsp_types::request::Shutdown>(|s, ()| {
434 s.shutdown_requested = true;
437 .on_sync::<lsp_types::request::SelectionRangeRequest>(|s, p| {
438 handlers::handle_selection_range(s.snapshot(), p)
440 .on_sync::<lsp_ext::MatchingBrace>(|s, p| {
441 handlers::handle_matching_brace(s.snapshot(), p)
443 .on_sync::<lsp_ext::MemoryUsage>(|s, p| handlers::handle_memory_usage(s, p))?
444 .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)
445 .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)
446 .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)
447 .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)
448 .on::<lsp_ext::Runnables>(handlers::handle_runnables)
449 .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)
450 .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)
451 .on::<lsp_ext::CodeActionResolveRequest>(handlers::handle_code_action_resolve)
452 .on::<lsp_ext::HoverRequest>(handlers::handle_hover)
453 .on::<lsp_ext::ExternalDocs>(handlers::handle_open_docs)
454 .on::<lsp_ext::OpenCargoToml>(handlers::handle_open_cargo_toml)
455 .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)
456 .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)
457 .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)
458 .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)
459 .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)
460 .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)
461 .on::<lsp_types::request::Completion>(handlers::handle_completion)
462 .on::<lsp_types::request::ResolveCompletionItem>(handlers::handle_completion_resolve)
463 .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)
464 .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)
465 .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)
466 .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)
467 .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)
468 .on::<lsp_types::request::Rename>(handlers::handle_rename)
469 .on::<lsp_types::request::References>(handlers::handle_references)
470 .on::<lsp_types::request::Formatting>(handlers::handle_formatting)
471 .on::<lsp_types::request::DocumentHighlightRequest>(handlers::handle_document_highlight)
472 .on::<lsp_types::request::CallHierarchyPrepare>(handlers::handle_call_hierarchy_prepare)
473 .on::<lsp_types::request::CallHierarchyIncomingCalls>(
474 handlers::handle_call_hierarchy_incoming,
476 .on::<lsp_types::request::CallHierarchyOutgoingCalls>(
477 handlers::handle_call_hierarchy_outgoing,
479 .on::<lsp_types::request::SemanticTokensFullRequest>(
480 handlers::handle_semantic_tokens_full,
482 .on::<lsp_types::request::SemanticTokensFullDeltaRequest>(
483 handlers::handle_semantic_tokens_full_delta,
485 .on::<lsp_types::request::SemanticTokensRangeRequest>(
486 handlers::handle_semantic_tokens_range,
488 .on::<lsp_ext::Ssr>(handlers::handle_ssr)
492 fn on_notification(&mut self, not: Notification) -> Result<()> {
493 NotificationDispatcher { not: Some(not), global_state: self }
494 .on::<lsp_types::notification::Cancel>(|this, params| {
495 let id: lsp_server::RequestId = match params.id {
496 lsp_types::NumberOrString::Number(id) => id.into(),
497 lsp_types::NumberOrString::String(id) => id.into(),
502 .on::<lsp_types::notification::DidOpenTextDocument>(|this, params| {
503 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
506 .insert(path.clone(), DocumentData::new(params.text_document.version))
509 log::error!("duplicate DidOpenTextDocument: {}", path)
515 .set_file_contents(path, Some(params.text_document.text.into_bytes()));
517 // If the VFS contents are unchanged, update diagnostics, since `handle_event`
518 // won't see any changes. This avoids missing diagnostics when opening a file.
520 // If the file *was* changed, `handle_event` will already recompute and send
521 // diagnostics. We can't do it here, since the *current* file contents might be
522 // unset in salsa, since the VFS change hasn't been applied to the database yet.
524 this.maybe_update_diagnostics();
529 .on::<lsp_types::notification::DidChangeTextDocument>(|this, params| {
530 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
531 let doc = match this.mem_docs.get_mut(&path) {
534 log::error!("expected DidChangeTextDocument: {}", path);
538 let vfs = &mut this.vfs.write().0;
539 let file_id = vfs.file_id(&path).unwrap();
540 let mut text = String::from_utf8(vfs.file_contents(file_id).to_vec()).unwrap();
541 apply_document_changes(&mut text, params.content_changes);
543 // The version passed in DidChangeTextDocument is the version after all edits are applied
544 // so we should apply it before the vfs is notified.
545 doc.version = params.text_document.version;
547 vfs.set_file_contents(path.clone(), Some(text.into_bytes()));
551 .on::<lsp_types::notification::DidCloseTextDocument>(|this, params| {
552 let mut version = None;
553 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
554 match this.mem_docs.remove(&path) {
555 Some(doc) => version = Some(doc.version),
556 None => log::error!("orphan DidCloseTextDocument: {}", path),
559 this.semantic_tokens_cache.lock().remove(¶ms.text_document.uri);
561 if let Some(path) = path.as_path() {
562 this.loader.handle.invalidate(path.to_path_buf());
566 // Clear the diagnostics for the previously known version of the file.
567 // This prevents stale "cargo check" diagnostics if the file is
568 // closed, "cargo check" is run and then the file is reopened.
569 this.send_notification::<lsp_types::notification::PublishDiagnostics>(
570 lsp_types::PublishDiagnosticsParams {
571 uri: params.text_document.uri,
572 diagnostics: Vec::new(),
578 .on::<lsp_types::notification::DidSaveTextDocument>(|this, params| {
579 for flycheck in &this.flycheck {
582 if let Ok(abs_path) = from_proto::abs_path(¶ms.text_document.uri) {
583 this.maybe_refresh(&[(abs_path, ChangeKind::Modify)]);
587 .on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| {
588 // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
589 // this notification's parameters should be ignored and the actual config queried separately.
590 this.send_request::<lsp_types::request::WorkspaceConfiguration>(
591 lsp_types::ConfigurationParams {
592 items: vec![lsp_types::ConfigurationItem {
594 section: Some("rust-analyzer".to_string()),
598 log::debug!("config update response: '{:?}", resp);
599 let Response { error, result, .. } = resp;
601 match (error, result) {
603 log::error!("failed to fetch the server settings: {:?}", err)
605 (None, Some(mut configs)) => {
606 if let Some(json) = configs.get_mut(0) {
607 // Note that json can be null according to the spec if the client can't
608 // provide a configuration. This is handled in Config::update below.
609 let mut config = this.config.clone();
610 config.update(json.take());
611 this.update_configuration(config);
614 (None, None) => log::error!(
615 "received empty server settings response from the client"
623 .on::<lsp_types::notification::DidChangeWatchedFiles>(|this, params| {
624 for change in params.changes {
625 if let Ok(path) = from_proto::abs_path(&change.uri) {
626 this.loader.handle.invalidate(path);
634 fn update_file_notifications_on_threadpool(&mut self) {
635 self.maybe_update_diagnostics();
636 self.task_pool.handle.spawn_with_sender({
637 let snap = self.snapshot();
640 .prime_caches(|progress| {
641 sender.send(Task::PrimeCaches(progress)).unwrap();
643 .unwrap_or_else(|_: Canceled| {
644 // Pretend that we're done, so that the progress bar is removed. Otherwise
645 // the editor may complain about it already existing.
646 sender.send(Task::PrimeCaches(PrimeCachesProgress::Finished)).unwrap()
651 fn maybe_update_diagnostics(&mut self) {
652 let subscriptions = self
655 .map(|path| self.vfs.read().0.file_id(&path).unwrap())
656 .collect::<Vec<_>>();
658 log::trace!("updating notifications for {:?}", subscriptions);
659 if self.config.publish_diagnostics {
660 let snapshot = self.snapshot();
661 self.task_pool.handle.spawn(move || {
662 let diagnostics = subscriptions
664 .filter_map(|file_id| {
665 handlers::publish_diagnostics(&snapshot, file_id)
667 if !is_canceled(&*err) {
668 log::error!("failed to compute diagnostics: {:?}", err);
673 .map(|diags| (file_id, diags))
675 .collect::<Vec<_>>();
676 Task::Diagnostics(diagnostics)