1 //! FIXME: write short doc here
5 pub(crate) mod pending_requests;
7 use std::{error::Error, fmt, panic, path::PathBuf, sync::Arc, time::Instant};
9 use crossbeam_channel::{select, unbounded, RecvError, Sender};
10 use lsp_server::{Connection, ErrorCode, Message, Notification, Request, RequestId, Response};
11 use lsp_types::{ClientCapabilities, NumberOrString};
12 use ra_ide_api::{Canceled, FeatureFlags, FileId, LibraryData, SourceRootId};
14 use ra_vfs::{VfsTask, Watch};
15 use relative_path::RelativePathBuf;
16 use rustc_hash::FxHashSet;
17 use serde::{de::DeserializeOwned, Serialize};
18 use threadpool::ThreadPool;
22 pending_requests::{PendingRequest, PendingRequests},
23 subscriptions::Subscriptions,
26 world::{Options, WorldSnapshot, WorldState},
30 const THREADPOOL_SIZE: usize = 8;
31 const MAX_IN_FLIGHT_LIBS: usize = THREADPOOL_SIZE - 3;
40 pub fn new(code: i32, message: String) -> LspError {
41 LspError { code, message }
45 impl fmt::Display for LspError {
46 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
47 write!(f, "Language Server request failed with {}. ({})", self.code, self.message)
51 impl Error for LspError {}
54 ws_roots: Vec<PathBuf>,
55 client_caps: ClientCapabilities,
57 connection: Connection,
59 log::info!("server_config: {:#?}", config);
61 let mut loop_state = LoopState::default();
62 let mut world_state = {
63 // FIXME: support dynamic workspace loading.
65 let mut loaded_workspaces = Vec::new();
66 for ws_root in &ws_roots {
67 let workspace = ra_project_model::ProjectWorkspace::discover_with_sysroot(
72 Ok(workspace) => loaded_workspaces.push(workspace),
74 log::error!("loading workspace failed: {}", e);
77 req::MessageType::Error,
78 format!("rust-analyzer failed to load workspace: {}", e),
90 .map(|glob| ra_vfs_glob::Glob::new(glob))
91 .collect::<std::result::Result<Vec<_>, _>>()?;
93 if config.use_client_watching {
94 let registration_options = req::DidChangeWatchedFilesRegistrationOptions {
97 .flat_map(|ws| ws.to_roots())
98 .filter(|root| root.is_member())
99 .map(|root| format!("{}/**/*.rs", root.path().display()))
100 .map(|glob_pattern| req::FileSystemWatcher { glob_pattern, kind: None })
103 let registration = req::Registration {
104 id: "file-watcher".to_string(),
105 method: "workspace/didChangeWatchedFiles".to_string(),
106 register_options: Some(serde_json::to_value(registration_options).unwrap()),
108 let params = req::RegistrationParams { registrations: vec![registration] };
110 request_new::<req::RegisterCapability>(loop_state.next_request_id(), params);
111 connection.sender.send(request.into()).unwrap();
115 let text_document_caps = client_caps.text_document.as_ref();
117 publish_decorations: config.publish_decorations,
118 supports_location_link: text_document_caps
119 .and_then(|it| it.definition)
120 .and_then(|it| it.link_support)
122 line_folding_only: text_document_caps
123 .and_then(|it| it.folding_range.as_ref())
124 .and_then(|it| it.line_folding_only)
129 let feature_flags = {
130 let mut ff = FeatureFlags::default();
131 for (flag, value) in config.feature_flags {
132 if let Err(_) = ff.set(flag.as_str(), value) {
133 log::error!("unknown feature flag: {:?}", flag);
135 req::MessageType::Error,
136 format!("unknown feature flag: {:?}", flag),
143 log::info!("feature_flags: {:#?}", feature_flags);
150 Watch(!config.use_client_watching),
156 let pool = ThreadPool::new(THREADPOOL_SIZE);
157 let (task_sender, task_receiver) = unbounded::<Task>();
158 let (libdata_sender, libdata_receiver) = unbounded::<LibraryData>();
160 log::info!("server initialized, serving requests");
162 let task_sender = task_sender;
163 let libdata_sender = libdata_sender;
165 log::trace!("selecting");
166 let event = select! {
167 recv(&connection.receiver) -> msg => match msg {
168 Ok(msg) => Event::Msg(msg),
169 Err(RecvError) => Err("client exited without shutdown")?,
171 recv(task_receiver) -> task => Event::Task(task.unwrap()),
172 recv(world_state.task_receiver) -> task => match task {
173 Ok(task) => Event::Vfs(task),
174 Err(RecvError) => Err("vfs died")?,
176 recv(libdata_receiver) -> data => Event::Lib(data.unwrap())
178 if let Event::Msg(Message::Request(req)) = &event {
179 if connection.handle_shutdown(&req)? {
195 log::info!("waiting for tasks to finish...");
196 task_receiver.into_iter().for_each(|task| {
197 on_task(task, &connection.sender, &mut loop_state.pending_requests, &mut world_state)
199 libdata_receiver.into_iter().for_each(drop);
200 log::info!("...tasks have finished");
201 log::info!("joining threadpool...");
203 log::info!("...threadpool has finished");
205 let vfs = Arc::try_unwrap(world_state.vfs).expect("all snapshots should be dead");
214 Notify(Notification),
224 impl fmt::Debug for Event {
225 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
226 let debug_verbose_not = |not: &Notification, f: &mut fmt::Formatter| {
227 f.debug_struct("Notification").field("method", ¬.method).finish()
231 Event::Msg(Message::Notification(not)) => {
232 if notification_is::<req::DidOpenTextDocument>(not)
233 || notification_is::<req::DidChangeTextDocument>(not)
235 return debug_verbose_not(not, f);
238 Event::Task(Task::Notify(not)) => {
239 if notification_is::<req::PublishDecorations>(not)
240 || notification_is::<req::PublishDiagnostics>(not)
242 return debug_verbose_not(not, f);
245 Event::Task(Task::Respond(resp)) => {
247 .debug_struct("Response")
248 .field("id", &resp.id)
249 .field("error", &resp.error)
255 Event::Msg(it) => fmt::Debug::fmt(it, f),
256 Event::Task(it) => fmt::Debug::fmt(it, f),
257 Event::Vfs(it) => fmt::Debug::fmt(it, f),
258 Event::Lib(it) => fmt::Debug::fmt(it, f),
263 #[derive(Debug, Default)]
265 next_request_id: u64,
266 pending_responses: FxHashSet<RequestId>,
267 pending_requests: PendingRequests,
268 subscriptions: Subscriptions,
269 // We try not to index more than MAX_IN_FLIGHT_LIBS libraries at the same
270 // time to always have a thread ready to react to input.
271 in_flight_libraries: usize,
272 pending_libraries: Vec<(SourceRootId, Vec<(FileId, RelativePathBuf, Arc<String>)>)>,
273 workspace_loaded: bool,
277 fn next_request_id(&mut self) -> RequestId {
278 self.next_request_id += 1;
279 let res: RequestId = self.next_request_id.into();
280 let inserted = self.pending_responses.insert(res.clone());
288 task_sender: &Sender<Task>,
289 libdata_sender: &Sender<LibraryData>,
290 connection: &Connection,
291 world_state: &mut WorldState,
292 loop_state: &mut LoopState,
295 let loop_start = Instant::now();
297 // NOTE: don't count blocking select! call as a loop-turn time
298 let _p = profile("main_loop_inner/loop-turn");
299 log::info!("loop turn = {:?}", event);
300 let queue_count = pool.queued_count();
302 log::info!("queued count = {}", queue_count);
305 let mut state_changed = false;
307 Event::Task(task) => {
308 on_task(task, &connection.sender, &mut loop_state.pending_requests, world_state);
309 world_state.maybe_collect_garbage();
311 Event::Vfs(task) => {
312 world_state.vfs.write().handle_task(task);
313 state_changed = true;
316 world_state.add_lib(lib);
317 world_state.maybe_collect_garbage();
318 loop_state.in_flight_libraries -= 1;
320 Event::Msg(msg) => match msg {
321 Message::Request(req) => on_request(
323 &mut loop_state.pending_requests,
330 Message::Notification(not) => {
334 &mut loop_state.pending_requests,
335 &mut loop_state.subscriptions,
338 state_changed = true;
340 Message::Response(resp) => {
341 let removed = loop_state.pending_responses.remove(&resp.id);
343 log::error!("unexpected response: {:?}", resp)
349 loop_state.pending_libraries.extend(world_state.process_changes());
350 while loop_state.in_flight_libraries < MAX_IN_FLIGHT_LIBS
351 && !loop_state.pending_libraries.is_empty()
353 let (root, files) = loop_state.pending_libraries.pop().unwrap();
354 loop_state.in_flight_libraries += 1;
355 let sender = libdata_sender.clone();
356 pool.execute(move || {
357 log::info!("indexing {:?} ... ", root);
358 let _p = profile(&format!("indexed {:?}", root));
359 let data = LibraryData::prepare(root, files);
360 sender.send(data).unwrap();
364 if !loop_state.workspace_loaded
365 && world_state.roots_to_scan == 0
366 && loop_state.pending_libraries.is_empty()
367 && loop_state.in_flight_libraries == 0
369 loop_state.workspace_loaded = true;
370 let n_packages: usize = world_state.workspaces.iter().map(|it| it.n_packages()).sum();
371 if world_state.feature_flags().get("notifications.workspace-loaded") {
372 let msg = format!("workspace loaded, {} rust packages", n_packages);
373 show_message(req::MessageType::Info, msg, &connection.sender);
378 update_file_notifications_on_threadpool(
380 world_state.snapshot(),
381 world_state.options.publish_decorations,
383 loop_state.subscriptions.subscriptions(),
391 msg_sender: &Sender<Message>,
392 pending_requests: &mut PendingRequests,
393 state: &mut WorldState,
396 Task::Respond(response) => {
397 if let Some(completed) = pending_requests.finish(&response.id) {
398 log::info!("handled req#{} in {:?}", completed.id, completed.duration);
399 state.complete_request(completed);
400 msg_sender.send(response.into()).unwrap();
404 msg_sender.send(n.into()).unwrap();
410 world: &mut WorldState,
411 pending_requests: &mut PendingRequests,
413 sender: &Sender<Task>,
414 msg_sender: &Sender<Message>,
415 request_received: Instant,
418 let mut pool_dispatcher = PoolDispatcher {
428 .on_sync::<req::CollectGarbage>(|s, ()| Ok(s.collect_garbage()))?
429 .on_sync::<req::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
430 .on_sync::<req::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
431 .on_sync::<req::SelectionRangeRequest>(|s, p| {
432 handlers::handle_selection_range(s.snapshot(), p)
434 .on_sync::<req::FindMatchingBrace>(|s, p| {
435 handlers::handle_find_matching_brace(s.snapshot(), p)
437 .on::<req::AnalyzerStatus>(handlers::handle_analyzer_status)?
438 .on::<req::SyntaxTree>(handlers::handle_syntax_tree)?
439 .on::<req::OnTypeFormatting>(handlers::handle_on_type_formatting)?
440 .on::<req::DocumentSymbolRequest>(handlers::handle_document_symbol)?
441 .on::<req::WorkspaceSymbol>(handlers::handle_workspace_symbol)?
442 .on::<req::GotoDefinition>(handlers::handle_goto_definition)?
443 .on::<req::GotoImplementation>(handlers::handle_goto_implementation)?
444 .on::<req::GotoTypeDefinition>(handlers::handle_goto_type_definition)?
445 .on::<req::ParentModule>(handlers::handle_parent_module)?
446 .on::<req::Runnables>(handlers::handle_runnables)?
447 .on::<req::DecorationsRequest>(handlers::handle_decorations)?
448 .on::<req::Completion>(handlers::handle_completion)?
449 .on::<req::CodeActionRequest>(handlers::handle_code_action)?
450 .on::<req::CodeLensRequest>(handlers::handle_code_lens)?
451 .on::<req::CodeLensResolve>(handlers::handle_code_lens_resolve)?
452 .on::<req::FoldingRangeRequest>(handlers::handle_folding_range)?
453 .on::<req::SignatureHelpRequest>(handlers::handle_signature_help)?
454 .on::<req::HoverRequest>(handlers::handle_hover)?
455 .on::<req::PrepareRenameRequest>(handlers::handle_prepare_rename)?
456 .on::<req::Rename>(handlers::handle_rename)?
457 .on::<req::References>(handlers::handle_references)?
458 .on::<req::Formatting>(handlers::handle_formatting)?
459 .on::<req::DocumentHighlightRequest>(handlers::handle_document_highlight)?
460 .on::<req::InlayHints>(handlers::handle_inlay_hints)?
466 msg_sender: &Sender<Message>,
467 state: &mut WorldState,
468 pending_requests: &mut PendingRequests,
469 subs: &mut Subscriptions,
472 let not = match notification_cast::<req::Cancel>(not) {
474 let id: RequestId = match params.id {
475 NumberOrString::Number(id) => id.into(),
476 NumberOrString::String(id) => id.into(),
478 if pending_requests.cancel(&id) {
479 let response = Response::new_err(
481 ErrorCode::RequestCanceled as i32,
482 "canceled by client".to_string(),
484 msg_sender.send(response.into()).unwrap()
490 let not = match notification_cast::<req::DidOpenTextDocument>(not) {
492 let uri = params.text_document.uri;
493 let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?;
494 if let Some(file_id) =
495 state.vfs.write().add_file_overlay(&path, params.text_document.text)
497 subs.add_sub(FileId(file_id.0));
503 let not = match notification_cast::<req::DidChangeTextDocument>(not) {
505 let uri = params.text_document.uri;
506 let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?;
508 params.content_changes.pop().ok_or_else(|| "empty changes".to_string())?.text;
509 state.vfs.write().change_file_overlay(path.as_path(), text);
514 let not = match notification_cast::<req::DidCloseTextDocument>(not) {
516 let uri = params.text_document.uri;
517 let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?;
518 if let Some(file_id) = state.vfs.write().remove_file_overlay(path.as_path()) {
519 subs.remove_sub(FileId(file_id.0));
521 let params = req::PublishDiagnosticsParams { uri, diagnostics: Vec::new() };
522 let not = notification_new::<req::PublishDiagnostics>(params);
523 msg_sender.send(not.into()).unwrap();
528 let not = match notification_cast::<req::DidChangeConfiguration>(not) {
534 let not = match notification_cast::<req::DidChangeWatchedFiles>(not) {
536 let mut vfs = state.vfs.write();
537 for change in params.changes {
538 let uri = change.uri;
539 let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?;
540 vfs.notify_changed(path)
546 log::error!("unhandled notification: {:?}", not);
550 struct PoolDispatcher<'a> {
551 req: Option<Request>,
552 pool: &'a ThreadPool,
553 world: &'a mut WorldState,
554 pending_requests: &'a mut PendingRequests,
555 msg_sender: &'a Sender<Message>,
556 sender: &'a Sender<Task>,
557 request_received: Instant,
560 impl<'a> PoolDispatcher<'a> {
561 /// Dispatches the request onto the current thread
564 f: fn(&mut WorldState, R::Params) -> Result<R::Result>,
565 ) -> Result<&mut Self>
567 R: req::Request + 'static,
568 R::Params: DeserializeOwned + panic::UnwindSafe + 'static,
569 R::Result: Serialize + 'static,
571 let (id, params) = match self.parse::<R>() {
577 let world = panic::AssertUnwindSafe(&mut *self.world);
578 let task = panic::catch_unwind(move || {
579 let result = f(world.0, params);
580 result_to_task::<R>(id, result)
582 .map_err(|_| format!("sync task {:?} panicked", R::METHOD))?;
583 on_task(task, self.msg_sender, self.pending_requests, self.world);
587 /// Dispatches the request onto thread pool
588 fn on<R>(&mut self, f: fn(WorldSnapshot, R::Params) -> Result<R::Result>) -> Result<&mut Self>
590 R: req::Request + 'static,
591 R::Params: DeserializeOwned + Send + 'static,
592 R::Result: Serialize + 'static,
594 let (id, params) = match self.parse::<R>() {
602 let world = self.world.snapshot();
603 let sender = self.sender.clone();
605 let result = f(world, params);
606 let task = result_to_task::<R>(id, result);
607 sender.send(task).unwrap();
614 fn parse<R>(&mut self) -> Option<(RequestId, R::Params)>
616 R: req::Request + 'static,
617 R::Params: DeserializeOwned + 'static,
619 let req = self.req.take()?;
620 let (id, params) = match req.extract::<R::Params>(R::METHOD) {
623 self.req = Some(req);
627 self.pending_requests.start(PendingRequest {
629 method: R::METHOD.to_string(),
630 received: self.request_received,
635 fn finish(&mut self) {
636 match self.req.take() {
639 log::error!("unknown request: {:?}", req);
640 let resp = Response::new_err(
642 ErrorCode::MethodNotFound as i32,
643 "unknown request".to_string(),
645 self.msg_sender.send(resp.into()).unwrap();
651 fn result_to_task<R>(id: RequestId, result: Result<R::Result>) -> Task
653 R: req::Request + 'static,
654 R::Params: DeserializeOwned + 'static,
655 R::Result: Serialize + 'static,
657 let response = match result {
658 Ok(resp) => Response::new_ok(id, &resp),
659 Err(e) => match e.downcast::<LspError>() {
660 Ok(lsp_error) => Response::new_err(id, lsp_error.code, lsp_error.message),
663 // FIXME: When https://github.com/Microsoft/vscode-languageserver-node/issues/457
664 // gets fixed, we can return the proper response.
665 // This works around the issue where "content modified" error would continuously
666 // show an message pop-up in VsCode
669 // ErrorCode::ContentModified as i32,
670 // "content modified".to_string(),
672 Response::new_ok(id, ())
674 Response::new_err(id, ErrorCode::InternalError as i32, e.to_string())
679 Task::Respond(response)
682 fn update_file_notifications_on_threadpool(
684 world: WorldSnapshot,
685 publish_decorations: bool,
686 sender: Sender<Task>,
687 subscriptions: Vec<FileId>,
689 log::trace!("updating notifications for {:?}", subscriptions);
690 let publish_diagnostics = world.feature_flags().get("lsp.diagnostics");
691 pool.execute(move || {
692 for file_id in subscriptions {
693 if publish_diagnostics {
694 match handlers::publish_diagnostics(&world, file_id) {
696 if !is_canceled(&e) {
697 log::error!("failed to compute diagnostics: {:?}", e);
701 let not = notification_new::<req::PublishDiagnostics>(params);
702 sender.send(Task::Notify(not)).unwrap();
706 if publish_decorations {
707 match handlers::publish_decorations(&world, file_id) {
709 if !is_canceled(&e) {
710 log::error!("failed to compute decorations: {:?}", e);
714 let not = notification_new::<req::PublishDecorations>(params);
715 sender.send(Task::Notify(not)).unwrap();
723 pub fn show_message(typ: req::MessageType, message: impl Into<String>, sender: &Sender<Message>) {
724 let message = message.into();
725 let params = req::ShowMessageParams { typ, message };
726 let not = notification_new::<req::ShowMessage>(params);
727 sender.send(not.into()).unwrap();
730 fn is_canceled(e: &Box<dyn std::error::Error + Send + Sync>) -> bool {
731 e.downcast_ref::<Canceled>().is_some()
734 fn notification_is<N: lsp_types::notification::Notification>(notification: &Notification) -> bool {
735 notification.method == N::METHOD
738 fn notification_cast<N>(notification: Notification) -> std::result::Result<N::Params, Notification>
740 N: lsp_types::notification::Notification,
741 N::Params: DeserializeOwned,
743 notification.extract(N::METHOD)
746 fn notification_new<N>(params: N::Params) -> Notification
748 N: lsp_types::notification::Notification,
749 N::Params: Serialize,
751 Notification::new(N::METHOD.to_string(), params)
754 fn request_new<R>(id: RequestId, params: R::Params) -> Request
756 R: lsp_types::request::Request,
757 R::Params: Serialize,
759 Request::new(id, R::METHOD.to_string(), params)