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>((), |_, _| ());
374 if let Some(diagnostic_changes) = self.diagnostics.take_changes() {
375 for file_id in diagnostic_changes {
376 let url = file_id_to_url(&self.vfs.read().0, file_id);
377 let diagnostics = self.diagnostics.diagnostics_for(file_id).cloned().collect();
378 let version = from_proto::vfs_path(&url)
379 .map(|path| self.mem_docs.get(&path).map(|it| it.version))
380 .unwrap_or_default();
382 self.send_notification::<lsp_types::notification::PublishDiagnostics>(
383 lsp_types::PublishDiagnosticsParams { uri: url, diagnostics, version },
388 let loop_duration = loop_start.elapsed();
389 if loop_duration > Duration::from_millis(100) {
390 log::warn!("overly long loop turn: {:?}", loop_duration);
391 if env::var("RA_PROFILE").is_ok() {
393 lsp_types::MessageType::Error,
394 format!("overly long loop turn: {:?}", loop_duration),
401 fn on_request(&mut self, request_received: Instant, req: Request) -> Result<()> {
402 self.register_request(&req, request_received);
404 if self.shutdown_requested {
405 self.respond(Response::new_err(
407 lsp_server::ErrorCode::InvalidRequest as i32,
408 "Shutdown already requested.".to_owned(),
414 if self.status == Status::Loading && req.method != "shutdown" {
415 self.respond(lsp_server::Response::new_err(
417 // FIXME: i32 should impl From<ErrorCode> (from() guarantees lossless conversion)
418 lsp_server::ErrorCode::ContentModified as i32,
419 "Rust Analyzer is still loading...".to_owned(),
424 RequestDispatcher { req: Some(req), global_state: self }
425 .on_sync::<lsp_ext::ReloadWorkspace>(|s, ()| Ok(s.fetch_workspaces()))?
426 .on_sync::<lsp_ext::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
427 .on_sync::<lsp_ext::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
428 .on_sync::<lsp_types::request::Shutdown>(|s, ()| {
429 s.shutdown_requested = true;
432 .on_sync::<lsp_types::request::SelectionRangeRequest>(|s, p| {
433 handlers::handle_selection_range(s.snapshot(), p)
435 .on_sync::<lsp_ext::MatchingBrace>(|s, p| {
436 handlers::handle_matching_brace(s.snapshot(), p)
438 .on_sync::<lsp_ext::MemoryUsage>(|s, p| handlers::handle_memory_usage(s, p))?
439 .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)
440 .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)
441 .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)
442 .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)
443 .on::<lsp_ext::Runnables>(handlers::handle_runnables)
444 .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)
445 .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)
446 .on::<lsp_ext::CodeActionResolveRequest>(handlers::handle_code_action_resolve)
447 .on::<lsp_ext::HoverRequest>(handlers::handle_hover)
448 .on::<lsp_ext::ExternalDocs>(handlers::handle_open_docs)
449 .on::<lsp_ext::OpenCargoToml>(handlers::handle_open_cargo_toml)
450 .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)
451 .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)
452 .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)
453 .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)
454 .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)
455 .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)
456 .on::<lsp_types::request::Completion>(handlers::handle_completion)
457 .on::<lsp_types::request::ResolveCompletionItem>(handlers::handle_resolve_completion)
458 .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)
459 .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)
460 .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)
461 .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)
462 .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)
463 .on::<lsp_types::request::Rename>(handlers::handle_rename)
464 .on::<lsp_types::request::References>(handlers::handle_references)
465 .on::<lsp_types::request::Formatting>(handlers::handle_formatting)
466 .on::<lsp_types::request::DocumentHighlightRequest>(handlers::handle_document_highlight)
467 .on::<lsp_types::request::CallHierarchyPrepare>(handlers::handle_call_hierarchy_prepare)
468 .on::<lsp_types::request::CallHierarchyIncomingCalls>(
469 handlers::handle_call_hierarchy_incoming,
471 .on::<lsp_types::request::CallHierarchyOutgoingCalls>(
472 handlers::handle_call_hierarchy_outgoing,
474 .on::<lsp_types::request::SemanticTokensFullRequest>(
475 handlers::handle_semantic_tokens_full,
477 .on::<lsp_types::request::SemanticTokensFullDeltaRequest>(
478 handlers::handle_semantic_tokens_full_delta,
480 .on::<lsp_types::request::SemanticTokensRangeRequest>(
481 handlers::handle_semantic_tokens_range,
483 .on::<lsp_ext::Ssr>(handlers::handle_ssr)
487 fn on_notification(&mut self, not: Notification) -> Result<()> {
488 NotificationDispatcher { not: Some(not), global_state: self }
489 .on::<lsp_types::notification::Cancel>(|this, params| {
490 let id: lsp_server::RequestId = match params.id {
491 lsp_types::NumberOrString::Number(id) => id.into(),
492 lsp_types::NumberOrString::String(id) => id.into(),
497 .on::<lsp_types::notification::DidOpenTextDocument>(|this, params| {
498 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
501 .insert(path.clone(), DocumentData::new(params.text_document.version))
504 log::error!("duplicate DidOpenTextDocument: {}", path)
509 .set_file_contents(path, Some(params.text_document.text.into_bytes()));
510 this.maybe_update_diagnostics();
514 .on::<lsp_types::notification::DidChangeTextDocument>(|this, params| {
515 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
516 let doc = match this.mem_docs.get_mut(&path) {
519 log::error!("expected DidChangeTextDocument: {}", path);
523 let vfs = &mut this.vfs.write().0;
524 let file_id = vfs.file_id(&path).unwrap();
525 let mut text = String::from_utf8(vfs.file_contents(file_id).to_vec()).unwrap();
526 apply_document_changes(&mut text, params.content_changes);
528 // The version passed in DidChangeTextDocument is the version after all edits are applied
529 // so we should apply it before the vfs is notified.
530 doc.version = params.text_document.version;
532 vfs.set_file_contents(path.clone(), Some(text.into_bytes()));
536 .on::<lsp_types::notification::DidCloseTextDocument>(|this, params| {
537 let mut version = None;
538 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
539 match this.mem_docs.remove(&path) {
540 Some(doc) => version = Some(doc.version),
541 None => log::error!("orphan DidCloseTextDocument: {}", path),
544 this.semantic_tokens_cache.lock().remove(¶ms.text_document.uri);
546 if let Some(path) = path.as_path() {
547 this.loader.handle.invalidate(path.to_path_buf());
551 // Clear the diagnostics for the previously known version of the file.
552 // This prevents stale "cargo check" diagnostics if the file is
553 // closed, "cargo check" is run and then the file is reopened.
554 this.send_notification::<lsp_types::notification::PublishDiagnostics>(
555 lsp_types::PublishDiagnosticsParams {
556 uri: params.text_document.uri,
557 diagnostics: Vec::new(),
563 .on::<lsp_types::notification::DidSaveTextDocument>(|this, params| {
564 for flycheck in &this.flycheck {
567 if let Ok(abs_path) = from_proto::abs_path(¶ms.text_document.uri) {
568 this.maybe_refresh(&[(abs_path, ChangeKind::Modify)]);
572 .on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| {
573 // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
574 // this notification's parameters should be ignored and the actual config queried separately.
575 this.send_request::<lsp_types::request::WorkspaceConfiguration>(
576 lsp_types::ConfigurationParams {
577 items: vec![lsp_types::ConfigurationItem {
579 section: Some("rust-analyzer".to_string()),
583 log::debug!("config update response: '{:?}", resp);
584 let Response { error, result, .. } = resp;
586 match (error, result) {
588 log::error!("failed to fetch the server settings: {:?}", err)
590 (None, Some(mut configs)) => {
591 if let Some(json) = configs.get_mut(0) {
592 // Note that json can be null according to the spec if the client can't
593 // provide a configuration. This is handled in Config::update below.
594 let mut config = this.config.clone();
595 config.update(json.take());
596 this.update_configuration(config);
599 (None, None) => log::error!(
600 "received empty server settings response from the client"
608 .on::<lsp_types::notification::DidChangeWatchedFiles>(|this, params| {
609 for change in params.changes {
610 if let Ok(path) = from_proto::abs_path(&change.uri) {
611 this.loader.handle.invalidate(path);
619 fn update_file_notifications_on_threadpool(&mut self) {
620 self.maybe_update_diagnostics();
621 self.task_pool.handle.spawn_with_sender({
622 let snap = self.snapshot();
625 .prime_caches(|progress| {
626 sender.send(Task::PrimeCaches(progress)).unwrap();
628 .unwrap_or_else(|_: Canceled| {
629 // Pretend that we're done, so that the progress bar is removed. Otherwise
630 // the editor may complain about it already existing.
631 sender.send(Task::PrimeCaches(PrimeCachesProgress::Finished)).unwrap()
636 fn maybe_update_diagnostics(&mut self) {
637 let subscriptions = self
640 .map(|path| self.vfs.read().0.file_id(&path).unwrap())
641 .collect::<Vec<_>>();
643 log::trace!("updating notifications for {:?}", subscriptions);
644 if self.config.publish_diagnostics {
645 let snapshot = self.snapshot();
646 let subscriptions = subscriptions.clone();
647 self.task_pool.handle.spawn(move || {
648 let diagnostics = subscriptions
650 .filter_map(|file_id| {
651 handlers::publish_diagnostics(&snapshot, file_id)
653 if !is_canceled(&*err) {
654 log::error!("failed to compute diagnostics: {:?}", err);
659 .map(|diags| (file_id, diags))
661 .collect::<Vec<_>>();
662 Task::Diagnostics(diagnostics)