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 crossbeam_channel::{select, Receiver};
10 use lsp_server::{Connection, Notification, Request, Response};
11 use lsp_types::{notification::Notification as _, DidChangeTextDocumentParams};
13 use ra_ide::{Canceled, FileId};
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},
26 use ra_project_model::ProjectWorkspace;
29 pub fn main_loop(config: Config, connection: Connection) -> Result<()> {
30 log::info!("initial config: {:#?}", config);
32 // Windows scheduler implements priority boosts: if thread waits for an
33 // event (like a condvar), and event fires, priority of the thread is
34 // temporary bumped. This optimization backfires in our case: each time the
35 // `main_loop` schedules a task to run on a threadpool, the worker threads
36 // gets a higher priority, and (on a machine with fewer cores) displaces the
37 // main loop! We work-around this by marking the main loop as a
38 // higher-priority thread.
40 // https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities
41 // https://docs.microsoft.com/en-us/windows/win32/procthread/priority-boosts
42 // https://github.com/rust-analyzer/rust-analyzer/issues/2835
45 use winapi::um::processthreadsapi::*;
46 let thread = GetCurrentThread();
47 let thread_priority_above_normal = 1;
48 SetThreadPriority(thread, thread_priority_above_normal);
51 GlobalState::new(connection.sender.clone(), config).run(connection.receiver)
55 Lsp(lsp_server::Message),
57 Vfs(vfs::loader::Message),
58 Flycheck(flycheck::Message),
62 pub(crate) enum Task {
64 Diagnostics(Vec<(FileId, Vec<lsp_types::Diagnostic>)>),
65 Workspaces(Vec<anyhow::Result<ProjectWorkspace>>),
69 impl fmt::Debug for Event {
70 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
71 let debug_verbose_not = |not: &Notification, f: &mut fmt::Formatter| {
72 f.debug_struct("Notification").field("method", ¬.method).finish()
76 Event::Lsp(lsp_server::Message::Notification(not)) => {
77 if notification_is::<lsp_types::notification::DidOpenTextDocument>(not)
78 || notification_is::<lsp_types::notification::DidChangeTextDocument>(not)
80 return debug_verbose_not(not, f);
83 Event::Task(Task::Response(resp)) => {
85 .debug_struct("Response")
86 .field("id", &resp.id)
87 .field("error", &resp.error)
93 Event::Lsp(it) => fmt::Debug::fmt(it, f),
94 Event::Task(it) => fmt::Debug::fmt(it, f),
95 Event::Vfs(it) => fmt::Debug::fmt(it, f),
96 Event::Flycheck(it) => fmt::Debug::fmt(it, f),
102 fn run(mut self, inbox: Receiver<lsp_server::Message>) -> Result<()> {
103 if self.config.linked_projects.is_empty() && self.config.notifications.cargo_toml_not_found
106 lsp_types::MessageType::Error,
107 "rust-analyzer failed to discover workspace".to_string(),
111 let save_registration_options = lsp_types::TextDocumentSaveRegistrationOptions {
112 include_text: Some(false),
113 text_document_registration_options: lsp_types::TextDocumentRegistrationOptions {
114 document_selector: Some(vec![
115 lsp_types::DocumentFilter {
118 pattern: Some("**/*.rs".into()),
120 lsp_types::DocumentFilter {
123 pattern: Some("**/Cargo.toml".into()),
125 lsp_types::DocumentFilter {
128 pattern: Some("**/Cargo.lock".into()),
134 let registration = lsp_types::Registration {
135 id: "textDocument/didSave".to_string(),
136 method: "textDocument/didSave".to_string(),
137 register_options: Some(serde_json::to_value(save_registration_options).unwrap()),
139 self.send_request::<lsp_types::request::RegisterCapability>(
140 lsp_types::RegistrationParams { registrations: vec![registration] },
144 self.fetch_workspaces();
146 while let Some(event) = self.next_event(&inbox) {
147 if let Event::Lsp(lsp_server::Message::Notification(not)) = &event {
148 if not.method == lsp_types::notification::Exit::METHOD {
152 self.handle_event(event)?
155 Err("client exited without proper shutdown sequence")?
158 fn next_event(&self, inbox: &Receiver<lsp_server::Message>) -> Option<Event> {
160 recv(inbox) -> msg =>
161 msg.ok().map(Event::Lsp),
163 recv(self.task_pool.receiver) -> task =>
164 Some(Event::Task(task.unwrap())),
166 recv(self.loader.receiver) -> task =>
167 Some(Event::Vfs(task.unwrap())),
169 recv(self.flycheck_receiver) -> task =>
170 Some(Event::Flycheck(task.unwrap())),
174 fn handle_event(&mut self, event: Event) -> Result<()> {
175 let loop_start = Instant::now();
176 // NOTE: don't count blocking select! call as a loop-turn time
177 let _p = profile("GlobalState::handle_event");
179 log::info!("handle_event({:?})", event);
180 let queue_count = self.task_pool.handle.len();
182 log::info!("queued count = {}", queue_count);
185 let prev_status = self.status;
187 Event::Lsp(msg) => match msg {
188 lsp_server::Message::Request(req) => self.on_request(loop_start, req)?,
189 lsp_server::Message::Notification(not) => {
190 self.on_notification(not)?;
192 lsp_server::Message::Response(resp) => self.complete_request(resp),
194 Event::Task(task) => {
196 Task::Response(response) => self.respond(response),
197 Task::Diagnostics(diagnostics_per_file) => {
198 for (file_id, diagnostics) in diagnostics_per_file {
199 self.diagnostics.set_native_diagnostics(file_id, diagnostics)
202 Task::Workspaces(workspaces) => self.switch_workspaces(workspaces),
205 self.analysis_host.maybe_collect_garbage();
207 Event::Vfs(mut task) => {
208 let _p = profile("GlobalState::handle_event/vfs");
211 vfs::loader::Message::Loaded { files } => {
212 let vfs = &mut self.vfs.write().0;
213 for (path, contents) in files {
214 let path = VfsPath::from(path);
215 if !self.mem_docs.contains_key(&path) {
216 vfs.set_file_contents(path, contents)
220 vfs::loader::Message::Progress { n_total, n_done } => {
222 self.transition(Status::Invalid);
224 let state = if n_done == 0 {
225 self.transition(Status::Loading);
227 } else if n_done < n_total {
230 assert_eq!(n_done, n_total);
231 self.transition(Status::Ready);
234 self.report_progress(
237 Some(format!("{}/{}", n_done, n_total)),
238 Some(Progress::percentage(n_done, n_total)),
243 // Coalesce many VFS event into a single loop turn
244 task = match self.loader.receiver.try_recv() {
250 Event::Flycheck(task) => match task {
251 flycheck::Message::AddDiagnostic { workspace_root, diagnostic } => {
252 let diagnostics = crate::diagnostics::to_proto::map_rust_diagnostic_to_lsp(
253 &self.config.diagnostics,
257 for diag in diagnostics {
258 match url_to_file_id(&self.vfs.read().0, &diag.url) {
259 Ok(file_id) => self.diagnostics.add_check_diagnostic(
265 log::error!("File with cargo diagnostic not found in VFS: {}", err);
271 flycheck::Message::Progress(status) => {
272 let (state, message) = match status {
273 flycheck::Progress::DidStart => {
274 self.diagnostics.clear_check();
275 (Progress::Begin, None)
277 flycheck::Progress::DidCheckCrate(target) => {
278 (Progress::Report, Some(target))
280 flycheck::Progress::DidCancel => (Progress::End, None),
281 flycheck::Progress::DidFinish(result) => {
282 if let Err(err) = result {
283 log::error!("cargo check failed: {}", err)
285 (Progress::End, None)
289 self.report_progress("cargo check", state, message, None);
294 let state_changed = self.process_changes();
295 if prev_status == Status::Loading && self.status == Status::Ready {
296 if let Some(flycheck) = &self.flycheck {
301 if self.status == Status::Ready && (state_changed || prev_status == Status::Loading) {
302 let subscriptions = self
305 .map(|path| self.vfs.read().0.file_id(&path).unwrap())
306 .collect::<Vec<_>>();
308 self.update_file_notifications_on_threadpool(subscriptions);
311 if let Some(diagnostic_changes) = self.diagnostics.take_changes() {
312 for file_id in diagnostic_changes {
313 let url = file_id_to_url(&self.vfs.read().0, file_id);
314 let diagnostics = self.diagnostics.diagnostics_for(file_id).cloned().collect();
315 let version = from_proto::vfs_path(&url)
316 .map(|path| self.mem_docs.get(&path)?.version)
317 .unwrap_or_default();
319 self.send_notification::<lsp_types::notification::PublishDiagnostics>(
320 lsp_types::PublishDiagnosticsParams { uri: url, diagnostics, version },
325 let loop_duration = loop_start.elapsed();
326 if loop_duration > Duration::from_millis(100) {
327 log::warn!("overly long loop turn: {:?}", loop_duration);
328 if env::var("RA_PROFILE").is_ok() {
330 lsp_types::MessageType::Error,
331 format!("overly long loop turn: {:?}", loop_duration),
338 fn on_request(&mut self, request_received: Instant, req: Request) -> Result<()> {
339 self.register_request(&req, request_received);
341 RequestDispatcher { req: Some(req), global_state: self }
342 .on_sync::<lsp_ext::ReloadWorkspace>(|s, ()| Ok(s.fetch_workspaces()))?
343 .on_sync::<lsp_ext::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
344 .on_sync::<lsp_ext::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
345 .on_sync::<lsp_types::request::Shutdown>(|_, ()| Ok(()))?
346 .on_sync::<lsp_types::request::SelectionRangeRequest>(|s, p| {
347 handlers::handle_selection_range(s.snapshot(), p)
349 .on_sync::<lsp_ext::MatchingBrace>(|s, p| {
350 handlers::handle_matching_brace(s.snapshot(), p)
352 .on_sync::<lsp_ext::MemoryUsage>(|s, p| handlers::handle_memory_usage(s, p))?
353 .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)?
354 .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)?
355 .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)?
356 .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)?
357 .on::<lsp_ext::Runnables>(handlers::handle_runnables)?
358 .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)?
359 .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)?
360 .on::<lsp_ext::ResolveCodeActionRequest>(handlers::handle_resolve_code_action)?
361 .on::<lsp_ext::HoverRequest>(handlers::handle_hover)?
362 .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)?
363 .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)?
364 .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)?
365 .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)?
366 .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)?
367 .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)?
368 .on::<lsp_types::request::Completion>(handlers::handle_completion)?
369 .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)?
370 .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)?
371 .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)?
372 .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)?
373 .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)?
374 .on::<lsp_types::request::Rename>(handlers::handle_rename)?
375 .on::<lsp_types::request::References>(handlers::handle_references)?
376 .on::<lsp_types::request::Formatting>(handlers::handle_formatting)?
377 .on::<lsp_types::request::DocumentHighlightRequest>(
378 handlers::handle_document_highlight,
380 .on::<lsp_types::request::CallHierarchyPrepare>(
381 handlers::handle_call_hierarchy_prepare,
383 .on::<lsp_types::request::CallHierarchyIncomingCalls>(
384 handlers::handle_call_hierarchy_incoming,
386 .on::<lsp_types::request::CallHierarchyOutgoingCalls>(
387 handlers::handle_call_hierarchy_outgoing,
389 .on::<lsp_types::request::SemanticTokensRequest>(handlers::handle_semantic_tokens)?
390 .on::<lsp_types::request::SemanticTokensEditsRequest>(
391 handlers::handle_semantic_tokens_edits,
393 .on::<lsp_types::request::SemanticTokensRangeRequest>(
394 handlers::handle_semantic_tokens_range,
396 .on::<lsp_ext::Ssr>(handlers::handle_ssr)?
400 fn on_notification(&mut self, not: Notification) -> Result<()> {
401 NotificationDispatcher { not: Some(not), global_state: self }
402 .on::<lsp_types::notification::Cancel>(|this, params| {
403 let id: lsp_server::RequestId = match params.id {
404 lsp_types::NumberOrString::Number(id) => id.into(),
405 lsp_types::NumberOrString::String(id) => id.into(),
410 .on::<lsp_types::notification::DidOpenTextDocument>(|this, params| {
411 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
414 .insert(path.clone(), DocumentData::new(params.text_document.version))
417 log::error!("duplicate DidOpenTextDocument: {}", path)
422 .set_file_contents(path, Some(params.text_document.text.into_bytes()));
426 .on::<lsp_types::notification::DidChangeTextDocument>(|this, params| {
427 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
428 let DidChangeTextDocumentParams { text_document, content_changes } = params;
429 let vfs = &mut this.vfs.write().0;
430 let world = this.snapshot();
431 let file_id = vfs.file_id(&path).unwrap();
433 // let file_id = vfs.file_id(&path).unwrap();
434 let mut text = String::from_utf8(vfs.file_contents(file_id).to_vec()).unwrap();
435 let line_index = world.analysis.file_line_index(file_id)?;
436 apply_document_changes(&mut text, content_changes, Cow::Borrowed(&line_index));
438 // The version passed in DidChangeTextDocument is the version after all edits are applied
439 // so we should apply it before the vfs is notified.
440 let doc = this.mem_docs.get_mut(&path).unwrap();
441 doc.version = text_document.version;
443 vfs.set_file_contents(path.clone(), Some(text.into_bytes()));
447 .on::<lsp_types::notification::DidCloseTextDocument>(|this, params| {
448 let mut version = None;
449 if let Ok(path) = from_proto::vfs_path(¶ms.text_document.uri) {
450 match this.mem_docs.remove(&path) {
451 Some(doc) => version = doc.version,
452 None => log::error!("orphan DidCloseTextDocument: {}", path),
455 this.semantic_tokens_cache.lock().unwrap().remove(¶ms.text_document.uri);
457 if let Some(path) = path.as_path() {
458 this.loader.handle.invalidate(path.to_path_buf());
462 // Clear the diagnostics for the previously known version of the file.
463 // This prevents stale "cargo check" diagnostics if the file is
464 // closed, "cargo check" is run and then the file is reopened.
465 this.send_notification::<lsp_types::notification::PublishDiagnostics>(
466 lsp_types::PublishDiagnosticsParams {
467 uri: params.text_document.uri,
468 diagnostics: Vec::new(),
474 .on::<lsp_types::notification::DidSaveTextDocument>(|this, params| {
475 if let Some(flycheck) = &this.flycheck {
478 if let Ok(abs_path) = from_proto::abs_path(¶ms.text_document.uri) {
479 this.maybe_refresh(&[(abs_path, ChangeKind::Modify)]);
483 .on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| {
484 // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
485 // this notification's parameters should be ignored and the actual config queried separately.
486 this.send_request::<lsp_types::request::WorkspaceConfiguration>(
487 lsp_types::ConfigurationParams {
488 items: vec![lsp_types::ConfigurationItem {
490 section: Some("rust-analyzer".to_string()),
494 log::debug!("config update response: '{:?}", resp);
495 let Response { error, result, .. } = resp;
497 match (error, result) {
499 log::error!("failed to fetch the server settings: {:?}", err)
501 (None, Some(mut configs)) => {
502 if let Some(json) = configs.get_mut(0) {
503 // Note that json can be null according to the spec if the client can't
504 // provide a configuration. This is handled in Config::update below.
505 let mut config = this.config.clone();
506 config.update(json.take());
507 this.update_configuration(config);
510 (None, None) => log::error!(
511 "received empty server settings response from the client"
519 .on::<lsp_types::notification::DidChangeWatchedFiles>(|this, params| {
520 for change in params.changes {
521 if let Ok(path) = from_proto::abs_path(&change.uri) {
522 this.loader.handle.invalidate(path);
530 fn update_file_notifications_on_threadpool(&mut self, subscriptions: Vec<FileId>) {
531 log::trace!("updating notifications for {:?}", subscriptions);
532 if self.config.publish_diagnostics {
533 let snapshot = self.snapshot();
534 let subscriptions = subscriptions.clone();
535 self.task_pool.handle.spawn(move || {
536 let diagnostics = subscriptions
538 .filter_map(|file_id| {
539 handlers::publish_diagnostics(&snapshot, file_id)
541 if !is_canceled(&*err) {
542 log::error!("failed to compute diagnostics: {:?}", err);
547 .map(|diags| (file_id, diags))
549 .collect::<Vec<_>>();
550 Task::Diagnostics(diagnostics)
553 self.task_pool.handle.spawn({
554 let subs = subscriptions;
555 let snap = self.snapshot();
557 snap.analysis.prime_caches(subs).unwrap_or_else(|_: Canceled| ());