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_db::base_db::{SourceDatabaseExt, VfsPath};
12 use lsp_server::{Connection, Notification, Request};
13 use lsp_types::notification::Notification as _;
14 use vfs::{ChangeKind, FileId};
18 dispatch::{NotificationDispatcher, RequestDispatcher},
20 global_state::{file_id_to_url, url_to_file_id, GlobalState},
22 lsp_utils::{apply_document_changes, notification_is, Progress},
23 mem_docs::DocumentData,
24 reload::{self, BuildDataProgress, ProjectWorkspaceProgress},
28 pub fn main_loop(config: Config, connection: Connection) -> Result<()> {
29 tracing::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 {
62 Response(lsp_server::Response),
63 Retry(lsp_server::Request),
64 Diagnostics(Vec<(FileId, Vec<lsp_types::Diagnostic>)>),
65 PrimeCaches(PrimeCachesProgress),
66 FetchWorkspace(ProjectWorkspaceProgress),
67 FetchBuildData(BuildDataProgress),
71 pub(crate) enum PrimeCachesProgress {
73 Report(ide::ParallelPrimeCachesProgress),
74 End { cancelled: bool },
77 impl fmt::Debug for Event {
78 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79 let debug_verbose_not = |not: &Notification, f: &mut fmt::Formatter| {
80 f.debug_struct("Notification").field("method", ¬.method).finish()
84 Event::Lsp(lsp_server::Message::Notification(not)) => {
85 if notification_is::<lsp_types::notification::DidOpenTextDocument>(not)
86 || notification_is::<lsp_types::notification::DidChangeTextDocument>(not)
88 return debug_verbose_not(not, f);
91 Event::Task(Task::Response(resp)) => {
93 .debug_struct("Response")
94 .field("id", &resp.id)
95 .field("error", &resp.error)
101 Event::Lsp(it) => fmt::Debug::fmt(it, f),
102 Event::Task(it) => fmt::Debug::fmt(it, f),
103 Event::Vfs(it) => fmt::Debug::fmt(it, f),
104 Event::Flycheck(it) => fmt::Debug::fmt(it, f),
110 fn run(mut self, inbox: Receiver<lsp_server::Message>) -> Result<()> {
111 if self.config.linked_projects().is_empty()
112 && self.config.detached_files().is_empty()
113 && self.config.notifications().cargo_toml_not_found
115 self.show_and_log_error("rust-analyzer failed to discover workspace".to_string(), None);
118 if self.config.did_save_text_document_dynamic_registration() {
119 let save_registration_options = lsp_types::TextDocumentSaveRegistrationOptions {
120 include_text: Some(false),
121 text_document_registration_options: lsp_types::TextDocumentRegistrationOptions {
122 document_selector: Some(vec![
123 lsp_types::DocumentFilter {
126 pattern: Some("**/*.rs".into()),
128 lsp_types::DocumentFilter {
131 pattern: Some("**/Cargo.toml".into()),
133 lsp_types::DocumentFilter {
136 pattern: Some("**/Cargo.lock".into()),
142 let registration = lsp_types::Registration {
143 id: "textDocument/didSave".to_string(),
144 method: "textDocument/didSave".to_string(),
145 register_options: Some(serde_json::to_value(save_registration_options).unwrap()),
147 self.send_request::<lsp_types::request::RegisterCapability>(
148 lsp_types::RegistrationParams { registrations: vec![registration] },
153 self.fetch_workspaces_queue.request_op("startup".to_string());
154 if let Some(cause) = self.fetch_workspaces_queue.should_start_op() {
155 self.fetch_workspaces(cause);
158 while let Some(event) = self.next_event(&inbox) {
159 if let Event::Lsp(lsp_server::Message::Notification(not)) = &event {
160 if not.method == lsp_types::notification::Exit::METHOD {
164 self.handle_event(event)?
167 Err("client exited without proper shutdown sequence".into())
170 fn next_event(&self, inbox: &Receiver<lsp_server::Message>) -> Option<Event> {
172 recv(inbox) -> msg =>
173 msg.ok().map(Event::Lsp),
175 recv(self.task_pool.receiver) -> task =>
176 Some(Event::Task(task.unwrap())),
178 recv(self.loader.receiver) -> task =>
179 Some(Event::Vfs(task.unwrap())),
181 recv(self.flycheck_receiver) -> task =>
182 Some(Event::Flycheck(task.unwrap())),
186 fn handle_event(&mut self, event: Event) -> Result<()> {
187 let loop_start = Instant::now();
188 // NOTE: don't count blocking select! call as a loop-turn time
189 let _p = profile::span("GlobalState::handle_event");
191 tracing::debug!("handle_event({:?})", event);
192 let task_queue_len = self.task_pool.handle.len();
193 if task_queue_len > 0 {
194 tracing::info!("task queue len: {}", task_queue_len);
197 let was_quiescent = self.is_quiescent();
199 Event::Lsp(msg) => match msg {
200 lsp_server::Message::Request(req) => self.on_request(loop_start, req),
201 lsp_server::Message::Notification(not) => {
202 self.on_notification(not)?;
204 lsp_server::Message::Response(resp) => self.complete_request(resp),
206 Event::Task(mut task) => {
207 let _p = profile::span("GlobalState::handle_event/task");
208 let mut prime_caches_progress = Vec::new();
211 Task::Response(response) => self.respond(response),
212 Task::Retry(req) => self.on_request(loop_start, req),
213 Task::Diagnostics(diagnostics_per_file) => {
214 for (file_id, diagnostics) in diagnostics_per_file {
215 self.diagnostics.set_native_diagnostics(file_id, diagnostics)
218 Task::PrimeCaches(progress) => match progress {
219 PrimeCachesProgress::Begin => prime_caches_progress.push(progress),
220 PrimeCachesProgress::Report(_) => {
221 match prime_caches_progress.last_mut() {
222 Some(last @ PrimeCachesProgress::Report(_)) => {
223 // Coalesce subsequent update events.
226 _ => prime_caches_progress.push(progress),
229 PrimeCachesProgress::End { .. } => prime_caches_progress.push(progress),
231 Task::FetchWorkspace(progress) => {
232 let (state, msg) = match progress {
233 ProjectWorkspaceProgress::Begin => (Progress::Begin, None),
234 ProjectWorkspaceProgress::Report(msg) => {
235 (Progress::Report, Some(msg))
237 ProjectWorkspaceProgress::End(workspaces) => {
238 self.fetch_workspaces_queue.op_completed(workspaces);
240 let old = Arc::clone(&self.workspaces);
241 self.switch_workspaces("fetched workspace".to_string());
242 let workspaces_updated = !Arc::ptr_eq(&old, &self.workspaces);
244 if self.config.run_build_scripts() && workspaces_updated {
245 self.fetch_build_data_queue
246 .request_op(format!("workspace updated"));
249 (Progress::End, None)
253 self.report_progress("Fetching", state, msg, None);
255 Task::FetchBuildData(progress) => {
256 let (state, msg) = match progress {
257 BuildDataProgress::Begin => (Some(Progress::Begin), None),
258 BuildDataProgress::Report(msg) => {
259 (Some(Progress::Report), Some(msg))
261 BuildDataProgress::End(build_data_result) => {
262 self.fetch_build_data_queue.op_completed(build_data_result);
264 self.switch_workspaces("fetched build data".to_string());
266 (Some(Progress::End), None)
270 if let Some(state) = state {
271 self.report_progress("Loading", state, msg, None);
276 // Coalesce multiple task events into one loop turn
277 task = match self.task_pool.receiver.try_recv() {
283 for progress in prime_caches_progress {
284 let (state, message, fraction);
286 PrimeCachesProgress::Begin => {
287 state = Progress::Begin;
291 PrimeCachesProgress::Report(report) => {
292 state = Progress::Report;
294 message = match &report.crates_currently_indexing[..] {
295 [crate_name] => Some(format!(
297 report.crates_done, report.crates_total, crate_name
299 [crate_name, rest @ ..] => Some(format!(
300 "{}/{} ({} + {} more)",
309 fraction = Progress::fraction(report.crates_done, report.crates_total);
311 PrimeCachesProgress::End { cancelled } => {
312 state = Progress::End;
316 self.prime_caches_queue.op_completed(());
318 self.prime_caches_queue
319 .request_op("restart after cancellation".to_string());
324 self.report_progress("Indexing", state, message, Some(fraction));
327 Event::Vfs(mut task) => {
328 let _p = profile::span("GlobalState::handle_event/vfs");
331 vfs::loader::Message::Loaded { files } => {
332 let vfs = &mut self.vfs.write().0;
333 for (path, contents) in files {
334 let path = VfsPath::from(path);
335 if !self.mem_docs.contains(&path) {
336 vfs.set_file_contents(path, contents);
340 vfs::loader::Message::Progress { n_total, n_done, config_version } => {
341 always!(config_version <= self.vfs_config_version);
343 self.vfs_progress_config_version = config_version;
344 self.vfs_progress_n_total = n_total;
345 self.vfs_progress_n_done = n_done;
347 let state = if n_done == 0 {
349 } else if n_done < n_total {
352 assert_eq!(n_done, n_total);
355 self.report_progress(
358 Some(format!("{}/{}", n_done, n_total)),
359 Some(Progress::fraction(n_done, n_total)),
363 // Coalesce many VFS event into a single loop turn
364 task = match self.loader.receiver.try_recv() {
370 Event::Flycheck(mut task) => {
371 let _p = profile::span("GlobalState::handle_event/flycheck");
374 flycheck::Message::AddDiagnostic { workspace_root, diagnostic } => {
375 let snap = self.snapshot();
377 crate::diagnostics::to_proto::map_rust_diagnostic_to_lsp(
378 &self.config.diagnostics_map(),
383 for diag in diagnostics {
384 match url_to_file_id(&self.vfs.read().0, &diag.url) {
385 Ok(file_id) => self.diagnostics.add_check_diagnostic(
392 "File with cargo diagnostic not found in VFS: {}",
400 flycheck::Message::Progress { id, progress } => {
401 let (state, message) = match progress {
402 flycheck::Progress::DidStart => {
403 self.diagnostics.clear_check();
404 (Progress::Begin, None)
406 flycheck::Progress::DidCheckCrate(target) => {
407 (Progress::Report, Some(target))
409 flycheck::Progress::DidCancel => (Progress::End, None),
410 flycheck::Progress::DidFinish(result) => {
411 if let Err(err) = result {
412 self.show_and_log_error(
413 "cargo check failed".to_string(),
414 Some(err.to_string()),
417 (Progress::End, None)
421 // When we're running multiple flychecks, we have to include a disambiguator in
422 // the title, or the editor complains. Note that this is a user-facing string.
423 let title = if self.flycheck.len() == 1 {
424 match self.config.flycheck() {
425 Some(config) => format!("{}", config),
426 None => "cargo check".to_string(),
429 format!("cargo check (#{})", id + 1)
431 self.report_progress(&title, state, message, None);
434 // Coalesce many flycheck updates into a single loop turn
435 task = match self.flycheck_receiver.try_recv() {
443 let state_changed = self.process_changes();
444 let memdocs_added_or_removed = self.mem_docs.take_changes();
446 if self.is_quiescent() {
448 for flycheck in &self.flycheck {
451 if self.config.prefill_caches() {
452 self.prime_caches_queue.request_op("became quiescent".to_string());
456 if !was_quiescent || state_changed {
457 // Refresh semantic tokens if the client supports it.
458 if self.config.semantic_tokens_refresh() {
459 self.semantic_tokens_cache.lock().clear();
460 self.send_request::<lsp_types::request::SemanticTokensRefresh>((), |_, _| ());
463 // Refresh code lens if the client supports it.
464 if self.config.code_lens_refresh() {
465 self.send_request::<lsp_types::request::CodeLensRefresh>((), |_, _| ());
469 if !was_quiescent || state_changed || memdocs_added_or_removed {
470 if self.config.publish_diagnostics() {
471 self.update_diagnostics()
476 if let Some(diagnostic_changes) = self.diagnostics.take_changes() {
477 for file_id in diagnostic_changes {
478 let db = self.analysis_host.raw_database();
479 let source_root = db.file_source_root(file_id);
480 if db.source_root(source_root).is_library {
481 // Only publish diagnostics for files in the workspace, not from crates.io deps
483 // While theoretically these should never have errors, we have quite a few false
484 // positives particularly in the stdlib, and those diagnostics would stay around
485 // forever if we emitted them here.
489 let url = file_id_to_url(&self.vfs.read().0, file_id);
490 let diagnostics = self.diagnostics.diagnostics_for(file_id).cloned().collect();
491 let version = from_proto::vfs_path(&url)
492 .map(|path| self.mem_docs.get(&path).map(|it| it.version))
493 .unwrap_or_default();
495 self.send_notification::<lsp_types::notification::PublishDiagnostics>(
496 lsp_types::PublishDiagnosticsParams { uri: url, diagnostics, version },
501 if self.config.cargo_autoreload() {
502 if let Some(cause) = self.fetch_workspaces_queue.should_start_op() {
503 self.fetch_workspaces(cause);
507 if !self.fetch_workspaces_queue.op_in_progress() {
508 if let Some(cause) = self.fetch_build_data_queue.should_start_op() {
509 self.fetch_build_data(cause);
513 if let Some(cause) = self.prime_caches_queue.should_start_op() {
514 tracing::debug!(%cause, "will prime caches");
515 let num_worker_threads = self.config.prime_caches_num_threads();
517 self.task_pool.handle.spawn_with_sender({
518 let analysis = self.snapshot().analysis;
520 sender.send(Task::PrimeCaches(PrimeCachesProgress::Begin)).unwrap();
521 let res = analysis.parallel_prime_caches(num_worker_threads, |progress| {
522 let report = PrimeCachesProgress::Report(progress);
523 sender.send(Task::PrimeCaches(report)).unwrap();
526 .send(Task::PrimeCaches(PrimeCachesProgress::End {
527 cancelled: res.is_err(),
534 let status = self.current_status();
535 if self.last_reported_status.as_ref() != Some(&status) {
536 self.last_reported_status = Some(status.clone());
538 if let (lsp_ext::Health::Error, Some(message)) = (status.health, &status.message) {
539 self.show_message(lsp_types::MessageType::ERROR, message.clone());
542 if self.config.server_status_notification() {
543 self.send_notification::<lsp_ext::ServerStatusNotification>(status);
547 let loop_duration = loop_start.elapsed();
548 if loop_duration > Duration::from_millis(100) && was_quiescent {
549 tracing::warn!("overly long loop turn: {:?}", loop_duration);
550 self.poke_rust_analyzer_developer(format!(
551 "overly long loop turn: {:?}",
558 fn on_request(&mut self, request_received: Instant, req: Request) {
559 self.register_request(&req, request_received);
561 if self.shutdown_requested {
562 self.respond(lsp_server::Response::new_err(
564 lsp_server::ErrorCode::InvalidRequest as i32,
565 "Shutdown already requested.".to_owned(),
570 // Avoid flashing a bunch of unresolved references during initial load.
571 if self.workspaces.is_empty() && !self.is_quiescent() {
572 self.respond(lsp_server::Response::new_err(
574 lsp_server::ErrorCode::ContentModified as i32,
575 "waiting for cargo metadata or cargo check".to_owned(),
580 RequestDispatcher { req: Some(req), global_state: self }
581 .on_sync_mut::<lsp_types::request::Shutdown>(|s, ()| {
582 s.shutdown_requested = true;
585 .on_sync_mut::<lsp_ext::ReloadWorkspace>(handlers::handle_workspace_reload)
586 .on_sync_mut::<lsp_ext::MemoryUsage>(handlers::handle_memory_usage)
587 .on_sync_mut::<lsp_ext::ShuffleCrateGraph>(handlers::handle_shuffle_crate_graph)
588 .on_sync::<lsp_ext::JoinLines>(handlers::handle_join_lines)
589 .on_sync::<lsp_ext::OnEnter>(handlers::handle_on_enter)
590 .on_sync::<lsp_types::request::SelectionRangeRequest>(handlers::handle_selection_range)
591 .on_sync::<lsp_ext::MatchingBrace>(handlers::handle_matching_brace)
592 .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)
593 .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)
594 .on::<lsp_ext::ViewHir>(handlers::handle_view_hir)
595 .on::<lsp_ext::ViewFileText>(handlers::handle_view_file_text)
596 .on::<lsp_ext::ViewCrateGraph>(handlers::handle_view_crate_graph)
597 .on::<lsp_ext::ViewItemTree>(handlers::handle_view_item_tree)
598 .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)
599 .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)
600 .on::<lsp_ext::Runnables>(handlers::handle_runnables)
601 .on::<lsp_ext::RelatedTests>(handlers::handle_related_tests)
602 .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)
603 .on::<lsp_ext::CodeActionResolveRequest>(handlers::handle_code_action_resolve)
604 .on::<lsp_ext::HoverRequest>(handlers::handle_hover)
605 .on::<lsp_ext::ExternalDocs>(handlers::handle_open_docs)
606 .on::<lsp_ext::OpenCargoToml>(handlers::handle_open_cargo_toml)
607 .on::<lsp_ext::MoveItem>(handlers::handle_move_item)
608 .on::<lsp_ext::WorkspaceSymbol>(handlers::handle_workspace_symbol)
609 .on::<lsp_ext::OnTypeFormatting>(handlers::handle_on_type_formatting)
610 .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)
611 .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)
612 .on::<lsp_types::request::GotoDeclaration>(handlers::handle_goto_declaration)
613 .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)
614 .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)
615 .on::<lsp_types::request::InlayHintRequest>(handlers::handle_inlay_hints)
616 .on::<lsp_types::request::InlayHintResolveRequest>(handlers::handle_inlay_hints_resolve)
617 .on::<lsp_types::request::Completion>(handlers::handle_completion)
618 .on::<lsp_types::request::ResolveCompletionItem>(handlers::handle_completion_resolve)
619 .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)
620 .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)
621 .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)
622 .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)
623 .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)
624 .on::<lsp_types::request::Rename>(handlers::handle_rename)
625 .on::<lsp_types::request::References>(handlers::handle_references)
626 .on::<lsp_types::request::Formatting>(handlers::handle_formatting)
627 .on::<lsp_types::request::RangeFormatting>(handlers::handle_range_formatting)
628 .on::<lsp_types::request::DocumentHighlightRequest>(handlers::handle_document_highlight)
629 .on::<lsp_types::request::CallHierarchyPrepare>(handlers::handle_call_hierarchy_prepare)
630 .on::<lsp_types::request::CallHierarchyIncomingCalls>(
631 handlers::handle_call_hierarchy_incoming,
633 .on::<lsp_types::request::CallHierarchyOutgoingCalls>(
634 handlers::handle_call_hierarchy_outgoing,
636 .on::<lsp_types::request::SemanticTokensFullRequest>(
637 handlers::handle_semantic_tokens_full,
639 .on::<lsp_types::request::SemanticTokensFullDeltaRequest>(
640 handlers::handle_semantic_tokens_full_delta,
642 .on::<lsp_types::request::SemanticTokensRangeRequest>(
643 handlers::handle_semantic_tokens_range,
645 .on::<lsp_types::request::WillRenameFiles>(handlers::handle_will_rename_files)
646 .on::<lsp_ext::Ssr>(handlers::handle_ssr)
650 fn on_notification(&mut self, not: Notification) -> Result<()> {
651 NotificationDispatcher { not: Some(not), global_state: self }
652 .on::<lsp_types::notification::Cancel>(|this, params| {
653 let id: lsp_server::RequestId = match params.id {
654 lsp_types::NumberOrString::Number(id) => id.into(),
655 lsp_types::NumberOrString::String(id) => id.into(),
660 .on::<lsp_types::notification::WorkDoneProgressCancel>(|_this, _params| {
661 // Just ignore this. It is OK to continue sending progress
662 // notifications for this token, as the client can't know when
663 // we accepted notification.
666 .on::<lsp_types::notification::DidOpenTextDocument>(|this, params| {
667 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
668 let already_exists = this
670 .insert(path.clone(), DocumentData::new(params.text_document.version))
673 tracing::error!("duplicate DidOpenTextDocument: {}", path)
678 .set_file_contents(path, Some(params.text_document.text.into_bytes()));
682 .on::<lsp_types::notification::DidChangeTextDocument>(|this, params| {
683 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
684 match this.mem_docs.get_mut(&path) {
686 // The version passed in DidChangeTextDocument is the version after all edits are applied
687 // so we should apply it before the vfs is notified.
688 doc.version = params.text_document.version;
691 tracing::error!("unexpected DidChangeTextDocument: {}", path);
696 let vfs = &mut this.vfs.write().0;
697 let file_id = vfs.file_id(&path).unwrap();
698 let mut text = String::from_utf8(vfs.file_contents(file_id).to_vec()).unwrap();
699 apply_document_changes(&mut text, params.content_changes);
701 vfs.set_file_contents(path, Some(text.into_bytes()));
705 .on::<lsp_types::notification::DidCloseTextDocument>(|this, params| {
706 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
707 if this.mem_docs.remove(&path).is_err() {
708 tracing::error!("orphan DidCloseTextDocument: {}", path);
711 this.semantic_tokens_cache.lock().remove(¶ms.text_document.uri);
713 if let Some(path) = path.as_path() {
714 this.loader.handle.invalidate(path.to_path_buf());
719 .on::<lsp_types::notification::DidSaveTextDocument>(|this, params| {
720 for flycheck in &this.flycheck {
723 if let Ok(abs_path) = from_proto::abs_path(¶ms.text_document.uri) {
724 if reload::should_refresh_for_change(&abs_path, ChangeKind::Modify) {
725 this.fetch_workspaces_queue
726 .request_op(format!("DidSaveTextDocument {}", abs_path.display()));
731 .on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| {
732 // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
733 // this notification's parameters should be ignored and the actual config queried separately.
734 this.send_request::<lsp_types::request::WorkspaceConfiguration>(
735 lsp_types::ConfigurationParams {
736 items: vec![lsp_types::ConfigurationItem {
738 section: Some("rust-analyzer".to_string()),
742 tracing::debug!("config update response: '{:?}", resp);
743 let lsp_server::Response { error, result, .. } = resp;
745 match (error, result) {
747 tracing::error!("failed to fetch the server settings: {:?}", err)
749 (None, Some(mut configs)) => {
750 if let Some(json) = configs.get_mut(0) {
751 // Note that json can be null according to the spec if the client can't
752 // provide a configuration. This is handled in Config::update below.
753 let mut config = Config::clone(&*this.config);
754 if let Err(error) = config.update(json.take()) {
756 lsp_types::MessageType::WARNING,
760 this.update_configuration(config);
763 (None, None) => tracing::error!(
764 "received empty server settings response from the client"
772 .on::<lsp_types::notification::DidChangeWatchedFiles>(|this, params| {
773 for change in params.changes {
774 if let Ok(path) = from_proto::abs_path(&change.uri) {
775 this.loader.handle.invalidate(path);
784 fn update_diagnostics(&mut self) {
785 let subscriptions = self
788 .map(|path| self.vfs.read().0.file_id(path).unwrap())
789 .collect::<Vec<_>>();
791 tracing::trace!("updating notifications for {:?}", subscriptions);
793 let snapshot = self.snapshot();
794 self.task_pool.handle.spawn(move || {
795 let diagnostics = subscriptions
797 .filter_map(|file_id| {
798 handlers::publish_diagnostics(&snapshot, file_id)
800 .map(|diags| (file_id, diags))
802 .collect::<Vec<_>>();
803 Task::Diagnostics(diagnostics)