1 //! The main loop of `ra_lsp_server` responsible for dispatching LSP requests/replies and
2 //! notifications back to the client.
6 pub(crate) mod pending_requests;
8 use std::{error::Error, fmt, panic, path::PathBuf, sync::Arc, time::Instant};
10 use crossbeam_channel::{select, unbounded, RecvError, Sender};
11 use lsp_server::{Connection, ErrorCode, Message, Notification, Request, RequestId, Response};
12 use lsp_types::{ClientCapabilities, NumberOrString};
13 use ra_ide::{Canceled, FeatureFlags, FileId, LibraryData, SourceRootId};
15 use ra_vfs::{VfsTask, Watch};
16 use relative_path::RelativePathBuf;
17 use rustc_hash::FxHashSet;
18 use serde::{de::DeserializeOwned, Serialize};
19 use threadpool::ThreadPool;
22 cargo_check::CheckTask,
24 pending_requests::{PendingRequest, PendingRequests},
25 subscriptions::Subscriptions,
28 world::{Options, WorldSnapshot, WorldState},
32 const THREADPOOL_SIZE: usize = 8;
33 const MAX_IN_FLIGHT_LIBS: usize = THREADPOOL_SIZE - 3;
42 pub fn new(code: i32, message: String) -> LspError {
43 LspError { code, message }
47 impl fmt::Display for LspError {
48 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
49 write!(f, "Language Server request failed with {}. ({})", self.code, self.message)
53 impl Error for LspError {}
56 ws_roots: Vec<PathBuf>,
57 client_caps: ClientCapabilities,
59 connection: Connection,
61 log::info!("server_config: {:#?}", config);
63 let mut loop_state = LoopState::default();
64 let mut world_state = {
65 // FIXME: support dynamic workspace loading.
67 let mut loaded_workspaces = Vec::new();
68 for ws_root in &ws_roots {
69 let workspace = ra_project_model::ProjectWorkspace::discover_with_sysroot(
72 &config.cargo_features,
75 Ok(workspace) => loaded_workspaces.push(workspace),
77 log::error!("loading workspace failed: {}", e);
80 req::MessageType::Error,
81 format!("rust-analyzer failed to load workspace: {}", e),
93 .map(|glob| ra_vfs_glob::Glob::new(glob))
94 .collect::<std::result::Result<Vec<_>, _>>()?;
96 if config.use_client_watching {
97 let registration_options = req::DidChangeWatchedFilesRegistrationOptions {
100 .flat_map(|ws| ws.to_roots())
101 .filter(|root| root.is_member())
102 .map(|root| format!("{}/**/*.rs", root.path().display()))
103 .map(|glob_pattern| req::FileSystemWatcher { glob_pattern, kind: None })
106 let registration = req::Registration {
107 id: "file-watcher".to_string(),
108 method: "workspace/didChangeWatchedFiles".to_string(),
109 register_options: Some(serde_json::to_value(registration_options).unwrap()),
111 let params = req::RegistrationParams { registrations: vec![registration] };
113 request_new::<req::RegisterCapability>(loop_state.next_request_id(), params);
114 connection.sender.send(request.into()).unwrap();
118 let text_document_caps = client_caps.text_document.as_ref();
120 publish_decorations: config.publish_decorations,
121 supports_location_link: text_document_caps
122 .and_then(|it| it.definition)
123 .and_then(|it| it.link_support)
125 line_folding_only: text_document_caps
126 .and_then(|it| it.folding_range.as_ref())
127 .and_then(|it| it.line_folding_only)
129 max_inlay_hint_length: config.max_inlay_hint_length,
130 cargo_check_enable: config.cargo_check_enable,
131 cargo_check_command: config.cargo_check_command,
132 cargo_check_args: config.cargo_check_args,
136 let feature_flags = {
137 let mut ff = FeatureFlags::default();
138 for (flag, value) in config.feature_flags {
139 if ff.set(flag.as_str(), value).is_err() {
140 log::error!("unknown feature flag: {:?}", flag);
142 req::MessageType::Error,
143 format!("unknown feature flag: {:?}", flag),
150 log::info!("feature_flags: {:#?}", feature_flags);
157 Watch(!config.use_client_watching),
163 let pool = ThreadPool::new(THREADPOOL_SIZE);
164 let (task_sender, task_receiver) = unbounded::<Task>();
165 let (libdata_sender, libdata_receiver) = unbounded::<LibraryData>();
167 log::info!("server initialized, serving requests");
169 let task_sender = task_sender;
170 let libdata_sender = libdata_sender;
172 log::trace!("selecting");
173 let event = select! {
174 recv(&connection.receiver) -> msg => match msg {
175 Ok(msg) => Event::Msg(msg),
176 Err(RecvError) => Err("client exited without shutdown")?,
178 recv(task_receiver) -> task => Event::Task(task.unwrap()),
179 recv(world_state.task_receiver) -> task => match task {
180 Ok(task) => Event::Vfs(task),
181 Err(RecvError) => Err("vfs died")?,
183 recv(libdata_receiver) -> data => Event::Lib(data.unwrap()),
184 recv(world_state.check_watcher.task_recv) -> task => Event::CheckWatcher(task.unwrap())
186 if let Event::Msg(Message::Request(req)) = &event {
187 if connection.handle_shutdown(&req)? {
203 log::info!("waiting for tasks to finish...");
204 task_receiver.into_iter().for_each(|task| {
205 on_task(task, &connection.sender, &mut loop_state.pending_requests, &mut world_state)
207 libdata_receiver.into_iter().for_each(drop);
208 log::info!("...tasks have finished");
209 log::info!("joining threadpool...");
211 log::info!("...threadpool has finished");
213 let vfs = Arc::try_unwrap(world_state.vfs).expect("all snapshots should be dead");
222 Notify(Notification),
230 CheckWatcher(CheckTask),
233 impl fmt::Debug for Event {
234 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
235 let debug_verbose_not = |not: &Notification, f: &mut fmt::Formatter| {
236 f.debug_struct("Notification").field("method", ¬.method).finish()
240 Event::Msg(Message::Notification(not)) => {
241 if notification_is::<req::DidOpenTextDocument>(not)
242 || notification_is::<req::DidChangeTextDocument>(not)
244 return debug_verbose_not(not, f);
247 Event::Task(Task::Notify(not)) => {
248 if notification_is::<req::PublishDecorations>(not)
249 || notification_is::<req::PublishDiagnostics>(not)
251 return debug_verbose_not(not, f);
254 Event::Task(Task::Respond(resp)) => {
256 .debug_struct("Response")
257 .field("id", &resp.id)
258 .field("error", &resp.error)
264 Event::Msg(it) => fmt::Debug::fmt(it, f),
265 Event::Task(it) => fmt::Debug::fmt(it, f),
266 Event::Vfs(it) => fmt::Debug::fmt(it, f),
267 Event::Lib(it) => fmt::Debug::fmt(it, f),
268 Event::CheckWatcher(it) => fmt::Debug::fmt(it, f),
273 #[derive(Debug, Default)]
275 next_request_id: u64,
276 pending_responses: FxHashSet<RequestId>,
277 pending_requests: PendingRequests,
278 subscriptions: Subscriptions,
279 // We try not to index more than MAX_IN_FLIGHT_LIBS libraries at the same
280 // time to always have a thread ready to react to input.
281 in_flight_libraries: usize,
282 pending_libraries: Vec<(SourceRootId, Vec<(FileId, RelativePathBuf, Arc<String>)>)>,
283 workspace_loaded: bool,
287 fn next_request_id(&mut self) -> RequestId {
288 self.next_request_id += 1;
289 let res: RequestId = self.next_request_id.into();
290 let inserted = self.pending_responses.insert(res.clone());
298 task_sender: &Sender<Task>,
299 libdata_sender: &Sender<LibraryData>,
300 connection: &Connection,
301 world_state: &mut WorldState,
302 loop_state: &mut LoopState,
305 let loop_start = Instant::now();
307 // NOTE: don't count blocking select! call as a loop-turn time
308 let _p = profile("main_loop_inner/loop-turn");
309 log::info!("loop turn = {:?}", event);
310 let queue_count = pool.queued_count();
312 log::info!("queued count = {}", queue_count);
316 Event::Task(task) => {
317 on_task(task, &connection.sender, &mut loop_state.pending_requests, world_state);
318 world_state.maybe_collect_garbage();
320 Event::Vfs(task) => {
321 world_state.vfs.write().handle_task(task);
324 world_state.add_lib(lib);
325 world_state.maybe_collect_garbage();
326 loop_state.in_flight_libraries -= 1;
328 Event::CheckWatcher(task) => match task {
329 CheckTask::Update(uri) => {
330 // We manually send a diagnostic update when the watcher asks
331 // us to, to avoid the issue of having to change the file to
332 // receive updated diagnostics.
333 let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?;
334 if let Some(file_id) = world_state.vfs.read().path2file(&path) {
336 handlers::publish_diagnostics(&world_state.snapshot(), FileId(file_id.0))?;
337 let not = notification_new::<req::PublishDiagnostics>(params);
338 task_sender.send(Task::Notify(not)).unwrap();
342 Event::Msg(msg) => match msg {
343 Message::Request(req) => on_request(
345 &mut loop_state.pending_requests,
352 Message::Notification(not) => {
356 &mut loop_state.pending_requests,
357 &mut loop_state.subscriptions,
361 Message::Response(resp) => {
362 let removed = loop_state.pending_responses.remove(&resp.id);
364 log::error!("unexpected response: {:?}", resp)
370 let mut state_changed = false;
371 if let Some(changes) = world_state.process_changes() {
372 state_changed = true;
373 loop_state.pending_libraries.extend(changes);
376 while loop_state.in_flight_libraries < MAX_IN_FLIGHT_LIBS
377 && !loop_state.pending_libraries.is_empty()
379 let (root, files) = loop_state.pending_libraries.pop().unwrap();
380 loop_state.in_flight_libraries += 1;
381 let sender = libdata_sender.clone();
382 pool.execute(move || {
383 log::info!("indexing {:?} ... ", root);
384 let _p = profile(&format!("indexed {:?}", root));
385 let data = LibraryData::prepare(root, files);
386 sender.send(data).unwrap();
390 if !loop_state.workspace_loaded
391 && world_state.roots_to_scan == 0
392 && loop_state.pending_libraries.is_empty()
393 && loop_state.in_flight_libraries == 0
395 loop_state.workspace_loaded = true;
396 let n_packages: usize = world_state.workspaces.iter().map(|it| it.n_packages()).sum();
397 if world_state.feature_flags().get("notifications.workspace-loaded") {
398 let msg = format!("workspace loaded, {} rust packages", n_packages);
399 show_message(req::MessageType::Info, msg, &connection.sender);
404 update_file_notifications_on_threadpool(
406 world_state.snapshot(),
407 world_state.options.publish_decorations,
409 loop_state.subscriptions.subscriptions(),
417 msg_sender: &Sender<Message>,
418 pending_requests: &mut PendingRequests,
419 state: &mut WorldState,
422 Task::Respond(response) => {
423 if let Some(completed) = pending_requests.finish(&response.id) {
424 log::info!("handled req#{} in {:?}", completed.id, completed.duration);
425 state.complete_request(completed);
426 msg_sender.send(response.into()).unwrap();
430 msg_sender.send(n.into()).unwrap();
436 world: &mut WorldState,
437 pending_requests: &mut PendingRequests,
439 sender: &Sender<Task>,
440 msg_sender: &Sender<Message>,
441 request_received: Instant,
444 let mut pool_dispatcher = PoolDispatcher {
454 .on_sync::<req::CollectGarbage>(|s, ()| Ok(s.collect_garbage()))?
455 .on_sync::<req::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
456 .on_sync::<req::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
457 .on_sync::<req::SelectionRangeRequest>(|s, p| {
458 handlers::handle_selection_range(s.snapshot(), p)
460 .on_sync::<req::FindMatchingBrace>(|s, p| {
461 handlers::handle_find_matching_brace(s.snapshot(), p)
463 .on::<req::AnalyzerStatus>(handlers::handle_analyzer_status)?
464 .on::<req::SyntaxTree>(handlers::handle_syntax_tree)?
465 .on::<req::ExpandMacro>(handlers::handle_expand_macro)?
466 .on::<req::OnTypeFormatting>(handlers::handle_on_type_formatting)?
467 .on::<req::DocumentSymbolRequest>(handlers::handle_document_symbol)?
468 .on::<req::WorkspaceSymbol>(handlers::handle_workspace_symbol)?
469 .on::<req::GotoDefinition>(handlers::handle_goto_definition)?
470 .on::<req::GotoImplementation>(handlers::handle_goto_implementation)?
471 .on::<req::GotoTypeDefinition>(handlers::handle_goto_type_definition)?
472 .on::<req::ParentModule>(handlers::handle_parent_module)?
473 .on::<req::Runnables>(handlers::handle_runnables)?
474 .on::<req::DecorationsRequest>(handlers::handle_decorations)?
475 .on::<req::Completion>(handlers::handle_completion)?
476 .on::<req::CodeActionRequest>(handlers::handle_code_action)?
477 .on::<req::CodeLensRequest>(handlers::handle_code_lens)?
478 .on::<req::CodeLensResolve>(handlers::handle_code_lens_resolve)?
479 .on::<req::FoldingRangeRequest>(handlers::handle_folding_range)?
480 .on::<req::SignatureHelpRequest>(handlers::handle_signature_help)?
481 .on::<req::HoverRequest>(handlers::handle_hover)?
482 .on::<req::PrepareRenameRequest>(handlers::handle_prepare_rename)?
483 .on::<req::Rename>(handlers::handle_rename)?
484 .on::<req::References>(handlers::handle_references)?
485 .on::<req::Formatting>(handlers::handle_formatting)?
486 .on::<req::DocumentHighlightRequest>(handlers::handle_document_highlight)?
487 .on::<req::InlayHints>(handlers::handle_inlay_hints)?
493 msg_sender: &Sender<Message>,
494 state: &mut WorldState,
495 pending_requests: &mut PendingRequests,
496 subs: &mut Subscriptions,
499 let not = match notification_cast::<req::Cancel>(not) {
501 let id: RequestId = match params.id {
502 NumberOrString::Number(id) => id.into(),
503 NumberOrString::String(id) => id.into(),
505 if pending_requests.cancel(&id) {
506 let response = Response::new_err(
508 ErrorCode::RequestCanceled as i32,
509 "canceled by client".to_string(),
511 msg_sender.send(response.into()).unwrap()
517 let not = match notification_cast::<req::DidOpenTextDocument>(not) {
519 let uri = params.text_document.uri;
520 let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?;
521 if let Some(file_id) =
522 state.vfs.write().add_file_overlay(&path, params.text_document.text)
524 subs.add_sub(FileId(file_id.0));
530 let not = match notification_cast::<req::DidChangeTextDocument>(not) {
532 let uri = params.text_document.uri;
533 let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?;
535 params.content_changes.pop().ok_or_else(|| "empty changes".to_string())?.text;
536 state.vfs.write().change_file_overlay(path.as_path(), text);
541 let not = match notification_cast::<req::DidSaveTextDocument>(not) {
543 state.check_watcher.update();
548 let not = match notification_cast::<req::DidCloseTextDocument>(not) {
550 let uri = params.text_document.uri;
551 let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?;
552 if let Some(file_id) = state.vfs.write().remove_file_overlay(path.as_path()) {
553 subs.remove_sub(FileId(file_id.0));
556 req::PublishDiagnosticsParams { uri, diagnostics: Vec::new(), version: None };
557 let not = notification_new::<req::PublishDiagnostics>(params);
558 msg_sender.send(not.into()).unwrap();
563 let not = match notification_cast::<req::DidChangeConfiguration>(not) {
569 let not = match notification_cast::<req::DidChangeWatchedFiles>(not) {
571 let mut vfs = state.vfs.write();
572 for change in params.changes {
573 let uri = change.uri;
574 let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?;
575 vfs.notify_changed(path)
581 log::error!("unhandled notification: {:?}", not);
585 struct PoolDispatcher<'a> {
586 req: Option<Request>,
587 pool: &'a ThreadPool,
588 world: &'a mut WorldState,
589 pending_requests: &'a mut PendingRequests,
590 msg_sender: &'a Sender<Message>,
591 sender: &'a Sender<Task>,
592 request_received: Instant,
595 impl<'a> PoolDispatcher<'a> {
596 /// Dispatches the request onto the current thread
599 f: fn(&mut WorldState, R::Params) -> Result<R::Result>,
600 ) -> Result<&mut Self>
602 R: req::Request + 'static,
603 R::Params: DeserializeOwned + panic::UnwindSafe + 'static,
604 R::Result: Serialize + 'static,
606 let (id, params) = match self.parse::<R>() {
612 let world = panic::AssertUnwindSafe(&mut *self.world);
613 let task = panic::catch_unwind(move || {
614 let result = f(world.0, params);
615 result_to_task::<R>(id, result)
617 .map_err(|_| format!("sync task {:?} panicked", R::METHOD))?;
618 on_task(task, self.msg_sender, self.pending_requests, self.world);
622 /// Dispatches the request onto thread pool
623 fn on<R>(&mut self, f: fn(WorldSnapshot, R::Params) -> Result<R::Result>) -> Result<&mut Self>
625 R: req::Request + 'static,
626 R::Params: DeserializeOwned + Send + 'static,
627 R::Result: Serialize + 'static,
629 let (id, params) = match self.parse::<R>() {
637 let world = self.world.snapshot();
638 let sender = self.sender.clone();
640 let result = f(world, params);
641 let task = result_to_task::<R>(id, result);
642 sender.send(task).unwrap();
649 fn parse<R>(&mut self) -> Option<(RequestId, R::Params)>
651 R: req::Request + 'static,
652 R::Params: DeserializeOwned + 'static,
654 let req = self.req.take()?;
655 let (id, params) = match req.extract::<R::Params>(R::METHOD) {
658 self.req = Some(req);
662 self.pending_requests.start(PendingRequest {
664 method: R::METHOD.to_string(),
665 received: self.request_received,
670 fn finish(&mut self) {
671 match self.req.take() {
674 log::error!("unknown request: {:?}", req);
675 let resp = Response::new_err(
677 ErrorCode::MethodNotFound as i32,
678 "unknown request".to_string(),
680 self.msg_sender.send(resp.into()).unwrap();
686 fn result_to_task<R>(id: RequestId, result: Result<R::Result>) -> Task
688 R: req::Request + 'static,
689 R::Params: DeserializeOwned + 'static,
690 R::Result: Serialize + 'static,
692 let response = match result {
693 Ok(resp) => Response::new_ok(id, &resp),
694 Err(e) => match e.downcast::<LspError>() {
695 Ok(lsp_error) => Response::new_err(id, lsp_error.code, lsp_error.message),
698 // FIXME: When https://github.com/Microsoft/vscode-languageserver-node/issues/457
699 // gets fixed, we can return the proper response.
700 // This works around the issue where "content modified" error would continuously
701 // show an message pop-up in VsCode
704 // ErrorCode::ContentModified as i32,
705 // "content modified".to_string(),
707 Response::new_ok(id, ())
709 Response::new_err(id, ErrorCode::InternalError as i32, e.to_string())
714 Task::Respond(response)
717 fn update_file_notifications_on_threadpool(
719 world: WorldSnapshot,
720 publish_decorations: bool,
721 sender: Sender<Task>,
722 subscriptions: Vec<FileId>,
724 log::trace!("updating notifications for {:?}", subscriptions);
725 let publish_diagnostics = world.feature_flags().get("lsp.diagnostics");
726 pool.execute(move || {
727 for file_id in subscriptions {
728 if publish_diagnostics {
729 match handlers::publish_diagnostics(&world, file_id) {
731 if !is_canceled(&e) {
732 log::error!("failed to compute diagnostics: {:?}", e);
736 let not = notification_new::<req::PublishDiagnostics>(params);
737 sender.send(Task::Notify(not)).unwrap();
741 if publish_decorations {
742 match handlers::publish_decorations(&world, file_id) {
744 if !is_canceled(&e) {
745 log::error!("failed to compute decorations: {:?}", e);
749 let not = notification_new::<req::PublishDecorations>(params);
750 sender.send(Task::Notify(not)).unwrap();
758 pub fn show_message(typ: req::MessageType, message: impl Into<String>, sender: &Sender<Message>) {
759 let message = message.into();
760 let params = req::ShowMessageParams { typ, message };
761 let not = notification_new::<req::ShowMessage>(params);
762 sender.send(not.into()).unwrap();
765 fn is_canceled(e: &Box<dyn std::error::Error + Send + Sync>) -> bool {
766 e.downcast_ref::<Canceled>().is_some()
769 fn notification_is<N: lsp_types::notification::Notification>(notification: &Notification) -> bool {
770 notification.method == N::METHOD
773 fn notification_cast<N>(notification: Notification) -> std::result::Result<N::Params, Notification>
775 N: lsp_types::notification::Notification,
776 N::Params: DeserializeOwned,
778 notification.extract(N::METHOD)
781 fn notification_new<N>(params: N::Params) -> Notification
783 N: lsp_types::notification::Notification,
784 N::Params: Serialize,
786 Notification::new(N::METHOD.to_string(), params)
789 fn request_new<R>(id: RequestId, params: R::Params) -> Request
791 R: lsp_types::request::Request,
792 R::Params: Serialize,
794 Request::new(id, R::METHOD.to_string(), params)