Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

lsp: Honor dynamic LSP document selectors (#59243)

Shuhei Kadowaki23aca9895c8e
diff --git a/crates/agent/src/tools/rename_tool.rs b/crates/agent/src/tools/rename_tool.rs
index 46e1bddc892..b9065cc5ca9 100644
--- a/crates/agent/src/tools/rename_tool.rs
+++ b/crates/agent/src/tools/rename_tool.rs
@@ -81,6 +81,7 @@ impl AgentTool for RenameTool {
resolved.buffer.clone(),
resolved.position,
input.new_name.clone(),
+ None,
cx,
)
});
diff --git a/crates/collab/tests/integration/editor_tests.rs b/crates/collab/tests/integration/editor_tests.rs
index b1b9d7e0e76..60f5ae6e19c 100644
--- a/crates/collab/tests/integration/editor_tests.rs
+++ b/crates/collab/tests/integration/editor_tests.rs
@@ -33,8 +33,11 @@ use multi_buffer::{AnchorRangeExt as _, MultiBufferRow};
use pretty_assertions::assert_eq;
use project::{
ProgressToken, ProjectPath, SERVER_PROGRESS_THROTTLE_TIMEOUT,
- lsp_store::emmet_ext::LspExpandAbbreviation,
- lsp_store::lsp_ext_command::{ExpandedMacro, LspExtExpandMacro},
+ lsp_store::{
+ TokenType,
+ emmet_ext::LspExpandAbbreviation,
+ lsp_ext_command::{ExpandedMacro, LspExtExpandMacro},
+ },
trusted_worktrees::{PathTrust, TrustedWorktrees},
};
use recent_projects::disconnected_overlay::DisconnectedOverlay;
@@ -1199,6 +1202,410 @@ async fn test_collaborating_with_renames(cx_a: &mut TestAppContext, cx_b: &mut T
})
}
+#[gpui::test]
+async fn test_remote_rename_uses_server_that_prepared_it(
+ cx_a: &mut TestAppContext,
+ cx_b: &mut TestAppContext,
+) {
+ let mut server = TestServer::start(cx_a.executor()).await;
+ let client_a = server.create_client(cx_a, "user_a").await;
+ let client_b = server.create_client(cx_b, "user_b").await;
+ server
+ .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
+ .await;
+ let active_call_a = cx_a.read(ActiveCall::global);
+ cx_b.update(editor::init);
+
+ let unprepared_capabilities = lsp::ServerCapabilities {
+ rename_provider: Some(lsp::OneOf::Right(lsp::RenameOptions {
+ prepare_provider: Some(false),
+ work_done_progress_options: lsp::WorkDoneProgressOptions::default(),
+ })),
+ ..lsp::ServerCapabilities::default()
+ };
+ let prepared_capabilities = lsp::ServerCapabilities {
+ rename_provider: Some(lsp::OneOf::Right(lsp::RenameOptions {
+ prepare_provider: Some(true),
+ work_done_progress_options: lsp::WorkDoneProgressOptions::default(),
+ })),
+ ..lsp::ServerCapabilities::default()
+ };
+ client_a.language_registry().add(rust_lang());
+ let mut unprepared_servers = client_a.language_registry().register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ name: "unprepared-rename-server",
+ capabilities: unprepared_capabilities.clone(),
+ ..FakeLspAdapter::default()
+ },
+ );
+ let mut prepared_servers = client_a.language_registry().register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ name: "prepared-rename-server",
+ capabilities: prepared_capabilities.clone(),
+ ..FakeLspAdapter::default()
+ },
+ );
+ client_b.language_registry().add(rust_lang());
+ client_b.language_registry().register_fake_lsp_adapter(
+ "Rust",
+ FakeLspAdapter {
+ name: "unprepared-rename-server",
+ capabilities: unprepared_capabilities,
+ ..FakeLspAdapter::default()
+ },
+ );
+ client_b.language_registry().register_fake_lsp_adapter(
+ "Rust",
+ FakeLspAdapter {
+ name: "prepared-rename-server",
+ capabilities: prepared_capabilities,
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ client_a
+ .fs()
+ .insert_tree(path!("/dir"), json!({ "one.rs": "const ONE: usize = 1;" }))
+ .await;
+ let (project_a, worktree_id) = client_a.build_local_project(path!("/dir"), cx_a).await;
+ let project_id = active_call_a
+ .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
+ .await
+ .unwrap();
+ let project_b = client_b.join_remote_project(project_id, cx_b).await;
+ let (workspace_b, cx_b) = client_b.build_workspace(&project_b, cx_b);
+ let editor_b = workspace_b
+ .update_in(cx_b, |workspace, window, cx| {
+ workspace.open_path((worktree_id, rel_path("one.rs")), None, true, window, cx)
+ })
+ .await
+ .unwrap()
+ .downcast::<Editor>()
+ .unwrap();
+ let unprepared_server = unprepared_servers.next().await.unwrap();
+ let prepared_server = prepared_servers.next().await.unwrap();
+ cx_a.run_until_parked();
+ cx_b.run_until_parked();
+
+ let unprepared_prepare_count = Arc::new(AtomicUsize::new(0));
+ let _unprepared_prepare_requests = unprepared_server
+ .set_request_handler::<lsp::request::PrepareRenameRequest, _, _>({
+ let unprepared_prepare_count = unprepared_prepare_count.clone();
+ move |_, _| {
+ unprepared_prepare_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+ let _prepared_prepare_requests = prepared_server
+ .set_request_handler::<lsp::request::PrepareRenameRequest, _, _>(|_, _| async move {
+ Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
+ lsp::Position::new(0, 6),
+ lsp::Position::new(0, 9),
+ ))))
+ });
+ let unprepared_rename_count = Arc::new(AtomicUsize::new(0));
+ let _unprepared_rename_requests = unprepared_server
+ .set_request_handler::<lsp::request::Rename, _, _>({
+ let unprepared_rename_count = unprepared_rename_count.clone();
+ move |_, _| {
+ unprepared_rename_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+ let prepared_rename_count = Arc::new(AtomicUsize::new(0));
+ let _prepared_rename_requests = prepared_server
+ .set_request_handler::<lsp::request::Rename, _, _>({
+ let prepared_rename_count = prepared_rename_count.clone();
+ move |_, _| {
+ prepared_rename_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+
+ let prepare_rename = editor_b.update_in(cx_b, |editor, window, cx| {
+ editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
+ selections.select_ranges([MultiBufferOffset(7)..MultiBufferOffset(7)])
+ });
+ editor.rename(&Rename, window, cx).unwrap()
+ });
+ prepare_rename.await.unwrap();
+ editor_b.update(cx_b, |editor, cx| {
+ let rename = editor.pending_rename().unwrap();
+ rename.editor.update(cx, |rename_editor, cx| {
+ rename_editor.buffer().update(cx, |rename_buffer, cx| {
+ rename_buffer.edit(
+ [(MultiBufferOffset(0)..MultiBufferOffset(3), "TWO")],
+ None,
+ cx,
+ );
+ });
+ });
+ });
+
+ let confirm_rename = editor_b.update_in(cx_b, |editor, window, cx| {
+ Editor::confirm_rename(editor, &ConfirmRename, window, cx).unwrap()
+ });
+ confirm_rename.await.unwrap();
+
+ assert_eq!(unprepared_prepare_count.load(atomic::Ordering::SeqCst), 0);
+ assert_eq!(
+ unprepared_rename_count.load(atomic::Ordering::SeqCst),
+ 0,
+ "expected remote rename not to switch back to the first capable server",
+ );
+ assert_eq!(
+ prepared_rename_count.load(atomic::Ordering::SeqCst),
+ 1,
+ "expected remote rename to use the server that prepared it",
+ );
+}
+
+#[gpui::test]
+async fn test_remote_rename_with_stale_server_id_falls_back_to_capable_server(
+ cx_a: &mut TestAppContext,
+ cx_b: &mut TestAppContext,
+) {
+ let mut server = TestServer::start(cx_a.executor()).await;
+ let client_a = server.create_client(cx_a, "user_a").await;
+ let client_b = server.create_client(cx_b, "user_b").await;
+ server
+ .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
+ .await;
+ let active_call_a = cx_a.read(ActiveCall::global);
+
+ let capabilities = lsp::ServerCapabilities {
+ rename_provider: Some(lsp::OneOf::Left(true)),
+ ..lsp::ServerCapabilities::default()
+ };
+ client_a.language_registry().add(rust_lang());
+ let mut fake_servers = client_a.language_registry().register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ name: "rename-server",
+ capabilities: capabilities.clone(),
+ ..FakeLspAdapter::default()
+ },
+ );
+ client_b.language_registry().add(rust_lang());
+ client_b.language_registry().register_fake_lsp_adapter(
+ "Rust",
+ FakeLspAdapter {
+ name: "rename-server",
+ capabilities,
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ client_a
+ .fs()
+ .insert_tree(path!("/dir"), json!({ "one.rs": "const ONE: usize = 1;" }))
+ .await;
+ let (project_a, worktree_id) = client_a.build_local_project(path!("/dir"), cx_a).await;
+ let project_id = active_call_a
+ .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
+ .await
+ .unwrap();
+ let project_b = client_b.join_remote_project(project_id, cx_b).await;
+ let (buffer_b, _handle_b) = project_b
+ .update(cx_b, |project, cx| {
+ project.open_buffer_with_lsp((worktree_id, rel_path("one.rs")), cx)
+ })
+ .await
+ .unwrap();
+ let fake_server = fake_servers.next().await.unwrap();
+ cx_a.run_until_parked();
+ cx_b.run_until_parked();
+
+ let rename_request_count = Arc::new(AtomicUsize::new(0));
+ let _rename_requests = fake_server.set_request_handler::<lsp::request::Rename, _, _>({
+ let rename_request_count = rename_request_count.clone();
+ move |params, _| {
+ rename_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move {
+ assert_eq!(params.new_name, "TWO");
+ Ok(Some(lsp::WorkspaceEdit {
+ changes: Some(
+ [(
+ lsp::Uri::from_file_path(path!("/dir/one.rs")).unwrap(),
+ vec![lsp::TextEdit::new(
+ lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
+ "TWO".to_string(),
+ )],
+ )]
+ .into_iter()
+ .collect(),
+ ),
+ ..lsp::WorkspaceEdit::default()
+ }))
+ }
+ }
+ });
+
+ let transaction = project_b
+ .update(cx_b, |project, cx| {
+ project.perform_rename(
+ buffer_b.clone(),
+ 7,
+ "TWO".to_string(),
+ Some(lsp::LanguageServerId(4242)),
+ cx,
+ )
+ })
+ .await
+ .unwrap()
+ .0;
+
+ assert_eq!(
+ rename_request_count.load(atomic::Ordering::SeqCst),
+ 1,
+ "expected the host to drop the stale server id and fall back to the capable server",
+ );
+ assert_eq!(transaction.len(), 1);
+ buffer_b.read_with(cx_b, |buffer, _| {
+ assert_eq!(buffer.text(), "const TWO: usize = 1;");
+ });
+}
+
+#[gpui::test]
+async fn test_remote_dynamic_call_hierarchy_followups_use_prepared_server(
+ cx_a: &mut TestAppContext,
+ cx_b: &mut TestAppContext,
+) {
+ let mut server = TestServer::start(cx_a.executor()).await;
+ let client_a = server.create_client(cx_a, "user_a").await;
+ let client_b = server.create_client(cx_b, "user_b").await;
+ server
+ .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
+ .await;
+ let active_call_a = cx_a.read(ActiveCall::global);
+ cx_b.update(editor::init);
+
+ client_a.language_registry().add(rust_lang());
+ let mut fake_servers = client_a.language_registry().register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities::default(),
+ ..FakeLspAdapter::default()
+ },
+ );
+ client_b.language_registry().add(rust_lang());
+ client_b.language_registry().register_fake_lsp_adapter(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities::default(),
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ client_a
+ .fs()
+ .insert_tree(path!("/dir"), json!({ "one.rs": "fn one() {}" }))
+ .await;
+ let (project_a, worktree_id) = client_a.build_local_project(path!("/dir"), cx_a).await;
+ let project_id = active_call_a
+ .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
+ .await
+ .unwrap();
+ let project_b = client_b.join_remote_project(project_id, cx_b).await;
+ let (workspace_b, cx_b) = client_b.build_workspace(&project_b, cx_b);
+ let editor_b = workspace_b
+ .update_in(cx_b, |workspace, window, cx| {
+ workspace.open_path((worktree_id, rel_path("one.rs")), None, true, window, cx)
+ })
+ .await
+ .unwrap()
+ .downcast::<Editor>()
+ .unwrap();
+ let buffer_b = editor_b
+ .read_with(cx_b, |editor, cx| editor.buffer().read(cx).as_singleton())
+ .unwrap();
+ let fake_server = fake_servers.next().await.unwrap();
+ cx_a.run_until_parked();
+ cx_b.run_until_parked();
+
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "file-call-hierarchy".to_string(),
+ method: "textDocument/prepareCallHierarchy".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "file" }],
+ })),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx_a.run_until_parked();
+ cx_b.run_until_parked();
+
+ let item = lsp::CallHierarchyItem {
+ name: "one".to_string(),
+ kind: lsp::SymbolKind::FUNCTION,
+ tags: None,
+ detail: None,
+ uri: lsp::Uri::from_file_path(path!("/dir/one.rs")).unwrap(),
+ range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 11)),
+ selection_range: lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(0, 6)),
+ data: None,
+ };
+ let _prepare_requests = fake_server
+ .set_request_handler::<lsp::request::CallHierarchyPrepare, _, _>({
+ let item = item.clone();
+ move |_, _| {
+ let item = item.clone();
+ async move { Ok(Some(vec![item])) }
+ }
+ });
+ let incoming_request_count = Arc::new(AtomicUsize::new(0));
+ let _incoming_requests = fake_server
+ .set_request_handler::<lsp::request::CallHierarchyIncomingCalls, _, _>({
+ let incoming_request_count = incoming_request_count.clone();
+ move |_, _| {
+ incoming_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+ let outgoing_request_count = Arc::new(AtomicUsize::new(0));
+ let _outgoing_requests = fake_server
+ .set_request_handler::<lsp::request::CallHierarchyOutgoingCalls, _, _>({
+ let outgoing_request_count = outgoing_request_count.clone();
+ move |_, _| {
+ outgoing_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+
+ let items = project_b
+ .update(cx_b, |project, cx| {
+ project.prepare_call_hierarchy(&buffer_b, 0, cx)
+ })
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(items.len(), 1);
+ let item = items.into_iter().next().unwrap();
+
+ project_b
+ .update(cx_b, |project, cx| project.incoming_calls(item.clone(), cx))
+ .await
+ .unwrap()
+ .unwrap();
+ project_b
+ .update(cx_b, |project, cx| project.outgoing_calls(item, cx))
+ .await
+ .unwrap()
+ .unwrap();
+
+ assert_eq!(incoming_request_count.load(atomic::Ordering::SeqCst), 1);
+ assert_eq!(outgoing_request_count.load(atomic::Ordering::SeqCst), 1);
+}
+
#[gpui::test]
async fn test_slow_lsp_server(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
let mut server = TestServer::start(cx_a.executor()).await;
@@ -1444,7 +1851,7 @@ async fn test_collaborating_with_code_lens_resolve(
..lsp::ServerCapabilities::default()
};
client_a.language_registry().add(rust_lang());
- client_a.language_registry().register_fake_lsp(
+ let mut fake_language_servers = client_a.language_registry().register_fake_lsp(
"Rust",
FakeLspAdapter {
capabilities: capabilities.clone(),
@@ -1511,6 +1918,26 @@ async fn test_collaborating_with_code_lens_resolve(
.unwrap()
.downcast::<Editor>()
.unwrap();
+ let fake_language_server = fake_language_servers.next().await.unwrap();
+ fake_language_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "untitled-code-lens".to_string(),
+ method: "textDocument/codeLens".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [
+ { "language": "rust", "scheme": "untitled" }
+ ],
+ "resolveProvider": false,
+ })),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
cx_a.run_until_parked();
cx_b.run_until_parked();
@@ -5936,6 +6363,92 @@ async fn test_mutual_editor_semantic_token_cache_update(
});
}
+#[gpui::test]
+async fn test_guest_semantic_tokens_honor_dynamic_document_selectors(
+ cx_a: &mut TestAppContext,
+ cx_b: &mut TestAppContext,
+) {
+ run_guest_semantic_tokens_document_selector_test(
+ GuestSemanticTokensTestConfig {
+ include_static_capability: true,
+ include_matching_registration: true,
+ expected_token_type: Some("keyword"),
+ ..GuestSemanticTokensTestConfig::default()
+ },
+ cx_a,
+ cx_b,
+ )
+ .await;
+}
+
+#[gpui::test]
+async fn test_guest_does_not_guess_semantic_token_legend_without_matching_adapter(
+ cx_a: &mut TestAppContext,
+ cx_b: &mut TestAppContext,
+) {
+ run_guest_semantic_tokens_document_selector_test(
+ GuestSemanticTokensTestConfig {
+ remove_guest_adapter_before_stylizing: true,
+ include_static_capability: true,
+ include_matching_registration: true,
+ expect_unstyled_tokens: true,
+ ..GuestSemanticTokensTestConfig::default()
+ },
+ cx_a,
+ cx_b,
+ )
+ .await;
+}
+
+#[gpui::test]
+async fn test_guest_receives_dynamic_document_selectors_when_project_is_shared_later(
+ cx_a: &mut TestAppContext,
+ cx_b: &mut TestAppContext,
+) {
+ run_guest_semantic_tokens_document_selector_test(
+ GuestSemanticTokensTestConfig {
+ share_after_registration: true,
+ include_static_capability: true,
+ include_matching_registration: true,
+ expected_token_type: Some("keyword"),
+ ..GuestSemanticTokensTestConfig::default()
+ },
+ cx_a,
+ cx_b,
+ )
+ .await;
+}
+
+#[gpui::test]
+async fn test_guest_preserves_static_capability_after_nonmatching_dynamic_registration(
+ cx_a: &mut TestAppContext,
+ cx_b: &mut TestAppContext,
+) {
+ run_guest_semantic_tokens_document_selector_test(
+ GuestSemanticTokensTestConfig {
+ include_static_capability: true,
+ expected_token_type: Some("type"),
+ ..GuestSemanticTokensTestConfig::default()
+ },
+ cx_a,
+ cx_b,
+ )
+ .await;
+}
+
+#[gpui::test]
+async fn test_guest_does_not_treat_nonmatching_dynamic_capability_as_static(
+ cx_a: &mut TestAppContext,
+ cx_b: &mut TestAppContext,
+) {
+ run_guest_semantic_tokens_document_selector_test(
+ GuestSemanticTokensTestConfig::default(),
+ cx_a,
+ cx_b,
+ )
+ .await;
+}
+
#[gpui::test(iterations = 10)]
async fn test_semantic_token_refresh_is_forwarded(
cx_a: &mut TestAppContext,
@@ -6611,3 +7124,229 @@ fn blame_entry(sha: &str, range: Range<u32>) -> git::blame::BlameEntry {
boundary: false,
}
}
+
+#[derive(Default)]
+struct GuestSemanticTokensTestConfig {
+ share_after_registration: bool,
+ remove_guest_adapter_before_stylizing: bool,
+ include_static_capability: bool,
+ include_matching_registration: bool,
+ expect_unstyled_tokens: bool,
+ expected_token_type: Option<&'static str>,
+}
+
+async fn run_guest_semantic_tokens_document_selector_test(
+ config: GuestSemanticTokensTestConfig,
+ cx_a: &mut TestAppContext,
+ cx_b: &mut TestAppContext,
+) {
+ let GuestSemanticTokensTestConfig {
+ share_after_registration,
+ remove_guest_adapter_before_stylizing,
+ include_static_capability,
+ include_matching_registration,
+ expect_unstyled_tokens,
+ expected_token_type,
+ } = config;
+ let mut server = TestServer::start(cx_a.executor()).await;
+ let executor = cx_a.executor();
+ let client_a = server.create_client(cx_a, "user_a").await;
+ let client_b = server.create_client(cx_b, "user_b").await;
+ server
+ .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
+ .await;
+ let active_call_a = cx_a.read(ActiveCall::global);
+
+ let static_capabilities = lsp::ServerCapabilities {
+ semantic_tokens_provider: include_static_capability.then_some(
+ lsp::SemanticTokensServerCapabilities::SemanticTokensOptions(
+ lsp::SemanticTokensOptions {
+ legend: lsp::SemanticTokensLegend {
+ token_types: vec!["type".into()],
+ token_modifiers: Vec::new(),
+ },
+ full: Some(lsp::SemanticTokensFullOptions::Bool(true)),
+ ..lsp::SemanticTokensOptions::default()
+ },
+ ),
+ ),
+ ..lsp::ServerCapabilities::default()
+ };
+ client_a.language_registry().add(rust_lang());
+ let mut fake_language_servers = client_a.language_registry().register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: static_capabilities.clone(),
+ ..FakeLspAdapter::default()
+ },
+ );
+ client_b.language_registry().add(rust_lang());
+ client_b.language_registry().register_fake_lsp_adapter(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: static_capabilities,
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ client_a
+ .fs()
+ .insert_tree(path!("/a"), json!({ "main.rs": "fn main() {}" }))
+ .await;
+ let (project_a, worktree_id) = client_a.build_local_project(path!("/a"), cx_a).await;
+ active_call_a
+ .update(cx_a, |call, cx| call.set_location(Some(&project_a), cx))
+ .await
+ .unwrap();
+ let project_id = if share_after_registration {
+ None
+ } else {
+ Some(
+ active_call_a
+ .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
+ .await
+ .unwrap(),
+ )
+ };
+
+ let (_buffer_a, _handle_a) = project_a
+ .update(cx_a, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/a/main.rs"), cx)
+ })
+ .await
+ .unwrap();
+ let fake_language_server = fake_language_servers.next().await.unwrap();
+ executor.run_until_parked();
+
+ let semantic_tokens_registration =
+ |scheme: &str, full: lsp::SemanticTokensFullOptions, token_type: &str| {
+ serde_json::to_value(lsp::SemanticTokensRegistrationOptions {
+ text_document_registration_options: lsp::TextDocumentRegistrationOptions {
+ document_selector: Some(vec![lsp::DocumentFilter {
+ language: Some("rust".to_string()),
+ scheme: Some(scheme.to_string()),
+ pattern: None,
+ }]),
+ },
+ semantic_tokens_options: lsp::SemanticTokensOptions {
+ legend: lsp::SemanticTokensLegend {
+ token_types: vec![token_type.to_owned().into()],
+ token_modifiers: Vec::new(),
+ },
+ full: Some(full),
+ ..lsp::SemanticTokensOptions::default()
+ },
+ static_registration_options: lsp::StaticRegistrationOptions::default(),
+ })
+ .ok()
+ };
+ let mut registrations = Vec::new();
+ if include_matching_registration {
+ registrations.push(lsp::Registration {
+ id: "file-semantic-tokens".to_string(),
+ method: "textDocument/semanticTokens".to_string(),
+ register_options: semantic_tokens_registration(
+ "file",
+ lsp::SemanticTokensFullOptions::Delta { delta: Some(true) },
+ "keyword",
+ ),
+ });
+ }
+ registrations.push(lsp::Registration {
+ id: "untitled-semantic-tokens".to_string(),
+ method: "textDocument/semanticTokens".to_string(),
+ register_options: semantic_tokens_registration(
+ "untitled",
+ lsp::SemanticTokensFullOptions::Bool(true),
+ "comment",
+ ),
+ });
+ fake_language_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams { registrations },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+
+ let semantic_token_requests = Arc::new(AtomicUsize::new(0));
+ fake_language_server.set_request_handler::<lsp::request::SemanticTokensFullRequest, _, _>({
+ let semantic_token_requests = semantic_token_requests.clone();
+ move |_, _| {
+ semantic_token_requests.fetch_add(1, atomic::Ordering::SeqCst);
+ async move {
+ Ok(Some(lsp::SemanticTokensResult::Tokens(
+ lsp::SemanticTokens {
+ data: vec![0, 3, 4, 0, 0],
+ result_id: None,
+ },
+ )))
+ }
+ }
+ });
+ executor.run_until_parked();
+
+ let project_id = match project_id {
+ Some(project_id) => project_id,
+ None => active_call_a
+ .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
+ .await
+ .unwrap(),
+ };
+ let project_b = client_b.join_remote_project(project_id, cx_b).await;
+ let buffer_b = project_b
+ .update(cx_b, |project, cx| {
+ project.open_buffer((worktree_id, rel_path("main.rs")), cx)
+ })
+ .await
+ .unwrap();
+ executor.run_until_parked();
+
+ let requests_before_guest_fetch = semantic_token_requests.load(atomic::Ordering::SeqCst);
+ let lsp_store_b = project_b.read_with(cx_b, |project, _| project.lsp_store());
+ let guest_tokens = lsp_store_b
+ .update(cx_b, |lsp_store, cx| {
+ lsp_store.semantic_tokens(buffer_b.clone(), cx)
+ })
+ .await
+ .unwrap();
+
+ let expected_server_count =
+ usize::from(expected_token_type.is_some() || expect_unstyled_tokens);
+ assert_eq!(
+ semantic_token_requests.load(atomic::Ordering::SeqCst) - requests_before_guest_fetch,
+ expected_server_count,
+ "expected the guest request routing to honor the applicable providers",
+ );
+ assert_eq!(
+ guest_tokens.tokens.as_ref().map_or(0, HashMap::len),
+ expected_server_count,
+ "expected the guest token result to honor the applicable providers",
+ );
+ if expected_server_count == 0 {
+ return;
+ }
+ if remove_guest_adapter_before_stylizing {
+ client_b.language_registry().remove_lsp_adapter(
+ &language::LanguageName::new("Rust"),
+ &lsp::LanguageServerName::new_static("the-fake-language-server"),
+ );
+ }
+ let server_id = guest_tokens
+ .tokens
+ .as_ref()
+ .and_then(|tokens| tokens.keys().next().copied())
+ .expect("expected semantic tokens from one server");
+ let token_type = lsp_store_b.update(cx_b, |lsp_store, cx| {
+ let language = buffer_b.read(cx).language().map(|language| language.name());
+ lsp_store
+ .get_or_create_token_stylizer(server_id, language.as_ref(), cx)
+ .and_then(|stylizer| stylizer.token_type_name(TokenType(0)).cloned())
+ });
+ assert_eq!(
+ token_type.as_deref(),
+ expected_token_type,
+ "expected the guest to decode tokens only when the applicable provider's legend is known",
+ );
+}
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index ac59e3eeb12..2e41e84a2c3 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -1569,11 +1569,17 @@ struct SnippetState {
choices: Vec<Option<Vec<String>>>,
}
+pub struct RenameTarget {
+ range: Range<text::Anchor>,
+ language_server_id: Option<LanguageServerId>,
+}
+
#[doc(hidden)]
pub struct RenameState {
pub range: Range<Anchor>,
pub old_name: Arc<str>,
pub editor: Entity<Editor>,
+ language_server_id: Option<LanguageServerId>,
block_id: CustomBlockId,
}
@@ -8021,8 +8027,12 @@ impl Editor {
drop(snapshot);
Some(cx.spawn_in(window, async move |this, cx| {
- let rename_range = prepare_rename.await?;
- if let Some(rename_range) = rename_range {
+ let rename_target = prepare_rename.await?;
+ if let Some(RenameTarget {
+ range: rename_range,
+ language_server_id,
+ }) = rename_target
+ {
this.update_in(cx, |this, window, cx| {
let snapshot = cursor_buffer.read(cx).snapshot();
let rename_buffer_range = rename_range.to_offset(&snapshot);
@@ -8174,6 +8184,7 @@ impl Editor {
range,
old_name,
editor: rename_editor,
+ language_server_id,
block_id,
});
})?;
@@ -8217,6 +8228,7 @@ impl Editor {
&buffer,
start,
new_name.clone(),
+ rename.language_server_id,
cx,
)?;
@@ -11709,13 +11721,14 @@ pub trait SemanticsProvider {
buffer: &Entity<Buffer>,
position: text::Anchor,
cx: &mut App,
- ) -> Task<Result<Option<Range<text::Anchor>>>>;
+ ) -> Task<Result<Option<RenameTarget>>>;
fn perform_rename(
&self,
buffer: &Entity<Buffer>,
position: text::Anchor,
new_name: String,
+ language_server_id: Option<LanguageServerId>,
cx: &mut App,
) -> Option<Task<Result<ProjectTransaction>>>;
}
@@ -11855,7 +11868,7 @@ impl SemanticsProvider for WeakEntity<Project> {
buffer: &Entity<Buffer>,
position: text::Anchor,
cx: &mut App,
- ) -> Task<Result<Option<Range<text::Anchor>>>> {
+ ) -> Task<Result<Option<RenameTarget>>> {
let Some(this) = self.upgrade() else {
return Task::ready(Ok(None));
};
@@ -11865,7 +11878,13 @@ impl SemanticsProvider for WeakEntity<Project> {
let task = project.prepare_rename(buffer.clone(), position, cx);
cx.spawn(async move |_, cx| {
Ok(match task.await? {
- PrepareRenameResponse::Success(range) => Some(range),
+ PrepareRenameResponse::Success {
+ range,
+ language_server_id,
+ } => Some(RenameTarget {
+ range,
+ language_server_id,
+ }),
PrepareRenameResponse::InvalidPosition => None,
PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
// Fallback on using TreeSitter info to determine identifier range
@@ -11875,10 +11894,11 @@ impl SemanticsProvider for WeakEntity<Project> {
if kind != Some(CharKind::Word) {
return None;
}
- Some(
- snapshot.anchor_before(range.start)
+ Some(RenameTarget {
+ range: snapshot.anchor_before(range.start)
..snapshot.anchor_after(range.end),
- )
+ language_server_id: None,
+ })
})
}
})
@@ -11891,10 +11911,11 @@ impl SemanticsProvider for WeakEntity<Project> {
buffer: &Entity<Buffer>,
position: text::Anchor,
new_name: String,
+ language_server_id: Option<LanguageServerId>,
cx: &mut App,
) -> Option<Task<Result<ProjectTransaction>>> {
self.update(cx, |project, cx| {
- project.perform_rename(buffer.clone(), position, new_name, cx)
+ project.perform_rename(buffer.clone(), position, new_name, language_server_id, cx)
})
.ok()
}
diff --git a/crates/lsp/src/lsp.rs b/crates/lsp/src/lsp.rs
index 0366fdf5850..9e95b5760a9 100644
--- a/crates/lsp/src/lsp.rs
+++ b/crates/lsp/src/lsp.rs
@@ -450,12 +450,12 @@ where
}
/// Combined capabilities of the server and the adapter.
-#[derive(Debug, Clone)]
-pub struct AdapterServerCapabilities {
+#[derive(Debug, Clone, Copy)]
+pub struct AdapterServerCapabilities<'a> {
// Reported capabilities by the server
- pub server_capabilities: ServerCapabilities,
+ pub server_capabilities: &'a ServerCapabilities,
// List of code actions supported by the LspAdapter matching the server
- pub code_action_kinds: Option<Vec<CodeActionKind>>,
+ pub code_action_kinds: Option<&'a [CodeActionKind]>,
}
// See the VSCode docs [1] and the LSP Spec [2]
@@ -721,8 +721,8 @@ impl LanguageServer {
}
/// List of code action kinds this language server reports being able to emit.
- pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
- self.code_action_kinds.clone()
+ pub fn code_action_kinds(&self) -> Option<&[CodeActionKind]> {
+ self.code_action_kinds.as_deref()
}
async fn handle_incoming_messages<Stdout>(
@@ -1455,15 +1455,6 @@ impl LanguageServer {
self.capabilities.read().clone()
}
- /// Get the reported capabilities of the running language server and
- /// what we know on the client/adapter-side of its capabilities.
- pub fn adapter_server_capabilities(&self) -> AdapterServerCapabilities {
- AdapterServerCapabilities {
- server_capabilities: self.capabilities(),
- code_action_kinds: self.code_action_kinds(),
- }
- }
-
/// Update the capabilities of the running language server.
pub fn update_capabilities(&self, update: impl FnOnce(&mut ServerCapabilities)) {
update(self.capabilities.write().deref_mut());
diff --git a/crates/project/src/lsp_command.rs b/crates/project/src/lsp_command.rs
index a386162413f..9ce17157a3c 100644
--- a/crates/project/src/lsp_command.rs
+++ b/crates/project/src/lsp_command.rs
@@ -103,29 +103,15 @@ pub trait LspCommand: 'static + Sized + Send + std::fmt::Debug {
LanguageServerToQuery::FirstCapable
}
- fn to_lsp_params_or_response(
- &self,
- path: &Path,
- buffer: &Buffer,
- language_server: &Arc<LanguageServer>,
- cx: &App,
- ) -> Result<
- LspParamsOrResponse<<Self::LspRequest as lsp::request::Request>::Params, Self::Response>,
- > {
- if self.check_capabilities(language_server.adapter_server_capabilities()) {
- Ok(LspParamsOrResponse::Params(self.to_lsp(
- path,
- buffer,
- language_server,
- cx,
- )?))
- } else {
- Ok(LspParamsOrResponse::Response(Default::default()))
- }
- }
+ /// Returns whether the given static or dynamic capability supports this request.
+ fn check_capabilities(&self, _: AdapterServerCapabilities<'_>) -> bool;
- /// When false, `to_lsp_params_or_response` default implementation will return the default response.
- fn check_capabilities(&self, _: AdapterServerCapabilities) -> bool;
+ fn response_without_request<'a, I>(&self, _applicable_capabilities: I) -> Option<Self::Response>
+ where
+ I: Iterator<Item = AdapterServerCapabilities<'a>>,
+ {
+ None
+ }
fn to_lsp(
&self,
@@ -172,11 +158,6 @@ pub trait LspCommand: 'static + Sized + Send + std::fmt::Debug {
fn buffer_id_from_proto(message: &Self::ProtoRequest) -> Result<BufferId>;
}
-pub enum LspParamsOrResponse<P, R> {
- Params(P),
- Response(R),
-}
-
#[derive(Debug)]
pub(crate) struct PrepareRename {
pub position: PointUtf16,
@@ -187,6 +168,7 @@ pub(crate) struct PerformRename {
pub position: PointUtf16,
pub new_name: String,
pub push_to_history: bool,
+ pub language_server_id: Option<LanguageServerId>,
}
#[derive(Debug, Clone, Copy)]
@@ -692,23 +674,18 @@ impl LspCommand for GetIncomingCalls {
"Get incoming calls"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
- capabilities
- .server_capabilities
- .call_hierarchy_provider
- .as_ref()
- .is_some_and(|capability| match capability {
- lsp::CallHierarchyServerCapability::Simple(supported) => *supported,
- lsp::CallHierarchyServerCapability::Options(_) => true,
- })
+ /// Follow-up requests operate on a server-issued item, so the server's support is
+ /// already proven and no capability gate applies.
+ fn check_capabilities(&self, _: AdapterServerCapabilities) -> bool {
+ true
}
fn to_lsp(
&self,
path: &Path,
buffer: &Buffer,
- _language_server: &Arc<LanguageServer>,
- _cx: &App,
+ _: &Arc<LanguageServer>,
+ _: &App,
) -> Result<lsp::CallHierarchyIncomingCallsParams> {
Ok(lsp::CallHierarchyIncomingCallsParams {
item: call_hierarchy_item_to_lsp(&self.item, path, buffer)?,
@@ -839,23 +816,18 @@ impl LspCommand for GetOutgoingCalls {
"Get outgoing calls"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
- capabilities
- .server_capabilities
- .call_hierarchy_provider
- .as_ref()
- .is_some_and(|capability| match capability {
- lsp::CallHierarchyServerCapability::Simple(supported) => *supported,
- lsp::CallHierarchyServerCapability::Options(_) => true,
- })
+ /// Follow-up requests operate on a server-issued item, so the server's support is
+ /// already proven and no capability gate applies.
+ fn check_capabilities(&self, _: AdapterServerCapabilities) -> bool {
+ true
}
fn to_lsp(
&self,
path: &Path,
buffer: &Buffer,
- _language_server: &Arc<LanguageServer>,
- _cx: &App,
+ _: &Arc<LanguageServer>,
+ _: &App,
) -> Result<lsp::CallHierarchyOutgoingCallsParams> {
Ok(lsp::CallHierarchyOutgoingCallsParams {
item: call_hierarchy_item_to_lsp(&self.item, path, buffer)?,
@@ -977,45 +949,34 @@ impl LspCommand for PrepareRename {
"Prepare rename"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
capabilities
.server_capabilities
.rename_provider
+ .as_ref()
.is_some_and(|capability| match capability {
- OneOf::Left(enabled) => enabled,
- OneOf::Right(options) => options.prepare_provider.unwrap_or(false),
+ OneOf::Left(enabled) => *enabled,
+ OneOf::Right(_) => true,
})
}
- fn to_lsp_params_or_response(
+ fn response_without_request<'a, I>(
&self,
- path: &Path,
- buffer: &Buffer,
- language_server: &Arc<LanguageServer>,
- cx: &App,
- ) -> Result<LspParamsOrResponse<lsp::TextDocumentPositionParams, PrepareRenameResponse>> {
- let rename_provider = language_server
- .adapter_server_capabilities()
- .server_capabilities
- .rename_provider;
- match rename_provider {
- Some(lsp::OneOf::Right(RenameOptions {
- prepare_provider: Some(true),
- ..
- })) => Ok(LspParamsOrResponse::Params(self.to_lsp(
- path,
- buffer,
- language_server,
- cx,
- )?)),
- Some(lsp::OneOf::Right(_)) => Ok(LspParamsOrResponse::Response(
- PrepareRenameResponse::OnlyUnpreparedRenameSupported,
- )),
- Some(lsp::OneOf::Left(true)) => Ok(LspParamsOrResponse::Response(
- PrepareRenameResponse::OnlyUnpreparedRenameSupported,
- )),
- _ => anyhow::bail!("Rename not supported"),
- }
+ mut applicable_capabilities: I,
+ ) -> Option<Self::Response>
+ where
+ I: Iterator<Item = AdapterServerCapabilities<'a>>,
+ {
+ (!applicable_capabilities.any(|capabilities| {
+ matches!(
+ capabilities.server_capabilities.rename_provider.as_ref(),
+ Some(lsp::OneOf::Right(RenameOptions {
+ prepare_provider: Some(true),
+ ..
+ }))
+ )
+ }))
+ .then_some(PrepareRenameResponse::OnlyUnpreparedRenameSupported)
}
fn to_lsp(
@@ -1033,7 +994,7 @@ impl LspCommand for PrepareRename {
message: Option<lsp::PrepareRenameResponse>,
_: Entity<LspStore>,
buffer: Entity<Buffer>,
- _: LanguageServerId,
+ server_id: LanguageServerId,
cx: AsyncApp,
) -> Result<PrepareRenameResponse> {
buffer.read_with(&cx, |buffer, _| match message {
@@ -1043,9 +1004,10 @@ impl LspCommand for PrepareRename {
if buffer.clip_point_utf16(start, Bias::Left) == start.0
&& buffer.clip_point_utf16(end, Bias::Left) == end.0
{
- Ok(PrepareRenameResponse::Success(
- buffer.anchor_after(start)..buffer.anchor_before(end),
- ))
+ Ok(PrepareRenameResponse::Success {
+ range: buffer.anchor_after(start)..buffer.anchor_before(end),
+ language_server_id: Some(server_id),
+ })
} else {
Ok(PrepareRenameResponse::InvalidPosition)
}
@@ -1054,7 +1016,10 @@ impl LspCommand for PrepareRename {
let snapshot = buffer.snapshot();
let (range, _) = snapshot.surrounding_word(self.position, None);
let range = snapshot.anchor_after(range.start)..snapshot.anchor_before(range.end);
- Ok(PrepareRenameResponse::Success(range))
+ Ok(PrepareRenameResponse::Success {
+ range,
+ language_server_id: Some(server_id),
+ })
}
None => Ok(PrepareRenameResponse::InvalidPosition),
})
@@ -1100,12 +1065,16 @@ impl LspCommand for PrepareRename {
_: &mut App,
) -> proto::PrepareRenameResponse {
match response {
- PrepareRenameResponse::Success(range) => proto::PrepareRenameResponse {
+ PrepareRenameResponse::Success {
+ range,
+ language_server_id,
+ } => proto::PrepareRenameResponse {
can_rename: true,
only_unprepared_rename_supported: false,
start: Some(language::proto::serialize_anchor(&range.start)),
end: Some(language::proto::serialize_anchor(&range.end)),
version: serialize_version(buffer_version),
+ language_server_id: language_server_id.map(LanguageServerId::to_proto),
},
PrepareRenameResponse::OnlyUnpreparedRenameSupported => proto::PrepareRenameResponse {
can_rename: false,
@@ -1113,6 +1082,7 @@ impl LspCommand for PrepareRename {
start: None,
end: None,
version: vec![],
+ language_server_id: None,
},
PrepareRenameResponse::InvalidPosition => proto::PrepareRenameResponse {
can_rename: false,
@@ -1120,6 +1090,7 @@ impl LspCommand for PrepareRename {
start: None,
end: None,
version: vec![],
+ language_server_id: None,
},
}
}
@@ -1141,7 +1112,12 @@ impl LspCommand for PrepareRename {
message.start.and_then(deserialize_anchor),
message.end.and_then(deserialize_anchor),
) {
- Ok(PrepareRenameResponse::Success(start..end))
+ Ok(PrepareRenameResponse::Success {
+ range: start..end,
+ language_server_id: message
+ .language_server_id
+ .map(LanguageServerId::from_proto),
+ })
} else {
anyhow::bail!(
"Missing start or end position in remote project PrepareRenameResponse"
@@ -1169,12 +1145,13 @@ impl LspCommand for PerformRename {
"Rename"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
capabilities
.server_capabilities
.rename_provider
+ .as_ref()
.is_some_and(|capability| match capability {
- OneOf::Left(enabled) => enabled,
+ OneOf::Left(enabled) => *enabled,
OneOf::Right(_) => true,
})
}
@@ -1226,12 +1203,13 @@ impl LspCommand for PerformRename {
)),
new_name: self.new_name.clone(),
version: serialize_version(&buffer.version()),
+ language_server_id: self.language_server_id.map(LanguageServerId::to_proto),
}
}
async fn from_proto(
message: proto::PerformRename,
- _: Entity<LspStore>,
+ lsp_store: Entity<LspStore>,
buffer: Entity<Buffer>,
mut cx: AsyncApp,
) -> Result<Self> {
@@ -1244,11 +1222,25 @@ impl LspCommand for PerformRename {
buffer.wait_for_version(deserialize_version(&message.version))
})
.await?;
- Ok(Self {
+ let mut request = Self {
position: buffer.read_with(&cx, |buffer, _| position.to_point_utf16(buffer)),
new_name: message.new_name,
push_to_history: false,
- })
+ language_server_id: message.language_server_id.map(LanguageServerId::from_proto),
+ };
+ if let Some(server_id) = request.language_server_id {
+ // Only a store that runs the servers can judge the id; non-local stores forward
+ // the request upstream, where the authoritative store re-validates.
+ let server_is_capable = lsp_store.update(&mut cx, |lsp_store, cx| {
+ lsp_store.as_local().is_none()
+ || lsp_store
+ .language_server_capable_of_lsp_request(&buffer, server_id, &request, cx)
+ });
+ if !server_is_capable {
+ request.language_server_id = None;
+ }
+ }
+ Ok(request)
}
fn response_to_proto(
@@ -1298,12 +1290,13 @@ impl LspCommand for GetDefinitions {
"Get definition"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
capabilities
.server_capabilities
.definition_provider
+ .as_ref()
.is_some_and(|capability| match capability {
- OneOf::Left(supported) => supported,
+ OneOf::Left(supported) => *supported,
OneOf::Right(_options) => true,
})
}
@@ -1400,12 +1393,13 @@ impl LspCommand for GetEditPredictionDefinitions {
"Get edit prediction definition"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
capabilities
.server_capabilities
.definition_provider
+ .as_ref()
.is_some_and(|capability| match capability {
- OneOf::Left(supported) => supported,
+ OneOf::Left(supported) => *supported,
OneOf::Right(_options) => true,
})
}
@@ -1500,12 +1494,13 @@ impl LspCommand for GetDeclarations {
"Get declaration"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
capabilities
.server_capabilities
.declaration_provider
+ .as_ref()
.is_some_and(|capability| match capability {
- lsp::DeclarationCapability::Simple(supported) => supported,
+ lsp::DeclarationCapability::Simple(supported) => *supported,
lsp::DeclarationCapability::RegistrationOptions(..) => true,
lsp::DeclarationCapability::Options(..) => true,
})
@@ -1603,12 +1598,13 @@ impl LspCommand for GetImplementations {
"Get implementation"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
capabilities
.server_capabilities
.implementation_provider
+ .as_ref()
.is_some_and(|capability| match capability {
- lsp::ImplementationProviderCapability::Simple(enabled) => enabled,
+ lsp::ImplementationProviderCapability::Simple(enabled) => *enabled,
lsp::ImplementationProviderCapability::Options(_options) => true,
})
}
@@ -1705,7 +1701,7 @@ impl LspCommand for GetTypeDefinitions {
"Get type definition"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
!matches!(
&capabilities.server_capabilities.type_definition_provider,
None | Some(lsp::TypeDefinitionProviderCapability::Simple(false))
@@ -1804,7 +1800,7 @@ impl LspCommand for GetEditPredictionTypeDefinitions {
"Get edit prediction type definition"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
!matches!(
&capabilities.server_capabilities.type_definition_provider,
None | Some(lsp::TypeDefinitionProviderCapability::Simple(false))
@@ -2280,7 +2276,7 @@ impl LspCommand for GetReferences {
Some("Finding references...".to_owned())
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
match &capabilities.server_capabilities.references_provider {
Some(OneOf::Left(has_support)) => *has_support,
Some(OneOf::Right(_)) => true,
@@ -2454,12 +2450,13 @@ impl LspCommand for GetDocumentHighlights {
"Get document highlights"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
capabilities
.server_capabilities
.document_highlight_provider
+ .as_ref()
.is_some_and(|capability| match capability {
- OneOf::Left(supported) => supported,
+ OneOf::Left(supported) => *supported,
OneOf::Right(_options) => true,
})
}
@@ -2609,12 +2606,13 @@ impl LspCommand for GetDocumentSymbols {
"Get document symbols"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
capabilities
.server_capabilities
.document_symbol_provider
+ .as_ref()
.is_some_and(|capability| match capability {
- OneOf::Left(supported) => supported,
+ OneOf::Left(supported) => *supported,
OneOf::Right(_options) => true,
})
}
@@ -2806,7 +2804,7 @@ impl LspCommand for GetSignatureHelp {
"Get signature help"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
capabilities
.server_capabilities
.signature_help_provider
@@ -2930,9 +2928,9 @@ impl LspCommand for GetHover {
"Get hover"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
- match capabilities.server_capabilities.hover_provider {
- Some(lsp::HoverProviderCapability::Simple(enabled)) => enabled,
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
+ match capabilities.server_capabilities.hover_provider.as_ref() {
+ Some(lsp::HoverProviderCapability::Simple(enabled)) => *enabled,
Some(lsp::HoverProviderCapability::Options(_)) => true,
None => false,
}
@@ -3170,7 +3168,7 @@ impl LspCommand for GetCompletions {
"Get completion"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
capabilities
.server_capabilities
.completion_provider
@@ -3534,7 +3532,7 @@ impl LspCommand for GetCodeActions {
"Get code actions"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
match &capabilities.server_capabilities.code_action_provider {
None => false,
Some(lsp::CodeActionProviderCapability::Simple(false)) => false,
@@ -3586,27 +3584,6 @@ impl LspCommand for GetCodeActions {
relevant_diagnostics.push(diagnostic);
}
- let only = if let Some(requested) = &self.kinds {
- if let Some(supported_kinds) =
- Self::supported_code_action_kinds(language_server.adapter_server_capabilities())
- {
- let filtered = requested
- .iter()
- .filter(|requested_kind| {
- supported_kinds.iter().any(|supported_kind| {
- code_action_kind_matches(requested_kind, supported_kind)
- })
- })
- .cloned()
- .collect();
- Some(filtered)
- } else {
- Some(requested.clone())
- }
- } else {
- None
- };
-
Ok(lsp::CodeActionParams {
text_document: make_text_document_identifier(path)?,
range: range_to_lsp(self.range.to_point_utf16(buffer))?,
@@ -3614,7 +3591,7 @@ impl LspCommand for GetCodeActions {
partial_result_params: Default::default(),
context: lsp::CodeActionContext {
diagnostics: relevant_diagnostics,
- only,
+ only: self.kinds.clone(),
..lsp::CodeActionContext::default()
},
})
@@ -3762,10 +3739,14 @@ impl LspCommand for GetCodeActions {
}
impl GetCodeActions {
- fn supported_code_action_kinds(
- capabilities: AdapterServerCapabilities,
- ) -> Option<Vec<CodeActionKind>> {
- match capabilities.server_capabilities.code_action_provider {
+ fn supported_code_action_kinds<'a>(
+ capabilities: AdapterServerCapabilities<'a>,
+ ) -> Option<&'a [CodeActionKind]> {
+ match capabilities
+ .server_capabilities
+ .code_action_provider
+ .as_ref()
+ {
Some(lsp::CodeActionProviderCapability::Options(CodeActionOptions {
code_action_kinds: Some(supported_action_kinds),
..
@@ -3813,7 +3794,7 @@ impl LspCommand for OnTypeFormatting {
"Formatting on typing"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
Self::supports_on_type_formatting(&self.trigger, &capabilities.server_capabilities)
}
@@ -4319,7 +4300,7 @@ impl LspCommand for InlayHints {
"Inlay hints"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
Self::check_capabilities(&capabilities.server_capabilities)
}
@@ -4358,9 +4339,18 @@ impl LspCommand for InlayHints {
// Hence let's use a heuristic first to handle the most awkward case and look for more.
let force_no_type_left_padding =
lsp_adapter.name.0.as_ref() == "typescript-language-server";
+ let can_resolve = lsp_store.update(&mut cx, |lsp_store, cx| {
+ lsp_store.text_document_capability_matches_for_server(
+ &buffer,
+ server_id,
+ "textDocument/inlayHint",
+ |capabilities| InlayHints::can_resolve_inlays(capabilities.server_capabilities),
+ cx,
+ )
+ });
let hints = message.unwrap_or_default().into_iter().map(|lsp_hint| {
- let resolve_state = if InlayHints::can_resolve_inlays(&lsp_server.capabilities()) {
+ let resolve_state = if can_resolve {
ResolveState::CanResolve(lsp_server.server_id(), lsp_hint.data.clone())
} else {
ResolveState::Resolved
@@ -4471,7 +4461,7 @@ impl LspCommand for SemanticTokensFull {
"Semantic tokens full"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
capabilities
.server_capabilities
.semantic_tokens_provider
@@ -4622,7 +4612,7 @@ impl LspCommand for SemanticTokensDelta {
"Semantic tokens delta"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
capabilities
.server_capabilities
.semantic_tokens_provider
@@ -4775,7 +4765,7 @@ impl LspCommand for GetCodeLens {
"Code Lens"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
capabilities
.server_capabilities
.code_lens_provider
@@ -4891,8 +4881,9 @@ impl LspCommand for GetCodeLens {
}
impl LinkedEditingRange {
- pub fn check_server_capabilities(capabilities: ServerCapabilities) -> bool {
- let Some(linked_editing_options) = capabilities.linked_editing_range_provider else {
+ pub fn check_server_capabilities(capabilities: &ServerCapabilities) -> bool {
+ let Some(linked_editing_options) = capabilities.linked_editing_range_provider.as_ref()
+ else {
return false;
};
if let LinkedEditingRangeServerCapabilities::Simple(false) = linked_editing_options {
@@ -4912,8 +4903,8 @@ impl LspCommand for LinkedEditingRange {
"Linked editing range"
}
- fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
- Self::check_server_capabilities(capabilities.server_capabilities)
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
+ Self::check_server_capabilities(&capabilities.server_capabilities)
}
fn to_lsp(
@@ -5363,8 +5354,11 @@ impl LspCommand for GetDocumentDiagnostics {
"Get diagnostics"
}
- fn check_capabilities(&self, _: AdapterServerCapabilities) -> bool {
- true
+ fn check_capabilities(&self, capabilities: AdapterServerCapabilities<'_>) -> bool {
+ capabilities
+ .server_capabilities
+ .diagnostic_provider
+ .is_some()
}
fn to_lsp(
@@ -5552,7 +5546,7 @@ impl LspCommand for GetDocumentColor {
"Document color"
}
- fn check_capabilities(&self, server_capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, server_capabilities: AdapterServerCapabilities<'_>) -> bool {
server_capabilities
.server_capabilities
.color_provider
@@ -5695,7 +5689,7 @@ impl LspCommand for GetFoldingRanges {
"Folding ranges"
}
- fn check_capabilities(&self, server_capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, server_capabilities: AdapterServerCapabilities<'_>) -> bool {
server_capabilities
.server_capabilities
.folding_range_provider
@@ -5851,7 +5845,7 @@ impl LspCommand for GetDocumentLinks {
"Document links"
}
- fn check_capabilities(&self, server_capabilities: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, server_capabilities: AdapterServerCapabilities<'_>) -> bool {
server_capabilities
.server_capabilities
.document_link_provider
diff --git a/crates/project/src/lsp_store.rs b/crates/project/src/lsp_store.rs
index e2211b724a8..d0804834ae8 100644
--- a/crates/project/src/lsp_store.rs
+++ b/crates/project/src/lsp_store.rs
@@ -29,7 +29,7 @@ use self::code_lens::CodeLensData;
use self::document_colors::DocumentColorData;
use self::document_links::DocumentLinksData;
use self::document_symbols::DocumentSymbolsData;
-use self::dynamic_registration::{DynamicRegistrations, RegistrationSource};
+use self::dynamic_registration::DynamicRegistrations;
use self::inlay_hints::BufferInlayHints;
use crate::{
CodeAction, Completion, CompletionDisplayOptions, CompletionResponse, CompletionSource,
@@ -303,6 +303,12 @@ pub struct DocumentDiagnostics {
version: Option<i32>,
}
+#[derive(Clone, Debug)]
+struct DocumentSelectorContext {
+ language_id: String,
+ scheme: &'static str,
+}
+
pub struct LocalLspStore {
weak: WeakEntity<LspStore>,
pub worktree_store: Entity<WorktreeStore>,
@@ -321,6 +327,7 @@ pub struct LocalLspStore {
language_server_paths_watched_for_rename:
HashMap<LanguageServerId, RenamePathsWatchedForServer>,
language_server_dynamic_registrations: HashMap<LanguageServerId, DynamicRegistrations>,
+ initial_server_capabilities: HashMap<LanguageServerId, lsp::ServerCapabilities>,
supplementary_language_servers:
HashMap<LanguageServerId, (LanguageServerName, Arc<LanguageServer>)>,
prettier_store: Entity<PrettierStore>,
@@ -1503,6 +1510,7 @@ impl LocalLspStore {
Self::execute_code_actions_on_server(
&lsp_store,
language_server,
+ buffer,
actions,
push_to_history,
&mut project_transaction,
@@ -1940,23 +1948,66 @@ impl LocalLspStore {
return Ok(());
};
- let language_server = match specifier {
+ let adapter_and_server = match specifier {
settings::LanguageServerFormatterSpecifier::Specific { name } => {
- adapters_and_servers.iter().find_map(|(adapter, server)| {
- if adapter.name.0.as_ref() == name {
- Some(server.clone())
- } else {
- None
- }
- })
+ adapters_and_servers
+ .iter()
+ .find(|(adapter, _)| adapter.name.0.as_ref() == name)
+ .cloned()
+ }
+ settings::LanguageServerFormatterSpecifier::Current => {
+ lsp_store.read_with(cx, |lsp_store, cx| {
+ lsp_store.as_local().and_then(|local| {
+ let buffer_snapshot = buffer.handle.read(cx);
+ let adapter_and_server = if buffer.ranges.is_some() {
+ let range_formatter =
+ adapters_and_servers.iter().find(|(adapter, server)| {
+ buffer_supports_lsp_range_formatting(
+ local,
+ buffer_snapshot,
+ adapter,
+ server,
+ )
+ });
+ if range_formatter.is_some() {
+ range_formatter
+ } else if trigger == FormatTrigger::Save
+ && settings.format_on_save
+ == FormatOnSave::ModificationsIfAvailable
+ {
+ adapters_and_servers.iter().find(|(adapter, server)| {
+ buffer_supports_lsp_formatting(
+ local,
+ buffer_snapshot,
+ adapter,
+ server,
+ )
+ })
+ } else {
+ None
+ }
+ } else {
+ adapters_and_servers.iter().find(|(adapter, server)| {
+ buffer_supports_lsp_formatting(
+ local,
+ buffer_snapshot,
+ adapter,
+ server,
+ ) || buffer_supports_lsp_range_formatting(
+ local,
+ buffer_snapshot,
+ adapter,
+ server,
+ )
+ })
+ };
+ adapter_and_server.cloned()
+ })
+ })?
}
- settings::LanguageServerFormatterSpecifier::Current => adapters_and_servers
- .iter()
- .find(|(_, server)| Self::server_supports_formatting(server))
- .map(|(_, server)| server.clone()),
};
- let Some(language_server) = language_server else {
+ let Some((adapter, language_server)) = adapter_and_server else {
zlog::debug!(
logger =>
"No language server found to format buffer {buffer_path_abs:?}. Skipping",
@@ -1977,6 +2028,7 @@ impl LocalLspStore {
&buffer.handle,
ranges,
buffer_path_abs,
+ &adapter,
&language_server,
&settings,
cx,
@@ -1998,6 +2050,7 @@ impl LocalLspStore {
&lsp_store,
&buffer.handle,
buffer_path_abs,
+ &adapter,
&language_server,
&settings,
cx,
@@ -2020,6 +2073,7 @@ impl LocalLspStore {
&lsp_store,
&buffer.handle,
buffer_path_abs,
+ &adapter,
&language_server,
&settings,
cx,
@@ -2111,8 +2165,26 @@ impl LocalLspStore {
zlog::trace!(logger => "Executing {}", describe_code_action(&action));
- if let Err(err) =
- Self::try_resolve_code_action(server, &mut action, request_timeout).await
+ let can_resolve_actions = lsp_store.update(cx, |lsp_store, cx| {
+ lsp_store.text_document_capability_matches_for_server(
+ &buffer.handle,
+ server.server_id(),
+ "textDocument/codeAction",
+ |capabilities| {
+ GetCodeActions::can_resolve_actions(
+ capabilities.server_capabilities,
+ )
+ },
+ cx,
+ )
+ })?;
+ if let Err(err) = Self::try_resolve_code_action(
+ server,
+ &mut action,
+ can_resolve_actions,
+ request_timeout,
+ )
+ .await
{
zlog::error!(
logger =>
@@ -2404,16 +2476,22 @@ impl LocalLspStore {
buffer_handle: &Entity<Buffer>,
ranges: &[Range<Anchor>],
abs_path: &Path,
+ adapter: &Arc<CachedLspAdapter>,
language_server: &Arc<LanguageServer>,
settings: &LanguageSettings,
cx: &mut AsyncApp,
) -> Result<Option<Vec<(Range<Anchor>, Arc<str>)>>> {
- let capabilities = &language_server.capabilities();
- let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
- if !matches!(
- range_formatting_provider,
- Some(OneOf::Left(true) | OneOf::Right(_))
- ) {
+ let range_formatting_supported = this.read_with(cx, |this, cx| {
+ this.as_local().is_some_and(|local| {
+ buffer_supports_lsp_range_formatting(
+ local,
+ buffer_handle.read(cx),
+ adapter,
+ language_server,
+ )
+ })
+ })?;
+ if !range_formatting_supported {
log::debug!(
"Skipping range formatting: language server {} does not support range formatting",
language_server.name()
@@ -2537,17 +2615,11 @@ impl LocalLspStore {
}
}
- fn server_supports_formatting(server: &Arc<LanguageServer>) -> bool {
- let capabilities = server.capabilities();
- let formatting = capabilities.document_formatting_provider.as_ref();
- matches!(formatting, Some(p) if *p != OneOf::Left(false))
- || server_capabilities_support_range_formatting(&capabilities)
- }
-
async fn format_via_lsp(
this: &WeakEntity<LspStore>,
buffer: &Entity<Buffer>,
abs_path: &Path,
+ adapter: &Arc<CachedLspAdapter>,
language_server: &Arc<LanguageServer>,
settings: &LanguageSettings,
cx: &mut AsyncApp,
@@ -2557,10 +2629,23 @@ impl LocalLspStore {
let uri = file_path_to_lsp_url(abs_path)?;
let text_document = lsp::TextDocumentIdentifier::new(uri);
- let capabilities = &language_server.capabilities();
- let formatting_provider = capabilities.document_formatting_provider.as_ref();
- let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
+ let (formatting_supported, range_formatting_supported) =
+ this.read_with(cx, |this, cx| match this.as_local() {
+ Some(local) => {
+ let buffer = buffer.read(cx);
+ (
+ buffer_supports_lsp_formatting(local, buffer, adapter, language_server),
+ buffer_supports_lsp_range_formatting(
+ local,
+ buffer,
+ adapter,
+ language_server,
+ ),
+ )
+ }
+ None => (false, false),
+ })?;
let request_timeout = cx.update(|app| {
ProjectSettings::get_global(app)
@@ -2568,7 +2653,7 @@ impl LocalLspStore {
.get_request_timeout()
});
- let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
+ let lsp_edits = if formatting_supported {
let _timer = zlog::time!(logger => "format-full");
language_server
.request::<lsp::request::Formatting>(
@@ -2581,7 +2666,7 @@ impl LocalLspStore {
)
.await
.into_response()?
- } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
+ } else if range_formatting_supported {
let _timer = zlog::time!(logger => "format-range");
let buffer_start = lsp::Position::new(0, 0);
let buffer_end = buffer.read_with(cx, |b, _| point_to_lsp(b.max_point_utf16()));
@@ -2700,12 +2785,13 @@ impl LocalLspStore {
async fn try_resolve_code_action(
lang_server: &LanguageServer,
action: &mut CodeAction,
+ can_resolve: bool,
request_timeout: Duration,
) -> anyhow::Result<()> {
match &mut action.lsp_action {
LspAction::Action(lsp_action) => {
if !action.resolved
- && GetCodeActions::can_resolve_actions(&lang_server.capabilities())
+ && can_resolve
&& lsp_action.data.is_some()
&& (lsp_action.command.is_none() || lsp_action.edit.is_none())
{
@@ -2719,7 +2805,7 @@ impl LocalLspStore {
}
}
LspAction::CodeLens(lens) => {
- if !action.resolved && GetCodeLens::can_resolve_lens(&lang_server.capabilities()) {
+ if !action.resolved && can_resolve {
*lens = lang_server
.request::<lsp::request::CodeLensResolve>(lens.clone(), request_timeout)
.await
@@ -2782,35 +2868,32 @@ impl LocalLspStore {
self.lsp_tree
.get(path, language.name(), language.manifest(), &delegate, cx)
{
- let server = self
- .language_servers
- .get(&server_id)
- .and_then(|server_state| {
- if let LanguageServerState::Running { server, .. } = server_state {
- Some(server.clone())
- } else {
- None
- }
- });
- let server = match server {
- Some(server) => server,
- None => continue,
+ let Some((server, adapter)) =
+ self.language_servers
+ .get(&server_id)
+ .and_then(|server_state| {
+ if let LanguageServerState::Running {
+ server, adapter, ..
+ } = server_state
+ {
+ Some((server.clone(), adapter.clone()))
+ } else {
+ None
+ }
+ })
+ else {
+ continue;
};
buffer_handle.update(cx, |buffer, cx| {
buffer.set_completion_triggers(
server.server_id(),
- server
- .capabilities()
- .completion_provider
- .as_ref()
- .and_then(|provider| {
- provider
- .trigger_characters
- .as_ref()
- .map(|characters| characters.iter().cloned().collect())
- })
- .unwrap_or_default(),
+ completion_trigger_characters_for_buffer(
+ self,
+ server.server_id(),
+ &adapter,
+ buffer,
+ ),
cx,
);
});
@@ -3116,17 +3199,12 @@ impl LocalLspStore {
buffer_handle.update(cx, |buffer, cx| {
buffer.set_completion_triggers(
server.server_id(),
- server
- .capabilities()
- .completion_provider
- .as_ref()
- .and_then(|provider| {
- provider
- .trigger_characters
- .as_ref()
- .map(|characters| characters.iter().cloned().collect())
- })
- .unwrap_or_default(),
+ completion_trigger_characters_for_buffer(
+ self,
+ server.server_id(),
+ &adapter,
+ buffer,
+ ),
cx,
);
});
@@ -3354,6 +3432,7 @@ impl LocalLspStore {
pub async fn execute_code_actions_on_server(
lsp_store: &WeakEntity<LspStore>,
language_server: &Arc<LanguageServer>,
+ buffer: &Entity<Buffer>,
actions: Vec<CodeAction>,
push_to_history: bool,
project_transaction: &mut ProjectTransaction,
@@ -3364,11 +3443,28 @@ impl LocalLspStore {
.global_lsp_settings
.get_request_timeout()
});
+ let server_id = language_server.server_id();
+ let can_resolve_actions = lsp_store.update(cx, |lsp_store, cx| {
+ lsp_store.text_document_capability_matches_for_server(
+ buffer,
+ server_id,
+ "textDocument/codeAction",
+ |capabilities| {
+ GetCodeActions::can_resolve_actions(capabilities.server_capabilities)
+ },
+ cx,
+ )
+ })?;
for mut action in actions {
- Self::try_resolve_code_action(language_server, &mut action, request_timeout)
- .await
- .context("resolving a formatting code action")?;
+ Self::try_resolve_code_action(
+ language_server,
+ &mut action,
+ can_resolve_actions,
+ request_timeout,
+ )
+ .await
+ .context("resolving a formatting code action")?;
if let Some(edit) = action.lsp_action.edit() {
if edit.changes.is_none() && edit.document_changes.is_none() {
@@ -3908,6 +4004,9 @@ impl LocalLspStore {
self.last_workspace_edits_by_language_server
.remove(server_id_to_remove);
self.language_servers.remove(server_id_to_remove);
+ self.language_server_dynamic_registrations
+ .remove(server_id_to_remove);
+ self.initial_server_capabilities.remove(server_id_to_remove);
self.buffer_pull_diagnostics_result_ids
.remove(server_id_to_remove);
self.workspace_pull_diagnostics_result_ids
@@ -4344,33 +4443,22 @@ enum ChunkFetch {
Running(CacheInlayHintsTask),
}
-fn notify_server_capabilities_updated(server: &LanguageServer, cx: &mut Context<LspStore>) {
- if let Some(capabilities) = serde_json::to_string(&server.capabilities()).ok() {
- cx.emit(LspStoreEvent::LanguageServerUpdate {
- language_server_id: server.server_id(),
- name: Some(server.name()),
- message: proto::update_language_server::Variant::MetadataUpdated(
- proto::ServerMetadataUpdated {
- capabilities: Some(capabilities),
- binary: Some(proto::LanguageServerBinaryInfo {
- path: server.binary().path.to_string_lossy().into_owned(),
- arguments: server
- .binary()
- .arguments
- .iter()
- .map(|arg| arg.to_string_lossy().into_owned())
- .collect(),
- }),
- configuration: serde_json::to_string(server.configuration()).ok(),
- workspace_folders: server
- .workspace_folders()
- .iter()
- .map(|uri| uri.to_string())
- .collect(),
- },
- ),
- });
- }
+#[derive(serde::Serialize, serde::Deserialize)]
+struct SyncedServerCapabilities {
+ #[serde(flatten)]
+ server_capabilities: lsp::ServerCapabilities,
+ #[serde(
+ rename = "zedInitialServerCapabilities",
+ default,
+ skip_serializing_if = "Option::is_none"
+ )]
+ initial_server_capabilities: Option<lsp::ServerCapabilities>,
+ #[serde(
+ rename = "zedTextDocumentRegistrations",
+ default,
+ skip_serializing_if = "Option::is_none"
+ )]
+ text_document_registrations: Option<dynamic_registration::TextDocumentRegistrations>,
}
#[derive(Debug)]
@@ -4412,6 +4500,9 @@ pub struct LspStore {
diagnostic_summaries:
HashMap<WorktreeId, HashMap<Arc<RelPath>, HashMap<LanguageServerId, DiagnosticSummary>>>,
pub lsp_server_capabilities: HashMap<LanguageServerId, lsp::ServerCapabilities>,
+ lsp_server_initial_capabilities: HashMap<LanguageServerId, lsp::ServerCapabilities>,
+ lsp_server_text_document_registrations:
+ HashMap<LanguageServerId, dynamic_registration::TextDocumentRegistrations>,
semantic_token_config: SemanticTokenConfig,
lsp_data: HashMap<BufferId, BufferLspData>,
buffer_reload_tasks: HashMap<BufferId, Task<anyhow::Result<()>>>,
@@ -4655,7 +4746,14 @@ impl LspStore {
client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
client.add_entity_request_handler(Self::handle_lsp_command::<GetDocumentSymbols>);
client.add_entity_request_handler(Self::handle_lsp_command::<PrepareRename>);
- client.add_entity_request_handler(Self::handle_lsp_command::<PerformRename>);
+ client.add_entity_request_handler(|lsp_store, envelope, cx| {
+ Self::handle_routed_lsp_command::<PerformRename>(lsp_store, envelope, cx, |request| {
+ request
+ .language_server_id
+ .map(LanguageServerToQuery::Other)
+ .unwrap_or(LanguageServerToQuery::FirstCapable)
+ })
+ });
client.add_entity_request_handler(Self::handle_lsp_command::<LinkedEditingRange>);
client.add_entity_request_handler(Self::handle_lsp_ext_cancel_flycheck);
@@ -4756,6 +4854,7 @@ impl LspStore {
language_server_watched_paths: Default::default(),
language_server_paths_watched_for_rename: Default::default(),
language_server_dynamic_registrations: Default::default(),
+ initial_server_capabilities: HashMap::default(),
buffers_being_formatted: Default::default(),
buffers_to_refresh_hash_set: HashSet::default(),
buffers_to_refresh_queue: VecDeque::new(),
@@ -4799,6 +4898,8 @@ impl LspStore {
nonce: StdRng::from_os_rng().random(),
diagnostic_summaries: HashMap::default(),
lsp_server_capabilities: HashMap::default(),
+ lsp_server_initial_capabilities: HashMap::default(),
+ lsp_server_text_document_registrations: HashMap::default(),
semantic_token_config: SemanticTokenConfig::new(cx),
lsp_data: HashMap::default(),
buffer_reload_tasks: HashMap::default(),
@@ -4860,6 +4961,8 @@ impl LspStore {
nonce: StdRng::from_os_rng().random(),
diagnostic_summaries: HashMap::default(),
lsp_server_capabilities: HashMap::default(),
+ lsp_server_initial_capabilities: HashMap::default(),
+ lsp_server_text_document_registrations: HashMap::default(),
semantic_token_config: SemanticTokenConfig::new(cx),
next_hint_id: Arc::default(),
lsp_data: HashMap::default(),
@@ -5603,14 +5706,10 @@ impl LspStore {
where
R: LspCommand,
{
- self.check_if_capable_for_proto_request(
+ self.check_if_any_relevant_text_document_server_matches(
buffer,
- |capabilities| {
- request.check_capabilities(AdapterServerCapabilities {
- server_capabilities: capabilities.clone(),
- code_action_kinds: None,
- })
- },
+ <R::LspRequest as lsp::request::Request>::METHOD,
+ |_, capabilities| request.check_capabilities(capabilities),
cx,
)
}
@@ -5650,36 +5749,218 @@ impl LspStore {
.collect()
}
- fn check_if_any_relevant_server_matches<F>(
+ fn synced_server_capabilities(&self, server: &LanguageServer) -> SyncedServerCapabilities {
+ let (initial_server_capabilities, text_document_registrations) = self
+ .as_local()
+ .map(|local| {
+ let initial_server_capabilities = local
+ .initial_server_capabilities
+ .get(&server.server_id())
+ .cloned();
+ let text_document_registrations = local
+ .language_server_dynamic_registrations
+ .get(&server.server_id())
+ .map(|registrations| {
+ registrations
+ .text_documents
+ .iter()
+ .filter(|(_, registrations)| !registrations.is_empty())
+ .map(|(method, registrations)| (method.clone(), registrations.clone()))
+ .collect::<dynamic_registration::TextDocumentRegistrations>()
+ })
+ .filter(|registrations| !registrations.is_empty());
+ (initial_server_capabilities, text_document_registrations)
+ })
+ .unwrap_or_default();
+ SyncedServerCapabilities {
+ server_capabilities: server.capabilities(),
+ initial_server_capabilities,
+ text_document_registrations,
+ }
+ }
+
+ fn serialize_synced_server_capabilities(
+ &self,
+ server: &LanguageServer,
+ ) -> serde_json::Result<String> {
+ serde_json::to_string(&self.synced_server_capabilities(server))
+ }
+
+ fn notify_server_capabilities_updated(&self, server: &LanguageServer, cx: &mut Context<Self>) {
+ if let Some(capabilities) = self.serialize_synced_server_capabilities(server).log_err() {
+ cx.emit(LspStoreEvent::LanguageServerUpdate {
+ language_server_id: server.server_id(),
+ name: Some(server.name()),
+ message: proto::update_language_server::Variant::MetadataUpdated(
+ proto::ServerMetadataUpdated {
+ capabilities: Some(capabilities),
+ binary: Some(proto::LanguageServerBinaryInfo {
+ path: server.binary().path.to_string_lossy().into_owned(),
+ arguments: server
+ .binary()
+ .arguments
+ .iter()
+ .map(|arg| arg.to_string_lossy().into_owned())
+ .collect(),
+ }),
+ configuration: serde_json::to_string(server.configuration()).ok(),
+ workspace_folders: server
+ .workspace_folders()
+ .iter()
+ .map(|uri| uri.to_string())
+ .collect(),
+ },
+ ),
+ });
+ }
+ }
+
+ pub(crate) fn insert_synced_server_capabilities(
+ &mut self,
+ server_id: LanguageServerId,
+ capabilities_json: &str,
+ ) {
+ if let Some(capabilities) =
+ serde_json::from_str::<SyncedServerCapabilities>(capabilities_json).log_err()
+ {
+ self.lsp_server_capabilities
+ .insert(server_id, capabilities.server_capabilities);
+ match capabilities.initial_server_capabilities {
+ Some(capabilities) => {
+ self.lsp_server_initial_capabilities
+ .insert(server_id, capabilities);
+ }
+ None => {
+ self.lsp_server_initial_capabilities.remove(&server_id);
+ }
+ }
+ match capabilities.text_document_registrations {
+ Some(registrations) => {
+ self.lsp_server_text_document_registrations
+ .insert(server_id, registrations);
+ }
+ None => {
+ self.lsp_server_text_document_registrations
+ .remove(&server_id);
+ }
+ }
+ }
+ }
+
+ fn remote_document_selector_context(
+ &self,
+ server_id: LanguageServerId,
+ language: Option<&LanguageName>,
+ ) -> Option<DocumentSelectorContext> {
+ let language = language?;
+ let server_name = &self.language_server_statuses.get(&server_id)?.name;
+ // Without the host's adapter we cannot compute its language id. Callers that the host
+ // re-filters may fail open, while consumers of synced metadata must fail closed.
+ let language_id = self
+ .languages
+ .lsp_adapters(language)
+ .iter()
+ .find(|adapter| &adapter.name() == server_name)
+ .map(|adapter| adapter.language_id(language))?;
+ Some(DocumentSelectorContext {
+ language_id,
+ scheme: "file",
+ })
+ }
+
+ fn remote_text_document_capability_matches(
+ &self,
+ buffer: &Entity<Buffer>,
+ server_id: LanguageServerId,
+ method: &str,
+ check: impl FnMut(AdapterServerCapabilities<'_>) -> bool,
+ cx: &App,
+ ) -> bool {
+ let registration_method = text_document_registration_method(method);
+ let language = buffer.read(cx).language().map(|language| language.name());
+ let context = self.remote_document_selector_context(server_id, language.as_ref());
+ remote_text_document_capabilities_match(
+ self.lsp_server_initial_capabilities.get(&server_id),
+ self.lsp_server_capabilities.get(&server_id),
+ self.lsp_server_text_document_registrations
+ .get(&server_id)
+ .and_then(|registrations| registrations.get(registration_method)),
+ context.as_ref(),
+ check,
+ )
+ }
+
+ pub(crate) fn text_document_capability_matches_for_server(
+ &self,
+ buffer: &Entity<Buffer>,
+ server_id: LanguageServerId,
+ method: &str,
+ mut check: impl FnMut(AdapterServerCapabilities<'_>) -> bool,
+ cx: &mut App,
+ ) -> bool {
+ if let Some(local) = self.as_local() {
+ return buffer.update(cx, |buffer, cx| {
+ let Some((adapter, server)) = local
+ .language_servers_for_buffer(buffer, cx)
+ .find(|(_, server)| server.server_id() == server_id)
+ else {
+ return false;
+ };
+ text_document_capabilities_for_buffer(local, method, buffer, adapter, server)
+ .any(&mut check)
+ });
+ }
+
+ self.remote_text_document_capability_matches(buffer, server_id, method, check, cx)
+ }
+
+ fn check_if_any_relevant_text_document_server_matches<F>(
&self,
buffer: &Entity<Buffer>,
+ method: &str,
mut check: F,
cx: &App,
) -> bool
where
- F: FnMut(&LanguageServerStatus, &lsp::ServerCapabilities) -> bool,
+ F: FnMut(&lsp::LanguageServerName, AdapterServerCapabilities<'_>) -> bool,
{
+ if let Some(local) = self.as_local() {
+ let buffer = buffer.read(cx);
+ return local
+ .buffers_opened_in_servers
+ .get(&buffer.remote_id())
+ .into_iter()
+ .flatten()
+ .filter_map(|server_id| match local.language_servers.get(server_id)? {
+ LanguageServerState::Running {
+ adapter, server, ..
+ } => Some((adapter, server)),
+ _ => None,
+ })
+ .any(|(adapter, server)| {
+ let server_name = server.name();
+ text_document_capabilities_for_buffer(local, method, buffer, adapter, server)
+ .any(|capabilities| check(&server_name, capabilities))
+ });
+ }
+
self.relevant_server_ids_for_capability_check(buffer, cx)
.into_iter()
.filter_map(|server_id| {
Some((
- self.language_server_statuses.get(&server_id)?,
- self.lsp_server_capabilities.get(&server_id)?,
+ server_id,
+ &self.language_server_statuses.get(&server_id)?.name,
))
})
- .any(|(server_status, capabilities)| check(server_status, capabilities))
- }
-
- fn check_if_capable_for_proto_request<F>(
- &self,
- buffer: &Entity<Buffer>,
- mut check: F,
- cx: &App,
- ) -> bool
- where
- F: FnMut(&lsp::ServerCapabilities) -> bool,
- {
- self.check_if_any_relevant_server_matches(buffer, |_, capabilities| check(capabilities), cx)
+ .any(|(server_id, server_name)| {
+ self.remote_text_document_capability_matches(
+ buffer,
+ server_id,
+ method,
+ |capabilities| check(server_name, capabilities),
+ cx,
+ )
+ })
}
pub fn supports_range_formatting(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
@@ -5689,28 +5970,41 @@ impl LspStore {
Formatter::None => false,
Formatter::Auto => {
settings.prettier.allowed
- || self.check_if_capable_for_proto_request(
+ || self.check_if_any_relevant_text_document_server_matches(
buffer,
- server_capabilities_support_range_formatting,
+ "textDocument/rangeFormatting",
+ |_, capabilities| {
+ server_capabilities_support_range_formatting(
+ &capabilities.server_capabilities,
+ )
+ },
cx,
)
}
Formatter::Prettier => true,
Formatter::External { .. } => false,
Formatter::LanguageServer(settings::LanguageServerFormatterSpecifier::Current) => {
- self.check_if_capable_for_proto_request(
+ self.check_if_any_relevant_text_document_server_matches(
buffer,
- server_capabilities_support_range_formatting,
+ "textDocument/rangeFormatting",
+ |_, capabilities| {
+ server_capabilities_support_range_formatting(
+ &capabilities.server_capabilities,
+ )
+ },
cx,
)
}
Formatter::LanguageServer(
settings::LanguageServerFormatterSpecifier::Specific { name },
- ) => self.check_if_any_relevant_server_matches(
+ ) => self.check_if_any_relevant_text_document_server_matches(
buffer,
- |server_status, capabilities| {
- server_status.name.0.as_ref() == name
- && server_capabilities_support_range_formatting(capabilities)
+ "textDocument/rangeFormatting",
+ |server_name, capabilities| {
+ server_name.0.as_ref() == name
+ && server_capabilities_support_range_formatting(
+ &capabilities.server_capabilities,
+ )
},
cx,
),
@@ -5725,11 +6019,12 @@ impl LspStore {
fn all_capable_for_proto_request<F>(
&self,
buffer: &Entity<Buffer>,
+ method: &str,
mut check: F,
cx: &App,
) -> Vec<(lsp::LanguageServerId, lsp::LanguageServerName)>
where
- F: FnMut(&lsp::LanguageServerName, &lsp::ServerCapabilities) -> bool,
+ F: FnMut(&lsp::LanguageServerName, AdapterServerCapabilities<'_>) -> bool,
{
self.relevant_server_ids_for_capability_check(buffer, cx)
.into_iter()
@@ -5737,11 +6032,18 @@ impl LspStore {
Some((
server_id,
&self.language_server_statuses.get(&server_id)?.name,
- self.lsp_server_capabilities.get(&server_id)?,
))
})
- .filter(|(_, server_name, capabilities)| check(server_name, capabilities))
- .map(|(server_id, server_name, _)| (server_id, server_name.clone()))
+ .filter(|(server_id, server_name)| {
+ self.remote_text_document_capability_matches(
+ buffer,
+ *server_id,
+ method,
+ |capabilities| check(server_name, capabilities),
+ cx,
+ )
+ })
+ .map(|(server_id, server_name)| (server_id, server_name.clone()))
.collect()
}
@@ -5767,24 +6069,48 @@ impl LspStore {
);
}
- let Some(language_server) = buffer.update(cx, |buffer, cx| match server {
- LanguageServerToQuery::FirstCapable => self.as_local().and_then(|local| {
- local
- .language_servers_for_buffer(buffer, cx)
- .find(|(_, server)| {
- request.check_capabilities(server.adapter_server_capabilities())
- })
- .map(|(_, server)| server.clone())
- }),
- LanguageServerToQuery::Other(id) => self
- .language_server_for_local_buffer(buffer, id, cx)
- .and_then(|(_, server)| {
- request
- .check_capabilities(server.adapter_server_capabilities())
- .then(|| Arc::clone(server))
- }),
- }) else {
- return Task::ready(Ok(Default::default()));
+ let query_outcome = buffer.update(cx, |buffer, cx| {
+ let mut early_response = None;
+ if let Some(local) = self.as_local() {
+ for (adapter, language_server) in local.language_servers_for_buffer(buffer, cx) {
+ if let LanguageServerToQuery::Other(id) = server
+ && language_server.server_id() != id
+ {
+ continue;
+ }
+ let mut applicable_capabilities =
+ applicable_lsp_command_capabilities_for_buffer(
+ local,
+ &request,
+ buffer,
+ adapter,
+ language_server,
+ )
+ .peekable();
+ if applicable_capabilities.peek().is_some() {
+ match request.response_without_request(&mut applicable_capabilities) {
+ None => {
+ return LanguageServerQueryOutcome::Query(Arc::clone(
+ language_server,
+ ));
+ }
+ Some(response) => {
+ if early_response.is_none() {
+ early_response = Some(response);
+ }
+ }
+ }
+ }
+ if let LanguageServerToQuery::Other(_) = server {
+ break;
+ }
+ }
+ }
+ LanguageServerQueryOutcome::Respond(early_response.unwrap_or_default())
+ });
+ let language_server = match query_outcome {
+ LanguageServerQueryOutcome::Query(language_server) => language_server,
+ LanguageServerQueryOutcome::Respond(response) => return Task::ready(Ok(response)),
};
let file = File::from_dyn(buffer.read(cx).file()).and_then(File::as_local);
@@ -5793,27 +6119,22 @@ impl LspStore {
return Task::ready(Ok(Default::default()));
};
- let lsp_params = match request.to_lsp_params_or_response(
- &file.abs_path(cx),
- buffer.read(cx),
- &language_server,
- cx,
- ) {
- Ok(LspParamsOrResponse::Params(lsp_params)) => lsp_params,
- Ok(LspParamsOrResponse::Response(response)) => return Task::ready(Ok(response)),
- Err(err) => {
- let err = err.context(format!(
- "{} via {} failed",
- request.display_name(),
- language_server.name(),
- ));
- let message = format!("{err:#}");
- if should_log_lsp_request_failure(&message) {
- log::warn!("{message}");
+ let lsp_params =
+ match request.to_lsp(&file.abs_path(cx), buffer.read(cx), &language_server, cx) {
+ Ok(lsp_params) => lsp_params,
+ Err(err) => {
+ let err = err.context(format!(
+ "{} via {} failed",
+ request.display_name(),
+ language_server.name(),
+ ));
+ let message = format!("{err:#}");
+ if should_log_lsp_request_failure(&message) {
+ log::warn!("{message}");
+ }
+ return Task::ready(Err(err));
}
- return Task::ready(Err(err));
- }
- };
+ };
let status = request.status();
let request_timeout = ProjectSettings::get_global(cx)
@@ -6087,6 +6408,33 @@ impl LspStore {
}
}
+ fn can_resolve_lsp_action_for_buffer(
+ &self,
+ buffer: &Entity<Buffer>,
+ action: &CodeAction,
+ cx: &mut App,
+ ) -> bool {
+ match &action.lsp_action {
+ LspAction::Action(_) => self.text_document_capability_matches_for_server(
+ buffer,
+ action.server_id,
+ "textDocument/codeAction",
+ |capabilities| {
+ GetCodeActions::can_resolve_actions(capabilities.server_capabilities)
+ },
+ cx,
+ ),
+ LspAction::CodeLens(_) => self.text_document_capability_matches_for_server(
+ buffer,
+ action.server_id,
+ "textDocument/codeLens",
+ |capabilities| GetCodeLens::can_resolve_lens(capabilities.server_capabilities),
+ cx,
+ ),
+ LspAction::Command(_) => false,
+ }
+ }
+
pub fn apply_code_action(
&self,
buffer_handle: Entity<Buffer>,
@@ -6115,6 +6463,7 @@ impl LspStore {
.await
})
} else if self.mode.is_local() {
+ let can_resolve = self.can_resolve_lsp_action_for_buffer(&buffer_handle, &action, cx);
let Some((_, lang_server, request_timeout)) = buffer_handle.update(cx, |buffer, cx| {
let request_timeout = ProjectSettings::get_global(cx)
.global_lsp_settings
@@ -6126,9 +6475,14 @@ impl LspStore {
};
cx.spawn(async move |this, cx| {
- LocalLspStore::try_resolve_code_action(&lang_server, &mut action, request_timeout)
- .await
- .context("resolving a code action")?;
+ LocalLspStore::try_resolve_code_action(
+ &lang_server,
+ &mut action,
+ can_resolve,
+ request_timeout,
+ )
+ .await
+ .context("resolving a code action")?;
if let Some(edit) = action.lsp_action.edit()
&& (edit.changes.is_some() || edit.document_changes.is_some())
{
@@ -6209,6 +6563,10 @@ impl LspStore {
if action.resolved {
return Task::ready(Ok(action));
}
+ if !self.can_resolve_lsp_action_for_buffer(buffer, &action, cx) {
+ action.resolved = true;
+ return Task::ready(Ok(action));
+ }
if let Some((upstream_client, project_id)) = self.upstream_client() {
let request = proto::ResolveCodeAction {
project_id,
@@ -6235,9 +6593,14 @@ impl LspStore {
.global_lsp_settings
.get_request_timeout();
cx.background_spawn(async move {
- LocalLspStore::try_resolve_code_action(&lang_server, &mut action, request_timeout)
- .await
- .context("resolving a code action")?;
+ LocalLspStore::try_resolve_code_action(
+ &lang_server,
+ &mut action,
+ true,
+ request_timeout,
+ )
+ .await
+ .context("resolving a code action")?;
Ok(action)
})
} else {
@@ -6399,7 +6762,7 @@ impl LspStore {
local
.language_servers_for_buffer(buffer, cx)
.filter(|(_, server)| {
- LinkedEditingRange::check_server_capabilities(server.capabilities())
+ LinkedEditingRange::check_server_capabilities(&server.capabilities())
})
.filter(|(adapter, _)| {
scope
@@ -6445,10 +6808,14 @@ impl LspStore {
cx: &mut Context<Self>,
) -> Task<Result<Option<Transaction>>> {
if let Some((client, project_id)) = self.upstream_client() {
- if !self.check_if_capable_for_proto_request(
+ if !self.check_if_any_relevant_text_document_server_matches(
&buffer,
- |capabilities| {
- OnTypeFormatting::supports_on_type_formatting(&trigger, capabilities)
+ "textDocument/onTypeFormatting",
+ |_, capabilities| {
+ OnTypeFormatting::supports_on_type_formatting(
+ &trigger,
+ &capabilities.server_capabilities,
+ )
},
cx,
) {
@@ -6513,9 +6880,15 @@ impl LspStore {
push_to_history: bool,
cx: &mut Context<Self>,
) -> Option<Task<Result<Option<Transaction>>>> {
- if !self.check_if_capable_for_proto_request(
+ if !self.check_if_any_relevant_text_document_server_matches(
&buffer,
- |capabilities| OnTypeFormatting::supports_on_type_formatting(&trigger, capabilities),
+ "textDocument/onTypeFormatting",
+ |_, capabilities| {
+ OnTypeFormatting::supports_on_type_formatting(
+ &trigger,
+ &capabilities.server_capabilities,
+ )
+ },
cx,
) {
return None;
@@ -7084,10 +7457,6 @@ impl LspStore {
let server_id = item.server_id;
if let Some((upstream_client, project_id)) = self.upstream_client() {
let request = GetIncomingCalls { item };
- if !self.is_capable_for_proto_request(&buffer, &request, cx) {
- return Task::ready(Ok(None));
- }
-
let request_timeout = ProjectSettings::get_global(cx)
.global_lsp_settings
.get_request_timeout();
@@ -7144,10 +7513,6 @@ impl LspStore {
let server_id = item.server_id;
if let Some((upstream_client, project_id)) = self.upstream_client() {
let request = GetOutgoingCalls { item };
- if !self.is_capable_for_proto_request(&buffer, &request, cx) {
- return Task::ready(Ok(None));
- }
-
let request_timeout = ProjectSettings::get_global(cx)
.global_lsp_settings
.get_request_timeout();
@@ -7286,8 +7651,12 @@ impl LspStore {
let scope = snapshot.language_scope_at(offset);
let capable_lsps = self.all_capable_for_proto_request(
buffer,
+ "textDocument/completion",
|server_name, capabilities| {
- capabilities.completion_provider.is_some()
+ capabilities
+ .server_capabilities
+ .completion_provider
+ .is_some()
&& scope
.as_ref()
.map(|scope| scope.language_allowed(server_name))
@@ -7368,10 +7737,17 @@ impl LspStore {
return Task::ready(Ok(Vec::new()));
}
+ let request = GetCompletions {
+ position,
+ context: context.clone(),
+ server_id: None,
+ };
let server_ids: Vec<_> = buffer.update(cx, |buffer, cx| {
local
.language_servers_for_buffer(buffer, cx)
- .filter(|(_, server)| server.capabilities().completion_provider.is_some())
+ .filter(|(adapter, server)| {
+ lsp_command_allowed_for_buffer(local, &request, buffer, adapter, server)
+ })
.filter(|(adapter, _)| {
scope
.as_ref()
@@ -7467,14 +7843,24 @@ impl LspStore {
let client = self.upstream_client();
let buffer_id = buffer.read(cx).remote_id();
let buffer_snapshot = buffer.read(cx).snapshot();
+ let resolvable_servers = completion_indices
+ .iter()
+ .filter_map(|&completion_index| {
+ completions.borrow()[completion_index].source.server_id()
+ })
+ .filter(|&server_id| {
+ self.text_document_capability_matches_for_server(
+ &buffer,
+ server_id,
+ "textDocument/completion",
+ |capabilities| {
+ GetCompletions::can_resolve_completions(capabilities.server_capabilities)
+ },
+ cx,
+ )
+ })
+ .collect::<HashSet<_>>();
- if !self.check_if_capable_for_proto_request(
- &buffer,
- GetCompletions::can_resolve_completions,
- cx,
- ) {
- return Task::ready(Ok(false));
- }
cx.spawn(async move |lsp_store, cx| {
let request_timeout = cx.update(|app| {
ProjectSettings::get_global(app)
@@ -7490,6 +7876,9 @@ impl LspStore {
completion.source.server_id()
};
if let Some(server_id) = server_id {
+ if !resolvable_servers.contains(&server_id) {
+ continue;
+ }
if Self::resolve_completion_remote(
project_id,
server_id,
@@ -7518,6 +7907,9 @@ impl LspStore {
completion.source.server_id()
};
if let Some(server_id) = server_id {
+ if !resolvable_servers.contains(&server_id) {
+ continue;
+ }
let server_and_adapter = lsp_store
.read_with(cx, |lsp_store, _| {
let server = lsp_store.language_server_for_id(server_id)?;
@@ -7536,6 +7928,7 @@ impl LspStore {
completions.clone(),
completion_index,
request_timeout,
+ true,
)
.await
.log_err()
@@ -7569,9 +7962,10 @@ impl LspStore {
completions: Rc<RefCell<Box<[Completion]>>>,
completion_index: usize,
request_timeout: Duration,
+ can_resolve: bool,
) -> Result<()> {
let server_id = server.server_id();
- if !GetCompletions::can_resolve_completions(&server.capabilities()) {
+ if !can_resolve {
return Ok(());
}
@@ -7879,14 +8273,21 @@ impl LspStore {
.global_lsp_settings
.get_request_timeout();
+ let Some(server_id) = completions.borrow()[completion_index].source.server_id() else {
+ return Task::ready(Ok(None));
+ };
+ let can_resolve = self.text_document_capability_matches_for_server(
+ &buffer_handle,
+ server_id,
+ "textDocument/completion",
+ |capabilities| {
+ GetCompletions::can_resolve_completions(capabilities.server_capabilities)
+ },
+ cx,
+ );
let Some(server) = buffer_handle.update(cx, |buffer, cx| {
- let completion = &completions.borrow()[completion_index];
- let server_id = completion.source.server_id()?;
- Some(
- self.language_server_for_local_buffer(buffer, server_id, cx)?
- .1
- .clone(),
- )
+ self.language_server_for_local_buffer(buffer, server_id, cx)
+ .map(|(_, server)| server.clone())
}) else {
return Task::ready(Ok(None));
};
@@ -7897,6 +8298,7 @@ impl LspStore {
completions.clone(),
completion_index,
request_timeout,
+ can_resolve,
)
.await
.context("resolving completion")?;
@@ -7974,40 +8376,23 @@ impl LspStore {
}
}
- pub fn pull_diagnostics(
- &mut self,
- buffer: Entity<Buffer>,
- cx: &mut Context<Self>,
- ) -> Task<Result<Option<Vec<LspPullDiagnostics>>>> {
- let buffer_id = buffer.read(cx).remote_id();
-
- if let Some((client, upstream_project_id)) = self.upstream_client() {
- let mut suitable_capabilities = None;
- // Are we capable for proto request?
- let any_server_has_diagnostics_provider = self.check_if_capable_for_proto_request(
- &buffer,
- |capabilities| {
- if let Some(caps) = &capabilities.diagnostic_provider {
- suitable_capabilities = Some(caps.clone());
- true
- } else {
- false
- }
- },
- cx,
- );
- // We don't really care which caps are passed into the request, as they're ignored by RPC anyways.
- let Some(dynamic_caps) = suitable_capabilities else {
- return Task::ready(Ok(None));
- };
- assert!(any_server_has_diagnostics_provider);
+ pub fn pull_diagnostics(
+ &mut self,
+ buffer: Entity<Buffer>,
+ cx: &mut Context<Self>,
+ ) -> Task<Result<Option<Vec<LspPullDiagnostics>>>> {
+ let buffer_id = buffer.read(cx).remote_id();
- let identifier = buffer_diagnostic_identifier(&dynamic_caps);
+ if let Some((client, upstream_project_id)) = self.upstream_client() {
+ // We don't really care which caps are passed into the request, as they're ignored by RPC anyways.
let request = GetDocumentDiagnostics {
previous_result_id: None,
- identifier,
+ identifier: None,
registration_id: None,
};
+ if !self.is_capable_for_proto_request(&buffer, &request, cx) {
+ return Task::ready(Ok(None));
+ }
let request_timeout = ProjectSettings::get_global(cx)
.global_lsp_settings
.get_request_timeout();
@@ -8028,28 +8413,48 @@ impl LspStore {
} else {
let servers = buffer.update(cx, |buffer, cx| {
self.running_language_servers_for_local_buffer(buffer, cx)
- .map(|(_, server)| server.clone())
+ .map(|(adapter, server)| (adapter.clone(), server.clone()))
.collect::<Vec<_>>()
});
let pull_diagnostics = servers
.into_iter()
- .flat_map(|server| {
+ .flat_map(|(adapter, server)| {
let result = maybe!({
let local = self.as_local()?;
let server_id = server.server_id();
- let providers_with_identifiers = local
+ let mut providers_with_identifiers = Vec::new();
+ if let Some(provider) = local
+ .initial_server_capabilities
+ .get(&server_id)
+ .and_then(|capabilities| capabilities.diagnostic_provider.clone())
+ {
+ providers_with_identifiers.push((None, provider));
+ }
+ if let Some(diagnostic_registrations) = local
.language_server_dynamic_registrations
.get(&server_id)
- .into_iter()
- .flat_map(|registrations| &registrations.diagnostics)
- .map(|(source, dynamic_caps)| {
- (
- source.registration_id().map(str::to_string),
- dynamic_caps.clone(),
- )
+ .and_then(|registrations| {
+ registrations.text_documents.get("textDocument/diagnostic")
})
- .collect::<Vec<_>>();
+ {
+ for (registration_id, registration) in diagnostic_registrations {
+ if !dynamic_text_document_registration_allows_buffer(
+ registration,
+ buffer.read(cx),
+ &adapter,
+ ) {
+ continue;
+ }
+ let Some(provider) =
+ registration.server_capabilities.diagnostic_provider.clone()
+ else {
+ continue;
+ };
+ providers_with_identifiers
+ .push((Some(registration_id.clone()), provider));
+ }
+ }
Some(
providers_with_identifiers
.into_iter()
@@ -8130,7 +8535,10 @@ impl LspStore {
cx: &mut Context<Self>,
) -> HashMap<Range<BufferRow>, Task<Result<CacheInlayHints>>> {
let next_hint_id = self.next_hint_id.clone();
- let current_servers = self.relevant_server_ids_for_capability_check(&buffer, cx);
+ let capability_probe = InlayHints {
+ range: text::Anchor::min_max_range_for_buffer(buffer.read(cx).remote_id()),
+ };
+ let current_servers = self.language_server_ids_for_request(&buffer, &capability_probe, cx);
let lsp_data = self.latest_lsp_data(&buffer, cx);
let query_version = lsp_data.buffer_version.clone();
if let InvalidationStrategy::RefreshRequested { server_id } = invalidate {
@@ -8410,13 +8818,19 @@ impl LspStore {
let Some(local) = self.as_local() else {
return false;
};
- let Some(registrations) = local.language_server_dynamic_registrations.get(&server_id)
- else {
- return false;
- };
- registrations.diagnostics.iter().any(|(source, _)| {
- source.registration_id() == registration_id.as_ref().map(|id| id.as_ref())
- })
+ match registration_id {
+ Some(registration_id) => local
+ .language_server_dynamic_registrations
+ .get(&server_id)
+ .and_then(|registrations| {
+ registrations.text_documents.get("textDocument/diagnostic")
+ })
+ .is_some_and(|registrations| registrations.contains_key(registration_id.as_ref())),
+ None => local
+ .initial_server_capabilities
+ .get(&server_id)
+ .is_some_and(|capabilities| capabilities.diagnostic_provider.is_some()),
+ }
}
pub fn pull_diagnostics_for_buffer(
@@ -9291,12 +9705,29 @@ impl LspStore {
.find(|(_, s)| s.server_id() == server_id)
}
+ pub(crate) fn language_server_capable_of_lsp_request<R: LspCommand>(
+ &self,
+ buffer: &Entity<Buffer>,
+ server_id: LanguageServerId,
+ request: &R,
+ cx: &mut App,
+ ) -> bool {
+ self.text_document_capability_matches_for_server(
+ buffer,
+ server_id,
+ <R::LspRequest as lsp::request::Request>::METHOD,
+ |capabilities| request.check_capabilities(capabilities),
+ cx,
+ )
+ }
+
fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
self.diagnostic_summaries.remove(&id_to_remove);
if let Some(local) = self.as_local_mut() {
let to_remove = local.remove_worktree(id_to_remove, cx);
for server in to_remove {
self.language_server_statuses.remove(&server);
+ self.cleanup_lsp_data(server);
}
}
}
@@ -9378,7 +9809,10 @@ impl LspStore {
self.downstream_client = Some((downstream_client.clone(), project_id));
for (server_id, status) in &self.language_server_statuses {
- if let Some(server) = self.language_server_for_id(*server_id) {
+ if let Some(server) = self.language_server_for_id(*server_id)
+ && let Some(capabilities) =
+ self.serialize_synced_server_capabilities(&server).log_err()
+ {
downstream_client
.send(proto::StartLanguageServer {
project_id,
@@ -9391,8 +9825,7 @@ impl LspStore {
.as_ref()
.map(|name| name.to_proto()),
}),
- capabilities: serde_json::to_string(&server.capabilities())
- .expect("serializing server LSP capabilities"),
+ capabilities,
})
.log_err();
}
@@ -9428,10 +9861,7 @@ impl LspStore {
.zip(server_capabilities)
.map(|(server, server_capabilities)| {
let server_id = LanguageServerId(server.id as usize);
- if let Ok(server_capabilities) = serde_json::from_str(&server_capabilities) {
- self.lsp_server_capabilities
- .insert(server_id, server_capabilities);
- }
+ self.insert_synced_server_capabilities(server_id, &server_capabilities);
let name = LanguageServerName::from_proto(server.name);
let worktree = server.worktree_id.map(WorktreeId::from_proto);
@@ -9951,28 +10381,43 @@ impl LspStore {
})
}
- fn local_lsp_servers_for_buffer(
+ fn language_server_ids_for_request<R>(
&self,
buffer: &Entity<Buffer>,
- cx: &mut Context<Self>,
- ) -> Vec<LanguageServerId> {
+ request: &R,
+ cx: &mut App,
+ ) -> HashSet<LanguageServerId>
+ where
+ R: LspCommand,
+ {
let Some(local) = self.as_local() else {
- return Vec::new();
+ return self
+ .relevant_server_ids_for_capability_check(buffer, cx)
+ .into_iter()
+ .filter(|server_id| {
+ self.remote_text_document_capability_matches(
+ buffer,
+ *server_id,
+ <R::LspRequest as lsp::request::Request>::METHOD,
+ |capabilities| request.check_capabilities(capabilities),
+ cx,
+ )
+ })
+ .collect();
};
-
- let snapshot = buffer.read(cx).snapshot();
-
+ let buffer_id = buffer.read(cx).remote_id();
buffer.update(cx, |buffer, cx| {
local
.language_servers_for_buffer(buffer, cx)
+ .filter(|(adapter, server)| {
+ lsp_command_allowed_for_buffer(local, request, buffer, adapter, server)
+ })
.map(|(_, server)| server.server_id())
.filter(|server_id| {
- self.as_local().is_none_or(|local| {
- local
- .buffers_opened_in_servers
- .get(&snapshot.remote_id())
- .is_some_and(|servers| servers.contains(server_id))
- })
+ local
+ .buffers_opened_in_servers
+ .get(&buffer_id)
+ .is_some_and(|servers| servers.contains(server_id))
})
.collect()
})
@@ -10018,6 +10463,9 @@ impl LspStore {
let server_ids = buffer.update(cx, |buffer, cx| {
local
.language_servers_for_buffer(buffer, cx)
+ .filter(|(adapter, server)| {
+ lsp_command_allowed_for_buffer(local, &request, buffer, adapter, server)
+ })
.filter(|(adapter, _)| {
scope
.as_ref()
@@ -10109,9 +10557,25 @@ impl LspStore {
}
async fn handle_lsp_command<T: LspCommand>(
+ this: Entity<Self>,
+ envelope: TypedEnvelope<T::ProtoRequest>,
+ cx: AsyncApp,
+ ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
+ where
+ <T::LspRequest as lsp::request::Request>::Params: Send,
+ <T::LspRequest as lsp::request::Request>::Result: Send,
+ {
+ Self::handle_routed_lsp_command(this, envelope, cx, |request: &T| {
+ request.language_server_to_query()
+ })
+ .await
+ }
+
+ async fn handle_routed_lsp_command<T: LspCommand>(
this: Entity<Self>,
envelope: TypedEnvelope<T::ProtoRequest>,
mut cx: AsyncApp,
+ server_to_query: impl FnOnce(&T) -> LanguageServerToQuery,
) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
where
<T::LspRequest as lsp::request::Request>::Params: Send,
@@ -10129,10 +10593,10 @@ impl LspStore {
cx.clone(),
)
.await?;
- let server = request.language_server_to_query();
+ let server_to_query = server_to_query(&request);
let response = this
.update(&mut cx, |this, cx| {
- this.request_lsp(buffer_handle.clone(), server, request, cx)
+ this.request_lsp(buffer_handle.clone(), server_to_query, request, cx)
})
.await?;
this.update(&mut cx, |this, cx| {
@@ -10413,9 +10877,14 @@ impl LspStore {
.await?;
}
Request::GetIncomingCalls(get_incoming_calls) => {
+ let item_server_id = get_incoming_calls
+ .item
+ .as_ref()
+ .map(|item| LanguageServerId::from_proto(item.server_id))
+ .context("missing call hierarchy item")?;
Self::query_lsp_locally::<GetIncomingCalls>(
lsp_store,
- server_id,
+ Some(item_server_id),
sender_id,
lsp_request_id,
get_incoming_calls,
@@ -10425,9 +10894,14 @@ impl LspStore {
.await?;
}
Request::GetOutgoingCalls(get_outgoing_calls) => {
+ let item_server_id = get_outgoing_calls
+ .item
+ .as_ref()
+ .map(|item| LanguageServerId::from_proto(item.server_id))
+ .context("missing call hierarchy item")?;
Self::query_lsp_locally::<GetOutgoingCalls>(
lsp_store,
- server_id,
+ Some(item_server_id),
sender_id,
lsp_request_id,
get_outgoing_calls,
@@ -10762,21 +11236,11 @@ impl LspStore {
mut cx: AsyncApp,
) -> Result<()> {
let server = envelope.payload.server.context("invalid server")?;
- let server_capabilities =
- serde_json::from_str::<lsp::ServerCapabilities>(&envelope.payload.capabilities)
- .with_context(|| {
- format!(
- "incorrect server capabilities {}",
- envelope.payload.capabilities
- )
- })?;
lsp_store.update(&mut cx, |lsp_store, cx| {
let server_id = LanguageServerId(server.id as usize);
let server_name = LanguageServerName::from_proto(server.name.clone());
let language_name = server.language_name.map(LanguageName::from_proto);
- lsp_store
- .lsp_server_capabilities
- .insert(server_id, server_capabilities);
+ lsp_store.insert_synced_server_capabilities(server_id, &envelope.payload.capabilities);
if let Some(ref lang_name) = language_name {
lsp_store.try_register_remote_adapter_locally(&server_name, lang_name);
@@ -11520,8 +11984,19 @@ impl LspStore {
let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
let completion = this
- .read_with(&cx, |this, cx| {
+ .update(&mut cx, |this, cx| {
let id = LanguageServerId(envelope.payload.language_server_id as usize);
+ let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
+ let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
+ let can_resolve = this.text_document_capability_matches_for_server(
+ &buffer,
+ id,
+ "textDocument/completion",
+ |capabilities| {
+ GetCompletions::can_resolve_completions(capabilities.server_capabilities)
+ },
+ cx,
+ );
let server = this
.language_server_for_id(id)
.with_context(|| format!("No language server {id}"))?;
@@ -11531,12 +12006,6 @@ impl LspStore {
.get_request_timeout();
anyhow::Ok(cx.background_spawn(async move {
- let can_resolve = server
- .capabilities()
- .completion_provider
- .as_ref()
- .and_then(|options| options.resolve_provider)
- .unwrap_or(false);
if can_resolve {
server
.request::<lsp::request::ResolveCompletionItem>(
@@ -12264,6 +12733,7 @@ impl LspStore {
local
.language_server_dynamic_registrations
.remove(&server_id);
+ local.initial_server_capabilities.remove(&server_id);
let server_state = local.language_servers.remove(&server_id);
self.cleanup_lsp_data(server_id);
@@ -12811,22 +13281,15 @@ impl LspStore {
// indicating that the server is up and running and ready
let workspace_folders = workspace_folders.lock().clone();
language_server.set_workspace_folders(workspace_folders);
+ let server_capabilities = language_server.capabilities();
+ local
+ .initial_server_capabilities
+ .insert(server_id, server_capabilities.clone());
- let workspace_diagnostics_refresh_tasks = language_server
- .capabilities()
+ let workspace_diagnostics_refresh_tasks = server_capabilities
.diagnostic_provider
+ .clone()
.and_then(|provider| {
- let diagnostics = &mut local
- .language_server_dynamic_registrations
- .entry(server_id)
- .or_default()
- .diagnostics;
- if !diagnostics
- .iter()
- .any(|(source, _)| source.registration_id().is_none())
- {
- diagnostics.push((RegistrationSource::Static, provider.clone()));
- }
let workspace_refresher =
lsp_workspace_diagnostics_refresh(None, provider, language_server.clone(), cx)?;
@@ -12886,8 +13349,11 @@ impl LspStore {
Some(key.worktree_id),
));
- let server_capabilities = language_server.capabilities();
- if let Some((downstream_client, project_id)) = self.downstream_client.as_ref() {
+ if let Some((downstream_client, project_id)) = self.downstream_client.as_ref()
+ && let Some(capabilities) = self
+ .serialize_synced_server_capabilities(&language_server)
+ .log_err()
+ {
downstream_client
.send(proto::StartLanguageServer {
project_id: *project_id,
@@ -12897,8 +13363,7 @@ impl LspStore {
worktree_id: Some(key.worktree_id.to_proto()),
language_name: Some(language_name.to_proto()),
}),
- capabilities: serde_json::to_string(&server_capabilities)
- .expect("serializing server LSP capabilities"),
+ capabilities,
})
.log_err();
}
@@ -13138,6 +13603,9 @@ impl LspStore {
cx: &mut Context<Self>,
) {
if let Some(local) = self.as_local_mut() {
+ local
+ .initial_server_capabilities
+ .insert(id, server.capabilities());
local
.supplementary_language_servers
.insert(id, (name.clone(), server));
@@ -13163,6 +13631,7 @@ impl LspStore {
) {
if let Some(local) = self.as_local_mut() {
local.supplementary_language_servers.remove(&id);
+ local.initial_server_capabilities.remove(&id);
cx.emit(LspStoreEvent::SupplementaryLanguageServerRemoved(id));
}
}
@@ -13533,6 +14002,9 @@ impl LspStore {
fn cleanup_lsp_data(&mut self, for_server: LanguageServerId) {
self.lsp_server_capabilities.remove(&for_server);
+ self.lsp_server_initial_capabilities.remove(&for_server);
+ self.lsp_server_text_document_registrations
+ .remove(&for_server);
self.semantic_token_config.remove_server_data(for_server);
for lsp_data in self.lsp_data.values_mut() {
lsp_data.remove_server_data(for_server);
@@ -13697,25 +14169,29 @@ impl LspStore {
buffer_id: BufferId,
cx: &mut Context<Self>,
) {
- let Some(local) = self.as_local_mut() else {
+ let Some(buffer) = self.buffer_store.read(cx).get(buffer_id) else {
return;
};
- let Some(languages_servers) = local.buffers_opened_in_servers.get(&buffer_id).cloned()
+ let Some(language_servers) = self
+ .language_server_ids_for_opened_buffer(buffer_id)
+ .cloned()
else {
return;
};
- for server_id in languages_servers {
- let inter_file_dependencies = self.as_local().is_some_and(|local| {
- local
- .language_server_dynamic_registrations
- .get(&server_id)
- .is_some_and(|registrations| {
- registrations
- .diagnostics
- .iter()
- .any(|(_, options)| diagnostics_inter_file_dependencies(options))
- })
- });
+ for server_id in language_servers {
+ let inter_file_dependencies = self.text_document_capability_matches_for_server(
+ &buffer,
+ server_id,
+ "textDocument/diagnostic",
+ |capabilities| {
+ capabilities
+ .server_capabilities
+ .diagnostic_provider
+ .as_ref()
+ .is_some_and(diagnostics_inter_file_dependencies)
+ },
+ cx,
+ );
if inter_file_dependencies {
let _ = self.pull_document_diagnostics_for_server(server_id, Some(buffer_id), cx);
}
@@ -14201,6 +14677,258 @@ impl LspStore {
}
}
+fn document_selector_context_for_buffer(
+ buffer: &Buffer,
+ adapter: &CachedLspAdapter,
+) -> Option<DocumentSelectorContext> {
+ let language = buffer.language()?;
+ Some(document_selector_context_for_language(
+ &language.name(),
+ adapter,
+ ))
+}
+
+fn document_selector_context_for_language(
+ language: &LanguageName,
+ adapter: &CachedLspAdapter,
+) -> DocumentSelectorContext {
+ DocumentSelectorContext {
+ language_id: adapter.language_id(language),
+ scheme: "file",
+ }
+}
+
+fn document_selector_matches(
+ document_selector: Option<&lsp::DocumentSelector>,
+ context: &DocumentSelectorContext,
+) -> bool {
+ let Some(document_selector) = document_selector else {
+ return true;
+ };
+
+ document_selector.iter().any(|filter| {
+ if let Some(language) = &filter.language
+ && language != &context.language_id
+ {
+ return false;
+ }
+
+ if let Some(scheme) = &filter.scheme
+ && !scheme.eq_ignore_ascii_case(context.scheme)
+ {
+ return false;
+ }
+
+ true
+ })
+}
+
+fn remote_text_document_capabilities_match(
+ initial_capabilities: Option<&lsp::ServerCapabilities>,
+ merged_capabilities: Option<&lsp::ServerCapabilities>,
+ registrations: Option<
+ &collections::IndexMap<String, dynamic_registration::DynamicTextDocumentRegistration>,
+ >,
+ context: Option<&DocumentSelectorContext>,
+ mut check: impl FnMut(AdapterServerCapabilities<'_>) -> bool,
+) -> bool {
+ let Some(initial_capabilities) = initial_capabilities else {
+ return merged_capabilities.is_some_and(|server_capabilities| {
+ check(AdapterServerCapabilities {
+ server_capabilities,
+ code_action_kinds: None,
+ })
+ });
+ };
+
+ if check(AdapterServerCapabilities {
+ server_capabilities: initial_capabilities,
+ code_action_kinds: None,
+ }) {
+ return true;
+ }
+
+ let Some(registrations) = registrations else {
+ return false;
+ };
+ registrations.values().any(|registration| {
+ context.is_none_or(|context| {
+ document_selector_matches(registration.document_selector.as_ref(), context)
+ }) && check(AdapterServerCapabilities {
+ server_capabilities: &registration.server_capabilities,
+ code_action_kinds: None,
+ })
+ })
+}
+
+fn dynamic_text_document_registration_allows_buffer(
+ registration: &dynamic_registration::DynamicTextDocumentRegistration,
+ buffer: &Buffer,
+ adapter: &CachedLspAdapter,
+) -> bool {
+ let Some(context) = document_selector_context_for_buffer(buffer, adapter) else {
+ return true;
+ };
+
+ document_selector_matches(registration.document_selector.as_ref(), &context)
+}
+
+fn text_document_registration_method(method: &str) -> &str {
+ // Some related requests have distinct methods but share one registration method.
+ match method {
+ "textDocument/prepareRename" => "textDocument/rename",
+ "textDocument/semanticTokens/full"
+ | "textDocument/semanticTokens/full/delta"
+ | "textDocument/semanticTokens/range" => "textDocument/semanticTokens",
+ _ => method,
+ }
+}
+
+fn text_document_capabilities_for_buffer<'a>(
+ local: &'a LocalLspStore,
+ method: &str,
+ buffer: &'a Buffer,
+ adapter: &'a CachedLspAdapter,
+ server: &'a LanguageServer,
+) -> impl Iterator<Item = AdapterServerCapabilities<'a>> {
+ let code_action_kinds = server.code_action_kinds();
+ let static_capabilities = local
+ .initial_server_capabilities
+ .get(&server.server_id())
+ .map(move |server_capabilities| AdapterServerCapabilities {
+ server_capabilities,
+ code_action_kinds,
+ });
+
+ let registration_method = text_document_registration_method(method);
+ let dynamic_capabilities = local
+ .language_server_dynamic_registrations
+ .get(&server.server_id())
+ .and_then(|registrations| registrations.text_documents.get(registration_method))
+ .into_iter()
+ .flat_map(|registrations| registrations.values())
+ .filter(move |registration| {
+ dynamic_text_document_registration_allows_buffer(registration, buffer, adapter)
+ })
+ .map(move |registration| AdapterServerCapabilities {
+ server_capabilities: &registration.server_capabilities,
+ code_action_kinds,
+ });
+
+ static_capabilities.into_iter().chain(dynamic_capabilities)
+}
+
+fn applicable_lsp_command_capabilities_for_buffer<'a, R>(
+ local: &'a LocalLspStore,
+ request: &'a R,
+ buffer: &'a Buffer,
+ adapter: &'a CachedLspAdapter,
+ server: &'a LanguageServer,
+) -> impl Iterator<Item = AdapterServerCapabilities<'a>>
+where
+ R: LspCommand,
+{
+ text_document_capabilities_for_buffer(
+ local,
+ <R::LspRequest as lsp::request::Request>::METHOD,
+ buffer,
+ adapter,
+ server,
+ )
+ .filter(move |capabilities| request.check_capabilities(*capabilities))
+}
+
+fn lsp_command_allowed_for_buffer<R>(
+ local: &LocalLspStore,
+ request: &R,
+ buffer: &Buffer,
+ adapter: &CachedLspAdapter,
+ server: &LanguageServer,
+) -> bool
+where
+ R: LspCommand,
+{
+ applicable_lsp_command_capabilities_for_buffer(local, request, buffer, adapter, server)
+ .next()
+ .is_some()
+}
+
+fn buffer_supports_lsp_formatting(
+ local: &LocalLspStore,
+ buffer: &Buffer,
+ adapter: &CachedLspAdapter,
+ server: &LanguageServer,
+) -> bool {
+ text_document_capabilities_for_buffer(local, "textDocument/formatting", buffer, adapter, server)
+ .any(|capabilities| {
+ server_capabilities_support_formatting(capabilities.server_capabilities)
+ })
+}
+
+fn buffer_supports_lsp_range_formatting(
+ local: &LocalLspStore,
+ buffer: &Buffer,
+ adapter: &CachedLspAdapter,
+ server: &LanguageServer,
+) -> bool {
+ text_document_capabilities_for_buffer(
+ local,
+ "textDocument/rangeFormatting",
+ buffer,
+ adapter,
+ server,
+ )
+ .any(|capabilities| {
+ server_capabilities_support_range_formatting(capabilities.server_capabilities)
+ })
+}
+
+fn completion_trigger_characters_for_buffer(
+ local: &LocalLspStore,
+ server_id: LanguageServerId,
+ adapter: &CachedLspAdapter,
+ buffer: &Buffer,
+) -> BTreeSet<String> {
+ fn extend_triggers(triggers: &mut BTreeSet<String>, options: &lsp::CompletionOptions) {
+ if let Some(characters) = &options.trigger_characters {
+ triggers.extend(characters.iter().cloned());
+ }
+ }
+
+ let mut triggers = BTreeSet::new();
+ if let Some(options) = local
+ .initial_server_capabilities
+ .get(&server_id)
+ .and_then(|capabilities| capabilities.completion_provider.as_ref())
+ {
+ extend_triggers(&mut triggers, options);
+ }
+ if let Some(registrations) = local
+ .language_server_dynamic_registrations
+ .get(&server_id)
+ .and_then(|registrations| registrations.text_documents.get("textDocument/completion"))
+ {
+ for registration in registrations.values() {
+ if dynamic_text_document_registration_allows_buffer(registration, buffer, adapter)
+ && let Some(options) = registration
+ .server_capabilities
+ .completion_provider
+ .as_ref()
+ {
+ extend_triggers(&mut triggers, options);
+ }
+ }
+ }
+ triggers
+}
+
+fn server_capabilities_support_formatting(capabilities: &lsp::ServerCapabilities) -> bool {
+ matches!(
+ capabilities.document_formatting_provider.as_ref(),
+ Some(provider) if *provider != OneOf::Left(false)
+ )
+}
+
fn server_capabilities_support_range_formatting(capabilities: &lsp::ServerCapabilities) -> bool {
matches!(
capabilities.document_range_formatting_provider.as_ref(),
@@ -14731,6 +15459,11 @@ pub enum LanguageServerToQuery {
Other(LanguageServerId),
}
+enum LanguageServerQueryOutcome<T> {
+ Query(Arc<LanguageServer>),
+ Respond(T),
+}
+
#[derive(Default)]
struct RenamePathsWatchedForServer {
did_rename: Vec<RenameActionPredicate>,
@@ -15844,6 +16577,171 @@ mod tests {
));
assert!(should_log_lsp_request_failure("something else entirely"));
}
+ #[test]
+ fn synced_server_capabilities_wire_format_is_compatible_with_plain_capabilities() {
+ let registrations: dynamic_registration::TextDocumentRegistrations =
+ HashMap::from_iter([(
+ "textDocument/completion".to_string(),
+ collections::IndexMap::from_iter([(
+ "file-completion".to_string(),
+ dynamic_registration::DynamicTextDocumentRegistration {
+ document_selector: Some(vec![lsp::DocumentFilter {
+ language: Some("rust".to_string()),
+ scheme: Some("file".to_string()),
+ pattern: None,
+ }]),
+ server_capabilities: lsp::ServerCapabilities {
+ completion_provider: Some(lsp::CompletionOptions {
+ trigger_characters: Some(vec![".".to_string()]),
+ ..lsp::CompletionOptions::default()
+ }),
+ ..lsp::ServerCapabilities::default()
+ },
+ },
+ )]),
+ )]);
+ let server_capabilities = lsp::ServerCapabilities {
+ hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
+ ..lsp::ServerCapabilities::default()
+ };
+ let initial_server_capabilities = lsp::ServerCapabilities {
+ definition_provider: Some(lsp::OneOf::Left(true)),
+ ..lsp::ServerCapabilities::default()
+ };
+
+ let envelope = serde_json::to_string(&SyncedServerCapabilities {
+ server_capabilities: server_capabilities.clone(),
+ initial_server_capabilities: Some(initial_server_capabilities.clone()),
+ text_document_registrations: Some(registrations.clone()),
+ })
+ .unwrap();
+ let parsed_by_old_peer =
+ serde_json::from_str::<lsp::ServerCapabilities>(&envelope).unwrap();
+ assert_eq!(
+ parsed_by_old_peer, server_capabilities,
+ "peers without the extra field should parse the envelope as plain capabilities",
+ );
+ let parsed = serde_json::from_str::<SyncedServerCapabilities>(&envelope).unwrap();
+ assert_eq!(parsed.server_capabilities, server_capabilities);
+ assert_eq!(
+ parsed.initial_server_capabilities,
+ Some(initial_server_capabilities)
+ );
+ assert_eq!(parsed.text_document_registrations, Some(registrations));
+
+ let plain_capabilities = serde_json::to_string(&server_capabilities).unwrap();
+ let parsed_plain =
+ serde_json::from_str::<SyncedServerCapabilities>(&plain_capabilities).unwrap();
+ assert_eq!(
+ parsed_plain.server_capabilities, server_capabilities,
+ "payloads from peers without the extra field should parse as an envelope",
+ );
+ assert_eq!(parsed_plain.initial_server_capabilities, None);
+ assert_eq!(parsed_plain.text_document_registrations, None);
+ }
+
+ #[test]
+ fn remote_capability_check_falls_back_to_merged_capabilities_without_initial_capabilities() {
+ let merged_capabilities = rename_capabilities();
+ let context = rust_file_context();
+ assert!(
+ remote_text_document_capabilities_match(
+ None,
+ Some(&merged_capabilities),
+ None,
+ Some(&context),
+ rename_capability_check,
+ ),
+ "old hosts send only merged capabilities, which must be consulted",
+ );
+ }
+
+ #[test]
+ fn remote_capability_check_skips_registrations_with_non_matching_selectors() {
+ let initial_capabilities = lsp::ServerCapabilities::default();
+ let merged_capabilities = rename_capabilities();
+ let registrations = rename_registrations("python");
+ let context = rust_file_context();
+ assert!(
+ !remote_text_document_capabilities_match(
+ Some(&initial_capabilities),
+ Some(&merged_capabilities),
+ Some(&registrations),
+ Some(&context),
+ rename_capability_check,
+ ),
+ "a registration scoped to another language must not match",
+ );
+ }
+
+ #[test]
+ fn remote_capability_check_fails_open_without_selector_context() {
+ let initial_capabilities = lsp::ServerCapabilities::default();
+ let merged_capabilities = rename_capabilities();
+ let registrations = rename_registrations("python");
+ assert!(
+ remote_text_document_capabilities_match(
+ Some(&initial_capabilities),
+ Some(&merged_capabilities),
+ Some(&registrations),
+ None,
+ rename_capability_check,
+ ),
+ "without a selector context the guest must fail open and let the host re-filter",
+ );
+ }
+
+ #[test]
+ fn remote_capability_check_rejects_when_no_registration_matches() {
+ let initial_capabilities = lsp::ServerCapabilities::default();
+ let merged_capabilities = rename_capabilities();
+ let registrations = collections::IndexMap::default();
+ let context = rust_file_context();
+ assert!(
+ !remote_text_document_capabilities_match(
+ Some(&initial_capabilities),
+ Some(&merged_capabilities),
+ Some(&registrations),
+ Some(&context),
+ rename_capability_check,
+ ),
+ "initial capabilities without the capability and no registrations must not match",
+ );
+ }
+
+ fn rename_capability_check(capabilities: AdapterServerCapabilities<'_>) -> bool {
+ capabilities.server_capabilities.rename_provider.is_some()
+ }
+
+ fn rename_capabilities() -> lsp::ServerCapabilities {
+ lsp::ServerCapabilities {
+ rename_provider: Some(lsp::OneOf::Left(true)),
+ ..lsp::ServerCapabilities::default()
+ }
+ }
+
+ fn rust_file_context() -> DocumentSelectorContext {
+ DocumentSelectorContext {
+ language_id: "rust".to_string(),
+ scheme: "file",
+ }
+ }
+
+ fn rename_registrations(
+ language: &str,
+ ) -> collections::IndexMap<String, dynamic_registration::DynamicTextDocumentRegistration> {
+ collections::IndexMap::from_iter([(
+ "rename-registration".to_string(),
+ dynamic_registration::DynamicTextDocumentRegistration {
+ document_selector: Some(vec![lsp::DocumentFilter {
+ language: Some(language.to_string()),
+ scheme: Some("file".to_string()),
+ pattern: None,
+ }]),
+ server_capabilities: rename_capabilities(),
+ },
+ )])
+ }
#[test]
fn lsp_pull_cancelled_with_retrigger_follows_the_spec() {
diff --git a/crates/project/src/lsp_store/code_lens.rs b/crates/project/src/lsp_store/code_lens.rs
index 52c35e13e68..abab635f799 100644
--- a/crates/project/src/lsp_store/code_lens.rs
+++ b/crates/project/src/lsp_store/code_lens.rs
@@ -148,7 +148,7 @@ impl LspStore {
) -> CodeLensTask {
let version_queried_for = buffer.read(cx).version();
let buffer_id = buffer.read(cx).remote_id();
- let current_servers = self.relevant_server_ids_for_capability_check(buffer, cx);
+ let current_servers = self.language_server_ids_for_request(buffer, &GetCodeLens, cx);
let mut servers_to_query = None;
if let Some(lsp_data) = self.current_lsp_data(buffer_id) {
@@ -396,10 +396,17 @@ impl LspStore {
let lens = lens.clone();
let action = cached.clone();
+ if !self.text_document_capability_matches_for_server(
+ buffer,
+ server_id,
+ "textDocument/codeLens",
+ |capabilities| GetCodeLens::can_resolve_lens(capabilities.server_capabilities),
+ cx,
+ ) {
+ return Task::ready(None).shared();
+ }
+
if self.upstream_client().is_some() {
- if !self.check_if_capable_for_proto_request(buffer, GetCodeLens::can_resolve_lens, cx) {
- return Task::ready(None).shared();
- }
let resolve = self.resolve_code_action(buffer, action, cx);
let task = cx
.spawn(async move |lsp_store, cx| {
@@ -439,9 +446,6 @@ impl LspStore {
let Some(server) = self.language_server_for_id(server_id) else {
return Task::ready(None).shared();
};
- if !GetCodeLens::can_resolve_lens(&server.capabilities()) {
- return Task::ready(None).shared();
- }
let request_timeout = ProjectSettings::get_global(cx)
.global_lsp_settings
.get_request_timeout();
diff --git a/crates/project/src/lsp_store/document_colors.rs b/crates/project/src/lsp_store/document_colors.rs
index e3465eba447..f87a14edd41 100644
--- a/crates/project/src/lsp_store/document_colors.rs
+++ b/crates/project/src/lsp_store/document_colors.rs
@@ -108,7 +108,7 @@ impl LspStore {
let version_queried_for = buffer.read(cx).version();
let buffer_id = buffer.read(cx).remote_id();
- let current_servers = self.relevant_server_ids_for_capability_check(&buffer, cx);
+ let current_servers = self.language_server_ids_for_request(&buffer, &GetDocumentColor, cx);
let mut servers_to_query = None;
if let Some(lsp_data) = self.current_lsp_data(buffer_id) {
diff --git a/crates/project/src/lsp_store/document_links.rs b/crates/project/src/lsp_store/document_links.rs
index 323b37604dc..313237be00e 100644
--- a/crates/project/src/lsp_store/document_links.rs
+++ b/crates/project/src/lsp_store/document_links.rs
@@ -130,7 +130,7 @@ impl LspStore {
let version_queried_for = buffer.read(cx).version();
let buffer_id = buffer.read(cx).remote_id();
- let current_servers = self.relevant_server_ids_for_capability_check(buffer, cx);
+ let current_servers = self.language_server_ids_for_request(buffer, &GetDocumentLinks, cx);
let mut servers_to_query = None;
if let Some(lsp_data) = self.current_lsp_data(buffer_id) {
@@ -448,10 +448,17 @@ impl LspStore {
data: cached_link.data.clone(),
};
+ if !self.text_document_capability_matches_for_server(
+ buffer,
+ server_id,
+ "textDocument/documentLink",
+ |capabilities| can_resolve_link(capabilities.server_capabilities),
+ cx,
+ ) {
+ return Task::ready(None);
+ }
+
if let Some((upstream_client, project_id)) = self.upstream_client() {
- if !self.check_if_capable_for_proto_request(buffer, can_resolve_link, cx) {
- return Task::ready(None);
- }
let request = proto::ResolveDocumentLink {
project_id,
buffer_id: buffer_id.into(),
@@ -466,9 +473,6 @@ impl LspStore {
let Some(server) = self.language_server_for_id(server_id) else {
return Task::ready(None);
};
- if !can_resolve_link(&server.capabilities()) {
- return Task::ready(None);
- }
let request_timeout = ProjectSettings::get_global(cx)
.global_lsp_settings
.get_request_timeout();
diff --git a/crates/project/src/lsp_store/document_symbols.rs b/crates/project/src/lsp_store/document_symbols.rs
index adda847c47e..2a8698f1db0 100644
--- a/crates/project/src/lsp_store/document_symbols.rs
+++ b/crates/project/src/lsp_store/document_symbols.rs
@@ -107,7 +107,7 @@ impl LspStore {
let version_queried_for = buffer.read(cx).version();
let buffer_id = buffer.read(cx).remote_id();
- let current_servers = self.relevant_server_ids_for_capability_check(buffer, cx);
+ let current_servers = self.language_server_ids_for_request(buffer, &GetDocumentSymbols, cx);
let mut servers_to_query = None;
if let Some(lsp_data) = self.current_lsp_data(buffer_id) {
diff --git a/crates/project/src/lsp_store/dynamic_registration.rs b/crates/project/src/lsp_store/dynamic_registration.rs
index 9af94842dd6..b251a35cbf0 100644
--- a/crates/project/src/lsp_store/dynamic_registration.rs
+++ b/crates/project/src/lsp_store/dynamic_registration.rs
@@ -7,16 +7,16 @@
//! the active registration is unregistered.
use anyhow::{Context as _, Result};
-use collections::{BTreeSet, HashSet};
+use collections::{HashMap, HashSet, IndexMap};
use gpui::{Context, SharedString};
use lsp::{
- CompletionOptions, DiagnosticServerCapabilities, LanguageServer, LanguageServerId, OneOf,
+ DiagnosticServerCapabilities, LanguageServer, LanguageServerId, OneOf,
TextDocumentSyncSaveOptions,
};
use crate::lsp_store::{
- LanguageServerState, LspStore, RenamePathsWatchedForServer, lsp_workspace_diagnostics_refresh,
- notify_server_capabilities_updated,
+ LanguageServerState, LspStore, RenamePathsWatchedForServer,
+ completion_trigger_characters_for_buffer, lsp_workspace_diagnostics_refresh,
};
#[derive(Debug)]
@@ -36,52 +36,182 @@ impl RegistrationSource {
pub(super) type CapabilityRegistrations<T> = Vec<(RegistrationSource, T)>;
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum CapabilityUnregistration {
- NotFound,
- Removed { active_capability_changed: bool },
+#[derive(Debug, Clone, Copy)]
+struct CapabilityRegistrationChange {
+ active_capability_changed: bool,
+ text_document_registration_changed: bool,
+ registration_changed: bool,
}
-impl CapabilityUnregistration {
- fn removed(self) -> bool {
- self != CapabilityUnregistration::NotFound
+impl CapabilityRegistrationChange {
+ fn applicability_may_have_changed(self) -> bool {
+ self.active_capability_changed || self.text_document_registration_changed
}
- fn capability_changed(self) -> bool {
- self == CapabilityUnregistration::Removed {
- active_capability_changed: true,
- }
+ fn ordered_capability_may_have_changed(self) -> bool {
+ self.active_capability_changed || self.registration_changed
}
}
+#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
+pub(super) struct DynamicTextDocumentRegistration {
+ pub(super) document_selector: Option<lsp::DocumentSelector>,
+ pub(super) server_capabilities: lsp::ServerCapabilities,
+}
+
+pub(super) type TextDocumentRegistrations =
+ HashMap<String, IndexMap<String, DynamicTextDocumentRegistration>>;
+
#[derive(Default, Debug)]
pub(super) struct DynamicRegistrations {
pub(super) did_change_watched_files: HashSet<String>,
- pub(super) diagnostics: CapabilityRegistrations<DiagnosticServerCapabilities>,
+ pub(super) text_documents: TextDocumentRegistrations,
workspace_folders: CapabilityRegistrations<lsp::WorkspaceFoldersServerCapabilities>,
workspace_symbol: CapabilityRegistrations<OneOf<bool, lsp::WorkspaceSymbolOptions>>,
file_operations: CapabilityRegistrations<lsp::WorkspaceFileOperationsServerCapabilities>,
execute_command: CapabilityRegistrations<lsp::ExecuteCommandOptions>,
- range_formatting: CapabilityRegistrations<OneOf<bool, lsp::DocumentRangeFormattingOptions>>,
- on_type_formatting: CapabilityRegistrations<lsp::DocumentOnTypeFormattingOptions>,
- formatting: CapabilityRegistrations<OneOf<bool, lsp::DocumentFormattingOptions>>,
- rename: CapabilityRegistrations<OneOf<bool, lsp::RenameOptions>>,
- code_action: CapabilityRegistrations<lsp::CodeActionProviderCapability>,
- definition: CapabilityRegistrations<OneOf<bool, lsp::DefinitionOptions>>,
- completion: CapabilityRegistrations<lsp::CompletionOptions>,
- hover: CapabilityRegistrations<lsp::HoverProviderCapability>,
- signature_help: CapabilityRegistrations<lsp::SignatureHelpOptions>,
- color: CapabilityRegistrations<lsp::ColorProviderCapability>,
- folding_range: CapabilityRegistrations<lsp::FoldingRangeProviderCapability>,
- document_link: CapabilityRegistrations<lsp::DocumentLinkOptions>,
- semantic_tokens: CapabilityRegistrations<lsp::SemanticTokensServerCapabilities>,
- inlay_hint: CapabilityRegistrations<OneOf<bool, lsp::InlayHintServerCapabilities>>,
- code_lens: CapabilityRegistrations<lsp::CodeLensOptions>,
- document_symbol: CapabilityRegistrations<OneOf<bool, lsp::DocumentSymbolOptions>>,
- call_hierarchy: CapabilityRegistrations<lsp::CallHierarchyServerCapability>,
}
impl LspStore {
+ fn register_dynamic_text_document_capability<T: Clone + PartialEq>(
+ &mut self,
+ server: &LanguageServer,
+ method: &str,
+ registration_id: String,
+ options: T,
+ document_selector: Option<lsp::DocumentSelector>,
+ cx: &mut Context<Self>,
+ capability_of: impl Fn(&mut lsp::ServerCapabilities) -> &mut Option<T>,
+ ) -> anyhow::Result<CapabilityRegistrationChange> {
+ let server_id = server.server_id();
+ let local = self
+ .as_local_mut()
+ .context("Expected LSP Store to be local")?;
+ let mut server_capabilities = lsp::ServerCapabilities::default();
+ *capability_of(&mut server_capabilities) = Some(options);
+ let new_registration = DynamicTextDocumentRegistration {
+ document_selector,
+ server_capabilities,
+ };
+ let registrations = local
+ .language_server_dynamic_registrations
+ .entry(server_id)
+ .or_default()
+ .text_documents
+ .entry(method.to_owned())
+ .or_default();
+ // Guests track registrations by id, so notify on any id-visible change; caches only
+ // consume the (selector, options) value set, so refresh flags compare sets.
+ let registration_changed = registrations.get(&registration_id) != Some(&new_registration);
+ let applicable_set_changed;
+ if registrations.contains_key(&registration_id) {
+ log::warn!(
+ "Received a duplicate {method} registration with ID {registration_id}, replacing the previous one"
+ );
+ let previous_values = registrations.values().cloned().collect::<Vec<_>>();
+ registrations.insert(registration_id, new_registration);
+ applicable_set_changed = !previous_values
+ .iter()
+ .all(|previous| registrations.values().any(|current| current == previous))
+ || !registrations
+ .values()
+ .all(|current| previous_values.contains(current));
+ } else {
+ applicable_set_changed = !registrations
+ .values()
+ .any(|existing| existing == &new_registration);
+ registrations.insert(registration_id, new_registration);
+ }
+ let new_active_envelope = registrations
+ .last()
+ .map(|(_, registration)| registration.server_capabilities.clone());
+ let new_active = match new_active_envelope {
+ Some(mut envelope) => capability_of(&mut envelope).take(),
+ None => local
+ .initial_server_capabilities
+ .get(&server_id)
+ .cloned()
+ .and_then(|mut capabilities| capability_of(&mut capabilities).take()),
+ };
+ let mut current_capabilities = server.capabilities();
+ let previous_active = capability_of(&mut current_capabilities).take();
+ let active_changed = new_active != previous_active;
+ if active_changed {
+ server.update_capabilities(|capabilities| *capability_of(capabilities) = new_active);
+ }
+ if active_changed || registration_changed {
+ self.notify_server_capabilities_updated(server, cx);
+ }
+ Ok(CapabilityRegistrationChange {
+ active_capability_changed: active_changed,
+ text_document_registration_changed: applicable_set_changed,
+ registration_changed,
+ })
+ }
+
+ fn unregister_dynamic_text_document_capability<T: Clone + PartialEq>(
+ &mut self,
+ server: &LanguageServer,
+ unregistration: &lsp::Unregistration,
+ cx: &mut Context<Self>,
+ capability_of: impl Fn(&mut lsp::ServerCapabilities) -> &mut Option<T>,
+ ) -> anyhow::Result<Option<CapabilityRegistrationChange>> {
+ let server_id = server.server_id();
+ let local = self
+ .as_local_mut()
+ .context("Expected LSP Store to be local")?;
+ let Some(registrations) = local
+ .language_server_dynamic_registrations
+ .get_mut(&server_id)
+ .and_then(|dynamic_registrations| {
+ dynamic_registrations
+ .text_documents
+ .get_mut(&unregistration.method)
+ })
+ else {
+ log::warn!(
+ "Attempted to unregister non-existent {} registration with ID {}",
+ unregistration.method,
+ unregistration.id
+ );
+ return Ok(None);
+ };
+ let Some(removed) = registrations.shift_remove(&unregistration.id) else {
+ log::warn!(
+ "Attempted to unregister non-existent {} registration with ID {}",
+ unregistration.method,
+ unregistration.id
+ );
+ return Ok(None);
+ };
+ let applicable_set_changed = !registrations
+ .values()
+ .any(|remaining| remaining == &removed);
+ let new_active_envelope = registrations
+ .last()
+ .map(|(_, registration)| registration.server_capabilities.clone());
+ let new_active = match new_active_envelope {
+ Some(mut envelope) => capability_of(&mut envelope).take(),
+ None => local
+ .initial_server_capabilities
+ .get(&server_id)
+ .cloned()
+ .and_then(|mut capabilities| capability_of(&mut capabilities).take()),
+ };
+ let mut current_capabilities = server.capabilities();
+ let previous_active = capability_of(&mut current_capabilities).take();
+ let active_changed = new_active != previous_active;
+ if active_changed {
+ server.update_capabilities(|capabilities| *capability_of(capabilities) = new_active);
+ }
+ self.notify_server_capabilities_updated(server, cx);
+ Ok(Some(CapabilityRegistrationChange {
+ active_capability_changed: active_changed,
+ text_document_registration_changed: applicable_set_changed,
+ registration_changed: true,
+ }))
+ }
+
/// Returns `true` when the registration changed the server's active capability value:
/// duplicate-ID replacements of non-active registrations and (re-)registrations with
/// options identical to the active ones do not.
@@ -99,12 +229,11 @@ impl LspStore {
let local = self
.as_local_mut()
.context("Expected LSP Store to be local")?;
- let registrations = registrations_of(
- local
- .language_server_dynamic_registrations
- .entry(server_id)
- .or_default(),
- );
+ let dynamic_registrations = local
+ .language_server_dynamic_registrations
+ .entry(server_id)
+ .or_default();
+ let registrations = registrations_of(dynamic_registrations);
if registrations.is_empty() {
let mut initial_capabilities = server.capabilities();
if let Some(static_options) = capability_of(&mut initial_capabilities).take() {
@@ -127,7 +256,7 @@ impl LspStore {
let active_changed = active != previously_active;
if active_changed {
server.update_capabilities(|capabilities| *capability_of(capabilities) = active);
- notify_server_capabilities_updated(server, cx);
+ self.notify_server_capabilities_updated(server, cx);
}
Ok(active_changed)
}
@@ -139,41 +268,43 @@ impl LspStore {
cx: &mut Context<Self>,
registrations_of: impl FnOnce(&mut DynamicRegistrations) -> &mut CapabilityRegistrations<T>,
capability_of: impl FnOnce(&mut lsp::ServerCapabilities) -> &mut Option<T>,
- ) -> anyhow::Result<CapabilityUnregistration> {
+ ) -> anyhow::Result<Option<bool>> {
let server_id = server.server_id();
let local = self
.as_local_mut()
.context("Expected LSP Store to be local")?;
- let registrations = local
+ let Some(dynamic_registrations) = local
.language_server_dynamic_registrations
.get_mut(&server_id)
- .map(registrations_of);
- let index = registrations.as_ref().and_then(|registrations| {
- registrations.iter().position(|(source, _)| {
- source.registration_id() == Some(unregistration.id.as_str())
- })
- });
- let (Some(registrations), Some(index)) = (registrations, index) else {
+ else {
log::warn!(
"Attempted to unregister non-existent {} registration with ID {}",
unregistration.method,
unregistration.id
);
- return Ok(CapabilityUnregistration::NotFound);
+ return Ok(None);
+ };
+ let registrations = registrations_of(dynamic_registrations);
+ let Some(index) = registrations
+ .iter()
+ .position(|(source, _)| source.registration_id() == Some(unregistration.id.as_str()))
+ else {
+ log::warn!(
+ "Attempted to unregister non-existent {} registration with ID {}",
+ unregistration.method,
+ unregistration.id
+ );
+ return Ok(None);
};
let removed_active = index + 1 == registrations.len();
let (_, removed_options) = registrations.remove(index);
let restored = registrations.last().map(|(_, options)| options.clone());
if !removed_active || restored.as_ref() == Some(&removed_options) {
- return Ok(CapabilityUnregistration::Removed {
- active_capability_changed: false,
- });
+ return Ok(Some(false));
}
server.update_capabilities(|capabilities| *capability_of(capabilities) = restored);
- notify_server_capabilities_updated(server, cx);
- Ok(CapabilityUnregistration::Removed {
- active_capability_changed: true,
- })
+ self.notify_server_capabilities_updated(server, cx);
+ Ok(Some(true))
}
fn update_paths_watched_for_rename(&mut self, server: &LanguageServer) {
@@ -208,35 +339,31 @@ impl LspStore {
}
}
- fn apply_completion_triggers(
- &self,
- server_id: LanguageServerId,
- options: Option<CompletionOptions>,
- cx: &mut Context<Self>,
- ) {
+ fn apply_completion_triggers(&self, server_id: LanguageServerId, cx: &mut Context<Self>) {
let Some(local) = self.as_local() else {
return;
};
+ let Some(LanguageServerState::Running { adapter, .. }) =
+ local.language_servers.get(&server_id)
+ else {
+ return;
+ };
let mut buffers_with_language_server = Vec::new();
for handle in self.buffer_store.read(cx).buffers() {
let buffer_id = handle.read(cx).remote_id();
if local
.buffers_opened_in_servers
.get(&buffer_id)
- .filter(|s| s.contains(&server_id))
+ .filter(|servers| servers.contains(&server_id))
.is_some()
{
buffers_with_language_server.push(handle);
}
}
- let triggers = options
- .and_then(|options| options.trigger_characters)
- .unwrap_or_default()
- .into_iter()
- .collect::<BTreeSet<_>>();
for handle in buffers_with_language_server {
- let triggers = triggers.clone();
- handle.update(cx, move |buffer, cx| {
+ handle.update(cx, |buffer, cx| {
+ let triggers =
+ completion_trigger_characters_for_buffer(local, server_id, adapter, buffer);
buffer.set_completion_triggers(server_id, triggers, cx);
});
}
@@ -264,7 +391,7 @@ impl LspStore {
false
};
if notify {
- notify_server_capabilities_updated(&server, cx);
+ self.notify_server_capabilities_updated(&server, cx);
}
}
}
@@ -340,103 +467,125 @@ impl LspStore {
}
}
"textDocument/rangeFormatting" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
let options = parse_register_capabilities(reg.register_options)?;
- self.register_dynamic_capability(
+ self.register_dynamic_text_document_capability(
&server,
&reg.method,
reg.id,
options,
+ document_selector,
cx,
- |registrations| &mut registrations.range_formatting,
|capabilities| &mut capabilities.document_range_formatting_provider,
)?;
}
"textDocument/onTypeFormatting" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
if let Some(options) = reg
.register_options
.map(serde_json::from_value)
.transpose()?
{
- self.register_dynamic_capability(
+ self.register_dynamic_text_document_capability(
&server,
&reg.method,
reg.id,
options,
+ document_selector,
cx,
- |registrations| &mut registrations.on_type_formatting,
|capabilities| &mut capabilities.document_on_type_formatting_provider,
)?;
}
}
"textDocument/formatting" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
let options = parse_register_capabilities(reg.register_options)?;
- self.register_dynamic_capability(
+ self.register_dynamic_text_document_capability(
&server,
&reg.method,
reg.id,
options,
+ document_selector,
cx,
- |registrations| &mut registrations.formatting,
|capabilities| &mut capabilities.document_formatting_provider,
)?;
}
"textDocument/rename" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
let options = parse_register_capabilities(reg.register_options)?;
- self.register_dynamic_capability(
+ self.register_dynamic_text_document_capability(
&server,
&reg.method,
reg.id,
options,
+ document_selector,
cx,
- |registrations| &mut registrations.rename,
|capabilities| &mut capabilities.rename_provider,
)?;
}
"textDocument/inlayHint" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
let options = parse_register_capabilities(reg.register_options)?;
- if self.register_dynamic_capability(
- &server,
- &reg.method,
- reg.id,
- options,
- cx,
- |registrations| &mut registrations.inlay_hint,
- |capabilities| &mut capabilities.inlay_hint_provider,
- )? {
+ if self
+ .register_dynamic_text_document_capability(
+ &server,
+ &reg.method,
+ reg.id,
+ options,
+ document_selector,
+ cx,
+ |capabilities| &mut capabilities.inlay_hint_provider,
+ )?
+ .applicability_may_have_changed()
+ {
self.refresh_inlay_hints(server_id, cx);
}
}
"textDocument/documentSymbol" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
let options = parse_register_capabilities(reg.register_options)?;
- if self.register_dynamic_capability(
- &server,
- &reg.method,
- reg.id,
- options,
- cx,
- |registrations| &mut registrations.document_symbol,
- |capabilities| &mut capabilities.document_symbol_provider,
- )? {
+ if self
+ .register_dynamic_text_document_capability(
+ &server,
+ &reg.method,
+ reg.id,
+ options,
+ document_selector,
+ cx,
+ |capabilities| &mut capabilities.document_symbol_provider,
+ )?
+ .applicability_may_have_changed()
+ {
self.refresh_document_symbols(Some(server_id), cx);
}
}
"textDocument/codeAction" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
let options = parse_register_capabilities(reg.register_options)?;
let provider = match options {
OneOf::Left(value) => lsp::CodeActionProviderCapability::Simple(value),
OneOf::Right(caps) => caps,
};
- self.register_dynamic_capability(
+ self.register_dynamic_text_document_capability(
&server,
&reg.method,
reg.id,
provider,
+ document_selector,
cx,
- |registrations| &mut registrations.code_action,
|capabilities| &mut capabilities.code_action_provider,
)?;
}
"textDocument/prepareCallHierarchy" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
let options = parse_register_capabilities(reg.register_options)?;
let provider = match options {
OneOf::Left(value) => lsp::CallHierarchyServerCapability::Simple(value),
@@ -444,77 +593,83 @@ impl LspStore {
lsp::CallHierarchyServerCapability::Options(options)
}
};
- self.register_dynamic_capability(
+ self.register_dynamic_text_document_capability(
&server,
&reg.method,
reg.id,
provider,
+ document_selector,
cx,
- |registrations| &mut registrations.call_hierarchy,
|capabilities| &mut capabilities.call_hierarchy_provider,
)?;
}
"textDocument/definition" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
let options = parse_register_capabilities(reg.register_options)?;
- self.register_dynamic_capability(
+ self.register_dynamic_text_document_capability(
&server,
&reg.method,
reg.id,
options,
+ document_selector,
cx,
- |registrations| &mut registrations.definition,
|capabilities| &mut capabilities.definition_provider,
)?;
}
"textDocument/completion" => {
- if let Some(caps) = reg
+ if let Some(registration_options) = reg
.register_options
- .map(serde_json::from_value::<CompletionOptions>)
+ .map(serde_json::from_value::<lsp::CompletionRegistrationOptions>)
.transpose()?
{
- if self.register_dynamic_capability(
+ self.register_dynamic_text_document_capability(
&server,
&reg.method,
reg.id,
- caps,
+ registration_options.completion_options,
+ registration_options
+ .text_document_registration_options
+ .document_selector,
cx,
- |registrations| &mut registrations.completion,
|capabilities| &mut capabilities.completion_provider,
- )? {
- let active = server.capabilities().completion_provider;
- self.apply_completion_triggers(server_id, active, cx);
- }
+ )?;
+ self.apply_completion_triggers(server_id, cx);
}
}
"textDocument/hover" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
let options = parse_register_capabilities(reg.register_options)?;
let provider = match options {
OneOf::Left(value) => lsp::HoverProviderCapability::Simple(value),
OneOf::Right(caps) => caps,
};
- self.register_dynamic_capability(
+ self.register_dynamic_text_document_capability(
&server,
&reg.method,
reg.id,
provider,
+ document_selector,
cx,
- |registrations| &mut registrations.hover,
|capabilities| &mut capabilities.hover_provider,
)?;
}
"textDocument/signatureHelp" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
if let Some(caps) = reg
.register_options
.map(serde_json::from_value)
.transpose()?
{
- self.register_dynamic_capability(
+ self.register_dynamic_text_document_capability(
&server,
&reg.method,
reg.id,
caps,
+ document_selector,
cx,
- |registrations| &mut registrations.signature_help,
|capabilities| &mut capabilities.signature_help_provider,
)?;
}
@@ -532,7 +687,7 @@ impl LspStore {
capabilities.text_document_sync =
Some(lsp::TextDocumentSyncCapability::Options(sync_options));
});
- notify_server_capabilities_updated(&server, cx);
+ self.notify_server_capabilities_updated(&server, cx);
}
}
"textDocument/didSave" => {
@@ -560,42 +715,49 @@ impl LspStore {
capabilities.text_document_sync =
Some(lsp::TextDocumentSyncCapability::Options(sync_options));
});
- notify_server_capabilities_updated(&server, cx);
+ self.notify_server_capabilities_updated(&server, cx);
}
}
"textDocument/codeLens" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
if let Some(options) = reg
.register_options
.map(serde_json::from_value)
.transpose()?
{
- if self.register_dynamic_capability(
- &server,
- &reg.method,
- reg.id,
- options,
- cx,
- |registrations| &mut registrations.code_lens,
- |capabilities| &mut capabilities.code_lens_provider,
- )? {
+ if self
+ .register_dynamic_text_document_capability(
+ &server,
+ &reg.method,
+ reg.id,
+ options,
+ document_selector,
+ cx,
+ |capabilities| &mut capabilities.code_lens_provider,
+ )?
+ .applicability_may_have_changed()
+ {
self.refresh_code_lens(Some(server_id), cx);
}
}
}
"textDocument/diagnostic" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
if let Some(caps) = reg
.register_options
.map(serde_json::from_value::<DiagnosticServerCapabilities>)
.transpose()?
{
let registration_id = reg.id.clone();
- self.register_dynamic_capability(
+ self.register_dynamic_text_document_capability(
&server,
&reg.method,
reg.id,
caps.clone(),
+ document_selector,
cx,
- |registrations| &mut registrations.diagnostics,
|capabilities| &mut capabilities.diagnostic_provider,
)?;
@@ -644,75 +806,94 @@ impl LspStore {
}
}
"textDocument/documentColor" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
let options = parse_register_capabilities(reg.register_options)?;
let provider = match options {
OneOf::Left(value) => lsp::ColorProviderCapability::Simple(value),
OneOf::Right(caps) => caps,
};
- if self.register_dynamic_capability(
- &server,
- &reg.method,
- reg.id,
- provider,
- cx,
- |registrations| &mut registrations.color,
- |capabilities| &mut capabilities.color_provider,
- )? {
+ if self
+ .register_dynamic_text_document_capability(
+ &server,
+ &reg.method,
+ reg.id,
+ provider,
+ document_selector,
+ cx,
+ |capabilities| &mut capabilities.color_provider,
+ )?
+ .applicability_may_have_changed()
+ {
self.refresh_document_colors(Some(server_id), cx);
}
}
"textDocument/foldingRange" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
let options = parse_register_capabilities(reg.register_options)?;
let provider = match options {
OneOf::Left(value) => lsp::FoldingRangeProviderCapability::Simple(value),
OneOf::Right(caps) => caps,
};
- if self.register_dynamic_capability(
- &server,
- &reg.method,
- reg.id,
- provider,
- cx,
- |registrations| &mut registrations.folding_range,
- |capabilities| &mut capabilities.folding_range_provider,
- )? {
+ if self
+ .register_dynamic_text_document_capability(
+ &server,
+ &reg.method,
+ reg.id,
+ provider,
+ document_selector,
+ cx,
+ |capabilities| &mut capabilities.folding_range_provider,
+ )?
+ .applicability_may_have_changed()
+ {
self.refresh_folding_ranges(Some(server_id), cx);
}
}
"textDocument/documentLink" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
if let Some(caps) = reg
.register_options
.map(serde_json::from_value)
.transpose()?
{
- if self.register_dynamic_capability(
- &server,
- &reg.method,
- reg.id,
- caps,
- cx,
- |registrations| &mut registrations.document_link,
- |capabilities| &mut capabilities.document_link_provider,
- )? {
+ if self
+ .register_dynamic_text_document_capability(
+ &server,
+ &reg.method,
+ reg.id,
+ caps,
+ document_selector,
+ cx,
+ |capabilities| &mut capabilities.document_link_provider,
+ )?
+ .applicability_may_have_changed()
+ {
self.refresh_document_links(Some(server_id), cx);
}
}
}
"textDocument/semanticTokens" => {
+ let document_selector =
+ parse_text_document_registration(reg.register_options.as_ref())?;
if let Some(caps) = reg
.register_options
.map(serde_json::from_value::<lsp::SemanticTokensRegistrationOptions>)
.transpose()?
{
- if self.register_dynamic_capability(
+ if self.register_dynamic_text_document_capability(
&server,
&reg.method,
reg.id,
lsp::SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(caps),
+ document_selector,
cx,
- |registrations| &mut registrations.semantic_tokens,
|capabilities| &mut capabilities.semantic_tokens_provider,
- )? {
+ )?
+ .ordered_capability_may_have_changed()
+ {
// Re-query already-open buffers, which would otherwise keep
// tree-sitter-only highlighting until edited.
self.refresh_semantic_tokens(server_id, cx);
@@ -746,7 +927,7 @@ impl LspStore {
false
};
if notify {
- notify_server_capabilities_updated(&server, cx);
+ self.notify_server_capabilities_updated(&server, cx);
}
}
"workspace/didChangeConfiguration" => {
@@ -776,20 +957,18 @@ impl LspStore {
)?;
}
"workspace/fileOperations" => {
- if self
- .unregister_dynamic_capability(
- &server,
- unreg,
- cx,
- |registrations| &mut registrations.file_operations,
- |capabilities| {
- &mut capabilities
- .workspace
- .get_or_insert_default()
- .file_operations
- },
- )?
- .capability_changed()
+ if self.unregister_dynamic_capability(
+ &server,
+ unreg,
+ cx,
+ |registrations| &mut registrations.file_operations,
+ |capabilities| {
+ &mut capabilities
+ .workspace
+ .get_or_insert_default()
+ .file_operations
+ },
+ )? == Some(true)
{
self.update_paths_watched_for_rename(&server);
}
@@ -804,111 +983,101 @@ impl LspStore {
)?;
}
"textDocument/rangeFormatting" => {
- self.unregister_dynamic_capability(
+ self.unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.range_formatting,
|capabilities| &mut capabilities.document_range_formatting_provider,
)?;
}
"textDocument/onTypeFormatting" => {
- self.unregister_dynamic_capability(
+ self.unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.on_type_formatting,
|capabilities| &mut capabilities.document_on_type_formatting_provider,
)?;
}
"textDocument/formatting" => {
- self.unregister_dynamic_capability(
+ self.unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.formatting,
|capabilities| &mut capabilities.document_formatting_provider,
)?;
}
"textDocument/rename" => {
- self.unregister_dynamic_capability(
+ self.unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.rename,
|capabilities| &mut capabilities.rename_provider,
)?;
}
"textDocument/codeAction" => {
- self.unregister_dynamic_capability(
+ self.unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.code_action,
|capabilities| &mut capabilities.code_action_provider,
)?;
}
"textDocument/prepareCallHierarchy" => {
- self.unregister_dynamic_capability(
+ self.unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.call_hierarchy,
|capabilities| &mut capabilities.call_hierarchy_provider,
)?;
}
"textDocument/definition" => {
- self.unregister_dynamic_capability(
+ self.unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.definition,
|capabilities| &mut capabilities.definition_provider,
)?;
}
"textDocument/completion" => {
if self
- .unregister_dynamic_capability(
+ .unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.completion,
|capabilities| &mut capabilities.completion_provider,
)?
- .capability_changed()
+ .is_some()
{
- let restored = server.capabilities().completion_provider;
- self.apply_completion_triggers(server_id, restored, cx);
+ self.apply_completion_triggers(server_id, cx);
}
}
"textDocument/hover" => {
- self.unregister_dynamic_capability(
+ self.unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.hover,
|capabilities| &mut capabilities.hover_provider,
)?;
}
"textDocument/signatureHelp" => {
- self.unregister_dynamic_capability(
+ self.unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.signature_help,
|capabilities| &mut capabilities.signature_help_provider,
)?;
}
"textDocument/semanticTokens" => {
if self
- .unregister_dynamic_capability(
+ .unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.semantic_tokens,
|capabilities| &mut capabilities.semantic_tokens_provider,
)?
- .capability_changed()
+ .is_some_and(
+ CapabilityRegistrationChange::ordered_capability_may_have_changed,
+ )
{
self.refresh_semantic_tokens(server_id, cx);
}
@@ -920,7 +1089,7 @@ impl LspStore {
capabilities.text_document_sync =
Some(lsp::TextDocumentSyncCapability::Options(sync_options));
});
- notify_server_capabilities_updated(&server, cx);
+ self.notify_server_capabilities_updated(&server, cx);
}
"textDocument/didSave" => {
server.update_capabilities(|capabilities| {
@@ -929,60 +1098,56 @@ impl LspStore {
capabilities.text_document_sync =
Some(lsp::TextDocumentSyncCapability::Options(sync_options));
});
- notify_server_capabilities_updated(&server, cx);
+ self.notify_server_capabilities_updated(&server, cx);
}
"textDocument/inlayHint" => {
if self
- .unregister_dynamic_capability(
+ .unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.inlay_hint,
|capabilities| &mut capabilities.inlay_hint_provider,
)?
- .capability_changed()
+ .is_some_and(CapabilityRegistrationChange::applicability_may_have_changed)
{
self.refresh_inlay_hints(server_id, cx);
}
}
"textDocument/documentSymbol" => {
if self
- .unregister_dynamic_capability(
+ .unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.document_symbol,
|capabilities| &mut capabilities.document_symbol_provider,
)?
- .capability_changed()
+ .is_some_and(CapabilityRegistrationChange::applicability_may_have_changed)
{
self.refresh_document_symbols(Some(server_id), cx);
}
}
"textDocument/codeLens" => {
if self
- .unregister_dynamic_capability(
+ .unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.code_lens,
|capabilities| &mut capabilities.code_lens_provider,
)?
- .capability_changed()
+ .is_some_and(CapabilityRegistrationChange::applicability_may_have_changed)
{
self.refresh_code_lens(Some(server_id), cx);
}
}
"textDocument/diagnostic" => {
if self
- .unregister_dynamic_capability(
+ .unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.diagnostics,
|capabilities| &mut capabilities.diagnostic_provider,
)?
- .removed()
+ .is_some()
{
let local = self
.as_local_mut()
@@ -1008,42 +1173,39 @@ impl LspStore {
}
"textDocument/documentColor" => {
if self
- .unregister_dynamic_capability(
+ .unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.color,
|capabilities| &mut capabilities.color_provider,
)?
- .capability_changed()
+ .is_some_and(CapabilityRegistrationChange::applicability_may_have_changed)
{
self.refresh_document_colors(Some(server_id), cx);
}
}
"textDocument/foldingRange" => {
if self
- .unregister_dynamic_capability(
+ .unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.folding_range,
|capabilities| &mut capabilities.folding_range_provider,
)?
- .capability_changed()
+ .is_some_and(CapabilityRegistrationChange::applicability_may_have_changed)
{
self.refresh_folding_ranges(Some(server_id), cx);
}
}
"textDocument/documentLink" => {
if self
- .unregister_dynamic_capability(
+ .unregister_dynamic_text_document_capability(
&server,
unreg,
cx,
- |registrations| &mut registrations.document_link,
|capabilities| &mut capabilities.document_link_provider,
)?
- .capability_changed()
+ .is_some_and(CapabilityRegistrationChange::applicability_may_have_changed)
{
self.refresh_document_links(Some(server_id), cx);
}
@@ -1056,6 +1218,16 @@ impl LspStore {
}
}
+fn parse_text_document_registration(
+ register_options: Option<&serde_json::Value>,
+) -> Result<Option<lsp::DocumentSelector>> {
+ Ok(register_options
+ .cloned()
+ .map(serde_json::from_value::<lsp::TextDocumentRegistrationOptions>)
+ .transpose()?
+ .and_then(|options| options.document_selector))
+}
+
// Registration with registerOptions as null, should fallback to true.
// https://github.com/microsoft/vscode-languageserver-node/blob/d90a87f9557a0df9142cfb33e251cfa6fe27d970/client/src/common/client.ts#L2133
fn parse_register_capabilities<T: serde::de::DeserializeOwned>(
diff --git a/crates/project/src/lsp_store/folding_ranges.rs b/crates/project/src/lsp_store/folding_ranges.rs
index e1be0c3d57a..9df23518efe 100644
--- a/crates/project/src/lsp_store/folding_ranges.rs
+++ b/crates/project/src/lsp_store/folding_ranges.rs
@@ -107,7 +107,7 @@ impl LspStore {
let version_queried_for = buffer.read(cx).version();
let buffer_id = buffer.read(cx).remote_id();
- let current_servers = self.relevant_server_ids_for_capability_check(buffer, cx);
+ let current_servers = self.language_server_ids_for_request(buffer, &GetFoldingRanges, cx);
let mut servers_to_query = None;
if let Some(lsp_data) = self.current_lsp_data(buffer_id) {
diff --git a/crates/project/src/lsp_store/inlay_hints.rs b/crates/project/src/lsp_store/inlay_hints.rs
index 8a48992ee53..29800a21a5a 100644
--- a/crates/project/src/lsp_store/inlay_hints.rs
+++ b/crates/project/src/lsp_store/inlay_hints.rs
@@ -258,12 +258,18 @@ impl LspStore {
server_id: LanguageServerId,
cx: &mut Context<Self>,
) -> Task<anyhow::Result<InlayHint>> {
+ if !self.text_document_capability_matches_for_server(
+ &buffer,
+ server_id,
+ "textDocument/inlayHint",
+ |capabilities| InlayHints::can_resolve_inlays(capabilities.server_capabilities),
+ cx,
+ ) {
+ hint.resolve_state = ResolveState::Resolved;
+ return Task::ready(Ok(hint));
+ }
+
if let Some((upstream_client, project_id)) = self.upstream_client() {
- if !self.check_if_capable_for_proto_request(&buffer, InlayHints::can_resolve_inlays, cx)
- {
- hint.resolve_state = ResolveState::Resolved;
- return Task::ready(Ok(hint));
- }
let request = proto::ResolveInlayHint {
project_id,
buffer_id: buffer.read(cx).remote_id().into(),
@@ -288,9 +294,6 @@ impl LspStore {
}) else {
return Task::ready(Ok(hint));
};
- if !InlayHints::can_resolve_inlays(&lang_server.capabilities()) {
- return Task::ready(Ok(hint));
- }
let buffer_snapshot = buffer.read(cx).snapshot();
let request_timeout = ProjectSettings::get_global(cx)
.global_lsp_settings
diff --git a/crates/project/src/lsp_store/lsp_ext_command.rs b/crates/project/src/lsp_store/lsp_ext_command.rs
index 6e6fd59399b..11cd9dea510 100644
--- a/crates/project/src/lsp_store/lsp_ext_command.rs
+++ b/crates/project/src/lsp_store/lsp_ext_command.rs
@@ -69,7 +69,7 @@ impl LspCommand for ExpandMacro {
"Expand macro"
}
- fn check_capabilities(&self, _: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, _: AdapterServerCapabilities<'_>) -> bool {
true
}
@@ -208,7 +208,7 @@ impl LspCommand for OpenDocs {
"Open docs"
}
- fn check_capabilities(&self, _: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, _: AdapterServerCapabilities<'_>) -> bool {
true
}
@@ -350,7 +350,7 @@ impl LspCommand for SwitchSourceHeader {
"Switch source header"
}
- fn check_capabilities(&self, _: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, _: AdapterServerCapabilities<'_>) -> bool {
true
}
@@ -439,7 +439,7 @@ impl LspCommand for GoToParentModule {
"Go to parent module"
}
- fn check_capabilities(&self, _: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, _: AdapterServerCapabilities<'_>) -> bool {
true
}
@@ -703,7 +703,7 @@ impl LspCommand for GetLspRunnables {
"LSP Runnables"
}
- fn check_capabilities(&self, _: AdapterServerCapabilities) -> bool {
+ fn check_capabilities(&self, _: AdapterServerCapabilities<'_>) -> bool {
true
}
diff --git a/crates/project/src/lsp_store/semantic_tokens.rs b/crates/project/src/lsp_store/semantic_tokens.rs
index 675ab29f76d..06d3b65fd48 100644
--- a/crates/project/src/lsp_store/semantic_tokens.rs
+++ b/crates/project/src/lsp_store/semantic_tokens.rs
@@ -1,4 +1,4 @@
-use std::{collections::hash_map, ops::Range, slice::ChunksExact, sync::Arc};
+use std::{ops::Range, slice::ChunksExact, sync::Arc};
use anyhow::Result;
@@ -10,7 +10,7 @@ use futures::{
};
use gpui::{App, AppContext, AsyncApp, Context, Entity, ReadGlobal as _, SharedString, Task};
use language::{Buffer, LanguageName, language_settings::all_language_settings};
-use lsp::{AdapterServerCapabilities, LanguageServerId};
+use lsp::LanguageServerId;
use rpc::{TypedEnvelope, proto};
use settings::{
DefaultSemanticTokenRules, SemanticTokenRule, SemanticTokenRules, Settings as _, SettingsStore,
@@ -26,12 +26,17 @@ use crate::{
LspCommand, SemanticTokensDelta, SemanticTokensEdit, SemanticTokensFull,
SemanticTokensResponse,
},
- lsp_store::missing_servers_to_query,
+ lsp_store::{
+ LanguageServerState, document_selector_context_for_language, document_selector_matches,
+ missing_servers_to_query,
+ },
project_settings::ProjectSettings,
};
+type StylizerKey = (LanguageServerId, Option<LanguageName>);
+
pub(super) struct SemanticTokenConfig {
- stylizers: HashMap<(LanguageServerId, Option<LanguageName>), SemanticTokenStylizer>,
+ stylizers: HashMap<StylizerKey, (lsp::SemanticTokensLegend, SemanticTokenStylizer)>,
rules: SemanticTokenRules,
global_mode: settings::SemanticTokens,
}
@@ -88,27 +93,54 @@ impl LspStore {
cx: &mut Context<Self>,
) -> SemanticTokensTask {
let version_queried_for = buffer.read(cx).version();
- let current_servers = self.relevant_server_ids_for_capability_check(&buffer, cx);
+ let capability_probe = SemanticTokensFull { for_server: None };
+ let current_servers = self.language_server_ids_for_request(&buffer, &capability_probe, cx);
+ let empty_current_servers_are_authoritative = self.as_local().is_some();
let latest_lsp_data = self.latest_lsp_data(&buffer, cx);
let semantic_tokens_data = latest_lsp_data.semantic_tokens.get_or_insert_default();
- let mut refreshed_servers = std::mem::take(&mut semantic_tokens_data.pending_refreshes);
- refreshed_servers.retain(|server_id| current_servers.contains(server_id));
- if !refreshed_servers.is_empty() {
+ let pending_refreshes = std::mem::take(&mut semantic_tokens_data.pending_refreshes);
+ let current_servers_are_authoritative =
+ !current_servers.is_empty() || empty_current_servers_are_authoritative;
+ let server_set_shrank = current_servers_are_authoritative
+ && (semantic_tokens_data
+ .raw_tokens
+ .servers
+ .keys()
+ .any(|server_id| !current_servers.contains(server_id))
+ || semantic_tokens_data
+ .fetched_servers
+ .iter()
+ .any(|server_id| !current_servers.contains(server_id)));
+ let cache_invalidated = !pending_refreshes.is_empty() || server_set_shrank;
+ if cache_invalidated {
semantic_tokens_data.update = None;
semantic_tokens_data.generation += 1;
}
- for refreshed_server in &refreshed_servers {
+ for refreshed_server in &pending_refreshes {
semantic_tokens_data
.raw_tokens
.servers
.remove(refreshed_server);
+ semantic_tokens_data
+ .fetched_servers
+ .remove(refreshed_server);
}
- let missing_servers = missing_servers_to_query(
- &mut semantic_tokens_data.raw_tokens.servers,
- &mut semantic_tokens_data.fetched_servers,
- &current_servers,
- )
- .unwrap_or_default();
+ let refreshed_servers = pending_refreshes
+ .into_iter()
+ .filter(|server_id| current_servers.contains(server_id))
+ .collect::<HashSet<_>>();
+ let missing_servers = if current_servers.is_empty() && current_servers_are_authoritative {
+ semantic_tokens_data.raw_tokens.servers.clear();
+ semantic_tokens_data.fetched_servers.clear();
+ HashSet::default()
+ } else {
+ missing_servers_to_query(
+ &mut semantic_tokens_data.raw_tokens.servers,
+ &mut semantic_tokens_data.fetched_servers,
+ &current_servers,
+ )
+ .unwrap_or_default()
+ };
if !missing_servers.is_empty() {
semantic_tokens_data.update = None;
}
@@ -122,6 +154,7 @@ impl LspStore {
let mut servers_to_fetch = refreshed_servers;
servers_to_fetch.extend(missing_servers);
+ let rebuild_from_cache_only = cache_invalidated && servers_to_fetch.is_empty();
let for_server = if servers_to_fetch.len() == 1 {
servers_to_fetch.iter().next().copied()
} else {
@@ -130,13 +163,19 @@ impl LspStore {
// with cheap deltas.
None
};
- semantic_tokens_data
- .fetched_servers
- .extend(match for_server {
- Some(server_id) => HashSet::from_iter([server_id]),
- None => current_servers,
- });
- let new_tokens = self.fetch_semantic_tokens_for_buffer(&buffer, for_server, cx);
+ if !rebuild_from_cache_only {
+ semantic_tokens_data
+ .fetched_servers
+ .extend(match for_server {
+ Some(server_id) => HashSet::from_iter([server_id]),
+ None => current_servers,
+ });
+ }
+ let new_tokens = if rebuild_from_cache_only {
+ Task::ready(None)
+ } else {
+ self.fetch_semantic_tokens_for_buffer(&buffer, for_server, cx)
+ };
let task_buffer = buffer.clone();
let task_version_queried_for = version_queried_for.clone();
@@ -199,7 +238,13 @@ impl LspStore {
&& let Some(semantic_tokens) = current_lsp_data.semantic_tokens.as_mut()
&& semantic_tokens.generation == query_generation
{
- if for_server.is_none() || semantic_tokens.raw_tokens.servers.is_empty()
+ if rebuild_from_cache_only {
+ let buffer_snapshot =
+ buffer.read_with(cx, |buffer, _| buffer.snapshot());
+ remaining_tokens =
+ Some((semantic_tokens.raw_tokens.clone(), buffer_snapshot));
+ } else if for_server.is_none()
+ || semantic_tokens.raw_tokens.servers.is_empty()
{
semantic_tokens.evict_all();
} else {
@@ -296,61 +341,50 @@ impl LspStore {
Some(tokens)
})
} else {
+ let full_request = SemanticTokensFull { for_server: None };
let token_tasks = self
- .local_lsp_servers_for_buffer(&buffer, cx)
+ .language_server_ids_for_request(buffer, &full_request, cx)
.into_iter()
.filter(|&server_id| {
for_server.is_none_or(|for_server_id| for_server_id == server_id)
})
- .filter_map(|server_id| {
- let capabilities = AdapterServerCapabilities {
- server_capabilities: self.lsp_server_capabilities.get(&server_id)?.clone(),
- code_action_kinds: None,
- };
+ .map(|server_id| {
let request_task = match self.semantic_tokens_result_id(server_id, buffer, cx) {
Some(result_id) => {
let delta_request = SemanticTokensDelta {
previous_result_id: result_id,
};
- if !delta_request.check_capabilities(capabilities.clone()) {
- let full_request = SemanticTokensFull {
- for_server: Some(server_id),
- };
- if !full_request.check_capabilities(capabilities) {
- return None;
- }
-
+ if self
+ .language_server_ids_for_request(buffer, &delta_request, cx)
+ .contains(&server_id)
+ {
self.request_lsp(
buffer.clone(),
LanguageServerToQuery::Other(server_id),
- full_request,
+ delta_request,
cx,
)
} else {
self.request_lsp(
buffer.clone(),
LanguageServerToQuery::Other(server_id),
- delta_request,
+ SemanticTokensFull {
+ for_server: Some(server_id),
+ },
cx,
)
}
}
- None => {
- let request = SemanticTokensFull {
+ None => self.request_lsp(
+ buffer.clone(),
+ LanguageServerToQuery::Other(server_id),
+ SemanticTokensFull {
for_server: Some(server_id),
- };
- if !request.check_capabilities(capabilities) {
- return None;
- }
- self.request_lsp(
- buffer.clone(),
- LanguageServerToQuery::Other(server_id),
- request,
- cx,
- )
- }
+ },
+ cx,
+ ),
};
- Some(async move { (server_id, request_task.await) })
+ async move { (server_id, request_task.await) }
})
.collect::<Vec<_>>();
if token_tasks.is_empty() {
@@ -478,34 +512,119 @@ impl LspStore {
language: Option<&LanguageName>,
cx: &mut App,
) -> Option<&SemanticTokenStylizer> {
- let stylizer = match self
+ let key = (server_id, language.cloned());
+ let legend = self.semantic_tokens_legend(server_id, language)?;
+ let up_to_date = self
.semantic_token_config
.stylizers
- .entry((server_id, language.cloned()))
+ .get(&key)
+ .is_some_and(|(cached_legend, _)| cached_legend == legend);
+ if !up_to_date {
+ let legend = legend.clone();
+ let language_rules = language.and_then(|language| {
+ SettingsStore::global(cx).language_semantic_token_rules(language.as_ref())
+ });
+ let stylizer = SemanticTokenStylizer::new(server_id, &legend, language_rules, cx);
+ self.semantic_token_config
+ .stylizers
+ .insert(key.clone(), (legend, stylizer));
+ }
+ self.semantic_token_config
+ .stylizers
+ .get(&key)
+ .map(|(_, stylizer)| stylizer)
+ }
+
+ fn semantic_tokens_legend(
+ &self,
+ server_id: LanguageServerId,
+ language: Option<&LanguageName>,
+ ) -> Option<&lsp::SemanticTokensLegend> {
+ if let Some(local) = self.as_local()
+ && let Some(language) = language
+ && let Some(LanguageServerState::Running { adapter, .. }) =
+ local.language_servers.get(&server_id)
{
- hash_map::Entry::Occupied(o) => o.into_mut(),
- hash_map::Entry::Vacant(v) => {
- let tokens_provider = self
- .lsp_server_capabilities
- .get(&server_id)?
- .semantic_tokens_provider
- .as_ref()?;
- let legend = match tokens_provider {
- lsp::SemanticTokensServerCapabilities::SemanticTokensOptions(opts) => {
- &opts.legend
+ let context = document_selector_context_for_language(language, adapter);
+ if let Some(registrations) = local
+ .language_server_dynamic_registrations
+ .get(&server_id)
+ .and_then(|registrations| {
+ registrations
+ .text_documents
+ .get("textDocument/semanticTokens")
+ })
+ {
+ for registration in registrations.values().rev() {
+ if document_selector_matches(registration.document_selector.as_ref(), &context)
+ && let Some(provider) = registration
+ .server_capabilities
+ .semantic_tokens_provider
+ .as_ref()
+ {
+ return Some(semantic_tokens_provider_legend(provider));
}
- lsp::SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(
- opts,
- ) => &opts.semantic_tokens_options.legend,
- };
- let language_rules = language.and_then(|language| {
- SettingsStore::global(cx).language_semantic_token_rules(language.as_ref())
- });
- let stylizer = SemanticTokenStylizer::new(server_id, legend, language_rules, cx);
- v.insert(stylizer)
+ }
}
- };
- Some(stylizer)
+ if let Some(provider) = local
+ .initial_server_capabilities
+ .get(&server_id)
+ .and_then(|capabilities| capabilities.semantic_tokens_provider.as_ref())
+ {
+ return Some(semantic_tokens_provider_legend(provider));
+ }
+ }
+
+ if let Some(initial_capabilities) = self.lsp_server_initial_capabilities.get(&server_id) {
+ let context = self.remote_document_selector_context(server_id, language);
+ if let Some(registrations) = self
+ .lsp_server_text_document_registrations
+ .get(&server_id)
+ .and_then(|registrations| registrations.get("textDocument/semanticTokens"))
+ {
+ // Token indices are only meaningful with the provider's legend, so do not
+ // guess when the guest cannot reconstruct the host's selector context.
+ for registration in registrations.values().rev() {
+ let matches = match context.as_ref() {
+ Some(context) => document_selector_matches(
+ registration.document_selector.as_ref(),
+ context,
+ ),
+ None if registration.document_selector.is_none() => true,
+ None => return None,
+ };
+ if matches
+ && let Some(provider) = registration
+ .server_capabilities
+ .semantic_tokens_provider
+ .as_ref()
+ {
+ return Some(semantic_tokens_provider_legend(provider));
+ }
+ }
+ }
+
+ let provider = initial_capabilities.semantic_tokens_provider.as_ref()?;
+ return Some(semantic_tokens_provider_legend(provider));
+ }
+
+ let tokens_provider = self
+ .lsp_server_capabilities
+ .get(&server_id)?
+ .semantic_tokens_provider
+ .as_ref()?;
+ Some(semantic_tokens_provider_legend(tokens_provider))
+ }
+}
+
+fn semantic_tokens_provider_legend(
+ provider: &lsp::SemanticTokensServerCapabilities,
+) -> &lsp::SemanticTokensLegend {
+ match provider {
+ lsp::SemanticTokensServerCapabilities::SemanticTokensOptions(options) => &options.legend,
+ lsp::SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(options) => {
+ &options.semantic_tokens_options.legend
+ }
}
}
diff --git a/crates/project/src/project.rs b/crates/project/src/project.rs
index 7e94d87c76a..3e8c279366e 100644
--- a/crates/project/src/project.rs
+++ b/crates/project/src/project.rs
@@ -486,7 +486,10 @@ impl ProjectPath {
#[derive(Debug, Default)]
pub enum PrepareRenameResponse {
- Success(Range<Anchor>),
+ Success {
+ range: Range<Anchor>,
+ language_server_id: Option<LanguageServerId>,
+ },
OnlyUnpreparedRenameSupported,
#[default]
InvalidPosition,
@@ -3782,14 +3785,11 @@ impl Project {
match message {
proto::update_language_server::Variant::MetadataUpdated(update) => {
self.lsp_store.update(cx, |lsp_store, _| {
- if let Some(capabilities) = update
- .capabilities
- .as_ref()
- .and_then(|capabilities| serde_json::from_str(capabilities).ok())
- {
- lsp_store
- .lsp_server_capabilities
- .insert(*language_server_id, capabilities);
+ if let Some(capabilities) = update.capabilities.as_ref() {
+ lsp_store.insert_synced_server_capabilities(
+ *language_server_id,
+ capabilities,
+ );
}
if let Some(language_server_status) = lsp_store
@@ -4695,20 +4695,32 @@ impl Project {
buffer: Entity<Buffer>,
position: T,
new_name: String,
+ language_server_id: Option<LanguageServerId>,
cx: &mut Context<Self>,
) -> Task<Result<ProjectTransaction>> {
let push_to_history = true;
let position = position.to_point_utf16(buffer.read(cx));
- self.request_lsp(
- buffer,
- LanguageServerToQuery::FirstCapable,
- PerformRename {
- position,
- new_name,
- push_to_history,
- },
- cx,
- )
+ let mut request = PerformRename {
+ position,
+ new_name,
+ push_to_history,
+ language_server_id,
+ };
+ if let Some(server_id) = request.language_server_id {
+ let server_is_capable = !self.is_local()
+ || self.lsp_store.update(cx, |lsp_store, cx| {
+ lsp_store
+ .language_server_capable_of_lsp_request(&buffer, server_id, &request, cx)
+ });
+ if !server_is_capable {
+ request.language_server_id = None;
+ }
+ }
+ let server_to_query = request
+ .language_server_id
+ .map(LanguageServerToQuery::Other)
+ .unwrap_or(LanguageServerToQuery::FirstCapable);
+ self.request_lsp(buffer, server_to_query, request, cx)
}
pub fn on_type_format<T: ToPointUtf16>(
diff --git a/crates/project/tests/integration/dynamic_registration.rs b/crates/project/tests/integration/dynamic_registration.rs
index 9600b2cc4cf..1c434780b86 100644
--- a/crates/project/tests/integration/dynamic_registration.rs
+++ b/crates/project/tests/integration/dynamic_registration.rs
@@ -4,6 +4,7 @@
use std::collections::BTreeMap;
use pretty_assertions::assert_eq;
+use project::lsp_store::TokenType;
use super::*;
@@ -132,6 +133,525 @@ async fn test_dynamic_semantic_tokens_registration(cx: &mut gpui::TestAppContext
);
}
+#[gpui::test]
+async fn test_local_semantic_tokens_request_uses_matching_dynamic_registration(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx);
+ let (project, fake_server) =
+ setup_dynamic_registration_test(cx, lsp::ServerCapabilities::default()).await;
+ let server_id = fake_server.server.server_id();
+ let method = "textDocument/semanticTokens";
+
+ let (buffer, _lsp_handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/the-root/a.rs"), cx)
+ })
+ .await
+ .unwrap();
+
+ let matching_options = lsp::SemanticTokensRegistrationOptions {
+ text_document_registration_options: lsp::TextDocumentRegistrationOptions {
+ document_selector: Some(vec![lsp::DocumentFilter {
+ language: Some("rust".to_string()),
+ scheme: Some("file".to_string()),
+ pattern: None,
+ }]),
+ },
+ semantic_tokens_options: lsp::SemanticTokensOptions {
+ legend: lsp::SemanticTokensLegend {
+ token_types: vec!["keyword".into()],
+ token_modifiers: Vec::new(),
+ },
+ full: Some(lsp::SemanticTokensFullOptions::Delta { delta: Some(true) }),
+ ..lsp::SemanticTokensOptions::default()
+ },
+ static_registration_options: lsp::StaticRegistrationOptions::default(),
+ };
+ let nonmatching_options = lsp::SemanticTokensRegistrationOptions {
+ text_document_registration_options: lsp::TextDocumentRegistrationOptions {
+ document_selector: Some(vec![lsp::DocumentFilter {
+ language: Some("rust".to_string()),
+ scheme: Some("untitled".to_string()),
+ pattern: None,
+ }]),
+ },
+ semantic_tokens_options: lsp::SemanticTokensOptions {
+ legend: lsp::SemanticTokensLegend {
+ token_types: vec!["comment".into()],
+ token_modifiers: Vec::new(),
+ },
+ full: Some(lsp::SemanticTokensFullOptions::Bool(false)),
+ ..lsp::SemanticTokensOptions::default()
+ },
+ static_registration_options: lsp::StaticRegistrationOptions::default(),
+ };
+
+ register_capability(
+ &fake_server,
+ method,
+ "file-semantic-tokens",
+ serde_json::to_value(matching_options).ok(),
+ )
+ .await;
+ register_capability(
+ &fake_server,
+ method,
+ "untitled-semantic-tokens",
+ serde_json::to_value(nonmatching_options).ok(),
+ )
+ .await;
+ cx.executor().run_until_parked();
+
+ let aggregate_options = match server_capabilities(&project, server_id, cx)
+ .semantic_tokens_provider
+ .expect("expected the later registration to become the aggregate capability")
+ {
+ lsp::SemanticTokensServerCapabilities::SemanticTokensOptions(options) => options,
+ lsp::SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(options) => {
+ options.semantic_tokens_options
+ }
+ };
+ assert_eq!(
+ aggregate_options.full,
+ Some(lsp::SemanticTokensFullOptions::Bool(false)),
+ "expected the nonmatching registration to make the aggregate capability reject full requests",
+ );
+
+ let semantic_token_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ fake_server.set_request_handler::<lsp::request::SemanticTokensFullRequest, _, _>({
+ let semantic_token_request_count = semantic_token_request_count.clone();
+ move |params, _| {
+ semantic_token_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ assert_eq!(
+ params.text_document.uri,
+ lsp::Uri::from_file_path(path!("/the-root/a.rs")).unwrap()
+ );
+ async move {
+ Ok(Some(lsp::SemanticTokensResult::Tokens(
+ lsp::SemanticTokens::default(),
+ )))
+ }
+ }
+ });
+
+ let lsp_store = project.read_with(cx, |project, _| project.lsp_store());
+ lsp_store
+ .update(cx, |lsp_store, cx| {
+ lsp_store.semantic_tokens(buffer.clone(), cx)
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(
+ semantic_token_request_count.load(atomic::Ordering::SeqCst),
+ 1,
+ "expected the matching registration to route a full semantic tokens request",
+ );
+
+ let stylizer_token_type = |cx: &mut gpui::TestAppContext| {
+ lsp_store.update(cx, |lsp_store, cx| {
+ let language = buffer.read(cx).language().map(|language| language.name());
+ lsp_store
+ .get_or_create_token_stylizer(server_id, language.as_ref(), cx)
+ .and_then(|stylizer| stylizer.token_type_name(TokenType(0)).cloned())
+ })
+ };
+ assert_eq!(
+ stylizer_token_type(cx).as_deref(),
+ Some("keyword"),
+ "expected the stylizer to use the matching registration's legend instead of the aggregate one",
+ );
+
+ let updated_matching_options = lsp::SemanticTokensRegistrationOptions {
+ text_document_registration_options: lsp::TextDocumentRegistrationOptions {
+ document_selector: Some(vec![lsp::DocumentFilter {
+ language: Some("rust".to_string()),
+ scheme: Some("file".to_string()),
+ pattern: None,
+ }]),
+ },
+ semantic_tokens_options: lsp::SemanticTokensOptions {
+ legend: lsp::SemanticTokensLegend {
+ token_types: vec!["function".into()],
+ token_modifiers: Vec::new(),
+ },
+ full: Some(lsp::SemanticTokensFullOptions::Delta { delta: Some(true) }),
+ ..lsp::SemanticTokensOptions::default()
+ },
+ static_registration_options: lsp::StaticRegistrationOptions::default(),
+ };
+ register_capability(
+ &fake_server,
+ method,
+ "file-semantic-tokens-2",
+ serde_json::to_value(updated_matching_options).ok(),
+ )
+ .await;
+ cx.executor().run_until_parked();
+
+ assert_eq!(
+ stylizer_token_type(cx).as_deref(),
+ Some("function"),
+ "expected the cached stylizer to be rebuilt for the newest matching registration's legend",
+ );
+}
+
+#[gpui::test]
+async fn test_semantic_tokens_refresh_when_duplicate_removal_changes_provider_order(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx);
+ let (project, fake_server) =
+ setup_dynamic_registration_test(cx, lsp::ServerCapabilities::default()).await;
+ let server_id = fake_server.server.server_id();
+ let method = "textDocument/semanticTokens";
+
+ let (buffer, _lsp_handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/the-root/a.rs"), cx)
+ })
+ .await
+ .unwrap();
+ let registration_options = |scheme: &str, token_type: &str| {
+ serde_json::to_value(lsp::SemanticTokensRegistrationOptions {
+ text_document_registration_options: lsp::TextDocumentRegistrationOptions {
+ document_selector: Some(vec![lsp::DocumentFilter {
+ language: Some("rust".to_string()),
+ scheme: Some(scheme.to_string()),
+ pattern: None,
+ }]),
+ },
+ semantic_tokens_options: lsp::SemanticTokensOptions {
+ legend: lsp::SemanticTokensLegend {
+ token_types: vec![token_type.to_owned().into()],
+ token_modifiers: Vec::new(),
+ },
+ full: Some(lsp::SemanticTokensFullOptions::Bool(true)),
+ ..lsp::SemanticTokensOptions::default()
+ },
+ static_registration_options: lsp::StaticRegistrationOptions::default(),
+ })
+ .ok()
+ };
+
+ let (refresh_events, _refresh_events_subscription) = observe_refresh_events(&project, cx);
+ register_capability(
+ &fake_server,
+ method,
+ "file-keyword-a",
+ registration_options("file", "keyword"),
+ )
+ .await;
+ register_capability(
+ &fake_server,
+ method,
+ "file-function",
+ registration_options("file", "function"),
+ )
+ .await;
+ register_capability(
+ &fake_server,
+ method,
+ "file-keyword-b",
+ registration_options("file", "keyword"),
+ )
+ .await;
+ register_capability(
+ &fake_server,
+ method,
+ "untitled-comment",
+ registration_options("untitled", "comment"),
+ )
+ .await;
+ cx.executor().run_until_parked();
+ refresh_events.lock().clear();
+
+ let lsp_store = project.read_with(cx, |project, _| project.lsp_store());
+ let stylizer_token_type = |cx: &mut gpui::TestAppContext| {
+ lsp_store.update(cx, |lsp_store, cx| {
+ let language = buffer.read(cx).language().map(|language| language.name());
+ lsp_store
+ .get_or_create_token_stylizer(server_id, language.as_ref(), cx)
+ .and_then(|stylizer| stylizer.token_type_name(TokenType(0)).cloned())
+ })
+ };
+ assert_eq!(
+ stylizer_token_type(cx).as_deref(),
+ Some("keyword"),
+ "expected the newest matching duplicate to provide the initial legend",
+ );
+
+ unregister_capabilities(&fake_server, method, &["file-keyword-b"]).await;
+ cx.executor().run_until_parked();
+
+ assert_eq!(
+ refresh_events.lock().as_slice(),
+ &[format!("semantic_tokens({server_id})")],
+ "expected removing an ordered duplicate to invalidate semantic tokens",
+ );
+ assert_eq!(
+ stylizer_token_type(cx).as_deref(),
+ Some("function"),
+ "expected the next matching registration to provide the updated legend",
+ );
+}
+
+#[gpui::test]
+async fn test_completion_resolve_uses_matching_dynamic_registration(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+ let (project, fake_server) =
+ setup_dynamic_registration_test(cx, lsp::ServerCapabilities::default()).await;
+ let method = "textDocument/completion";
+ let (buffer, _lsp_handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/the-root/a.rs"), cx)
+ })
+ .await
+ .unwrap();
+
+ register_capability(
+ &fake_server,
+ method,
+ "file-completion",
+ Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "file" }],
+ "resolveProvider": true,
+ })),
+ )
+ .await;
+ register_capability(
+ &fake_server,
+ method,
+ "untitled-completion",
+ Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "untitled" }],
+ "resolveProvider": false,
+ })),
+ )
+ .await;
+ cx.executor().run_until_parked();
+
+ fake_server.set_request_handler::<lsp::request::Completion, _, _>(|_, _| async move {
+ Ok(Some(lsp::CompletionResponse::Array(vec![
+ lsp::CompletionItem {
+ label: "completion".to_string(),
+ data: Some(json!({ "resolve": true })),
+ ..lsp::CompletionItem::default()
+ },
+ ])))
+ });
+ let resolve_requests = Arc::new(atomic::AtomicUsize::new(0));
+ fake_server.set_request_handler::<lsp::request::ResolveCompletionItem, _, _>({
+ let resolve_requests = resolve_requests.clone();
+ move |mut item, _| {
+ resolve_requests.fetch_add(1, atomic::Ordering::SeqCst);
+ async move {
+ item.detail = Some("resolved".to_string());
+ Ok(item)
+ }
+ }
+ });
+
+ let lsp_store = project.read_with(cx, |project, _| project.lsp_store());
+ let responses = lsp_store
+ .update(cx, |lsp_store, cx| {
+ lsp_store.completions(
+ &buffer,
+ PointUtf16::new(0, 0),
+ lsp::CompletionContext {
+ trigger_kind: lsp::CompletionTriggerKind::INVOKED,
+ trigger_character: None,
+ },
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+ let completions = responses
+ .into_iter()
+ .flat_map(|response| response.completions)
+ .collect::<Vec<_>>();
+ assert_eq!(completions.len(), 1);
+ let completions = Rc::new(RefCell::new(completions.into_boxed_slice()));
+
+ lsp_store
+ .update(cx, |lsp_store, cx| {
+ lsp_store.resolve_completions(buffer.clone(), vec![0], completions, cx)
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(
+ resolve_requests.load(atomic::Ordering::SeqCst),
+ 1,
+ "expected the matching file registration to enable completion resolve",
+ );
+}
+
+#[gpui::test]
+async fn test_code_lens_resolve_uses_matching_dynamic_registration(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+ let (project, fake_server) =
+ setup_dynamic_registration_test(cx, lsp::ServerCapabilities::default()).await;
+ let method = "textDocument/codeLens";
+ let (buffer, _lsp_handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/the-root/a.rs"), cx)
+ })
+ .await
+ .unwrap();
+
+ register_capability(
+ &fake_server,
+ method,
+ "file-code-lens",
+ Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "file" }],
+ "resolveProvider": true,
+ })),
+ )
+ .await;
+ register_capability(
+ &fake_server,
+ method,
+ "untitled-code-lens",
+ Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "untitled" }],
+ "resolveProvider": false,
+ })),
+ )
+ .await;
+ cx.executor().run_until_parked();
+
+ fake_server.set_request_handler::<lsp::request::CodeLensRequest, _, _>(|_, _| async move {
+ Ok(Some(vec![lsp::CodeLens {
+ range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 1)),
+ command: None,
+ data: Some(json!({ "resolve": true })),
+ }]))
+ });
+ let resolve_requests = Arc::new(atomic::AtomicUsize::new(0));
+ fake_server.set_request_handler::<lsp::request::CodeLensResolve, _, _>({
+ let resolve_requests = resolve_requests.clone();
+ move |mut lens, _| {
+ resolve_requests.fetch_add(1, atomic::Ordering::SeqCst);
+ async move {
+ lens.command = Some(lsp::Command {
+ title: "resolved".to_string(),
+ command: "test.resolve".to_string(),
+ arguments: None,
+ });
+ Ok(lens)
+ }
+ }
+ });
+
+ let lsp_store = project.read_with(cx, |project, _| project.lsp_store());
+ let actions = lsp_store
+ .update(cx, |lsp_store, cx| lsp_store.code_lens_actions(&buffer, cx))
+ .await
+ .unwrap()
+ .expect("expected code lens actions");
+ let (lens_id, action) = actions.into_iter().next().expect("expected one code lens");
+ let resolved = lsp_store
+ .update(cx, |lsp_store, cx| {
+ lsp_store.resolve_code_lens(&buffer, action.server_id, lens_id, cx)
+ })
+ .await
+ .expect("expected the code lens to resolve")
+ .1;
+
+ assert_eq!(
+ resolve_requests.load(atomic::Ordering::SeqCst),
+ 1,
+ "expected the matching file registration to enable code lens resolve",
+ );
+ assert_eq!(resolved.lsp_action.title(), "resolved");
+}
+
+#[gpui::test]
+async fn test_inlay_hint_resolve_state_uses_matching_dynamic_registration(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx);
+ let (project, fake_server) =
+ setup_dynamic_registration_test(cx, lsp::ServerCapabilities::default()).await;
+ let server_id = fake_server.server.server_id();
+ let method = "textDocument/inlayHint";
+ let (buffer, _lsp_handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/the-root/a.rs"), cx)
+ })
+ .await
+ .unwrap();
+ buffer.update(cx, |buffer, cx| {
+ buffer.edit([(0..0, "fn main() {}")], None, cx);
+ });
+ cx.executor().run_until_parked();
+
+ register_capability(
+ &fake_server,
+ method,
+ "file-inlay-hints",
+ Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "file" }],
+ "resolveProvider": true,
+ })),
+ )
+ .await;
+ register_capability(
+ &fake_server,
+ method,
+ "untitled-inlay-hints",
+ Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "untitled" }],
+ "resolveProvider": false,
+ })),
+ )
+ .await;
+ cx.executor().run_until_parked();
+
+ fake_server.set_request_handler::<lsp::request::InlayHintRequest, _, _>(|_, _| async move {
+ Ok(Some(vec![lsp::InlayHint {
+ position: lsp::Position::new(0, 0),
+ label: lsp::InlayHintLabel::String("hint".to_string()),
+ kind: None,
+ text_edits: None,
+ tooltip: None,
+ padding_left: None,
+ padding_right: None,
+ data: Some(json!({ "resolve": true })),
+ }]))
+ });
+
+ let lsp_store = project.read_with(cx, |project, _| project.lsp_store());
+ let hint_tasks = lsp_store.update(cx, |lsp_store, cx| {
+ let range =
+ buffer.read(cx).anchor_before(0)..buffer.read(cx).anchor_after(buffer.read(cx).len());
+ lsp_store.inlay_hints(
+ InvalidationStrategy::None,
+ buffer.clone(),
+ vec![range],
+ None,
+ cx,
+ )
+ });
+ let mut hints = Vec::new();
+ for (_, hint_task) in hint_tasks {
+ for (_, server_hints) in hint_task.await.unwrap() {
+ hints.extend(server_hints.into_iter().map(|(_, hint)| hint));
+ }
+ }
+
+ assert_eq!(hints.len(), 1);
+ assert_matches!(
+ &hints[0].resolve_state,
+ ResolveState::CanResolve(id, _) if *id == server_id,
+ "expected the matching file registration to mark the hint as resolvable",
+ );
+}
+
#[gpui::test]
async fn test_multi_registration_inlay_hint(cx: &mut gpui::TestAppContext) {
init_test(cx);
@@ -336,183 +856,439 @@ async fn test_multi_registration_restores_static_capability(cx: &mut gpui::TestA
"expected the statically declared inlay hint provider before any dynamic registration",
);
- let dynamic_options = lsp::InlayHintOptions {
- resolve_provider: Some(true),
- ..lsp::InlayHintOptions::default()
+ let dynamic_options = lsp::InlayHintOptions {
+ resolve_provider: Some(true),
+ ..lsp::InlayHintOptions::default()
+ };
+ register_capability(
+ &fake_server,
+ method,
+ "inlay-hint-dynamic",
+ serde_json::to_value(&dynamic_options).ok(),
+ )
+ .await;
+ cx.executor().run_until_parked();
+ assert_eq!(
+ server_capabilities(&project, server_id, cx).inlay_hint_provider,
+ Some(lsp::OneOf::Right(
+ lsp::InlayHintServerCapabilities::Options(dynamic_options)
+ )),
+ "expected the dynamic registration's options to override the static capability",
+ );
+
+ unregister_capabilities(&fake_server, method, &["unknown-id", "inlay-hint-dynamic"]).await;
+ cx.executor().run_until_parked();
+ assert_eq!(
+ server_capabilities(&project, server_id, cx).inlay_hint_provider,
+ Some(lsp::OneOf::Left(true)),
+ "expected the static capability to be restored after unregistering the last dynamic registration, despite an unknown ID earlier in the batch",
+ );
+}
+
+#[gpui::test]
+async fn test_multi_registration_duplicate_id_keeps_order(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+ let (project, fake_server) =
+ setup_dynamic_registration_test(cx, lsp::ServerCapabilities::default()).await;
+ let server_id = fake_server.server.server_id();
+ let method = "textDocument/inlayHint";
+
+ let options_a = lsp::InlayHintOptions {
+ resolve_provider: Some(true),
+ ..lsp::InlayHintOptions::default()
+ };
+ let options_b = lsp::InlayHintOptions {
+ resolve_provider: Some(false),
+ ..lsp::InlayHintOptions::default()
+ };
+ let options_a_replacement = lsp::InlayHintOptions::default();
+
+ let (refresh_events, _refresh_events_subscription) = observe_refresh_events(&project, cx);
+ register_capability(
+ &fake_server,
+ method,
+ "inlay-hint-a",
+ serde_json::to_value(&options_a).ok(),
+ )
+ .await;
+ register_capability(
+ &fake_server,
+ method,
+ "inlay-hint-b",
+ serde_json::to_value(&options_b).ok(),
+ )
+ .await;
+ cx.executor().run_until_parked();
+ assert_eq!(
+ refresh_events.lock().drain(..).collect::<Vec<_>>(),
+ vec![
+ format!("inlay_hints({server_id})"),
+ format!("inlay_hints({server_id})"),
+ ],
+ "expected both registrations to trigger a refresh",
+ );
+
+ register_capability(
+ &fake_server,
+ method,
+ "inlay-hint-a",
+ serde_json::to_value(&options_a_replacement).ok(),
+ )
+ .await;
+ cx.executor().run_until_parked();
+ assert_eq!(
+ server_capabilities(&project, server_id, cx).inlay_hint_provider,
+ Some(lsp::OneOf::Right(
+ lsp::InlayHintServerCapabilities::Options(options_b)
+ )),
+ "expected the latest distinct registration to stay active after a duplicate ID replaced an older one",
+ );
+ assert_eq!(
+ refresh_events.lock().drain(..).collect::<Vec<_>>(),
+ vec![format!("inlay_hints({server_id})")],
+ "expected replacing an inactive registration to refresh selector-aware caches",
+ );
+
+ unregister_capabilities(&fake_server, method, &["inlay-hint-b"]).await;
+ cx.executor().run_until_parked();
+ assert_eq!(
+ server_capabilities(&project, server_id, cx).inlay_hint_provider,
+ Some(lsp::OneOf::Right(
+ lsp::InlayHintServerCapabilities::Options(options_a_replacement)
+ )),
+ "expected the replaced registration's options to be restored",
+ );
+
+ unregister_capabilities(&fake_server, method, &["inlay-hint-a"]).await;
+ cx.executor().run_until_parked();
+ assert_eq!(
+ server_capabilities(&project, server_id, cx).inlay_hint_provider,
+ None,
+ "expected inlay hint provider to be cleared after unregistering the last registration",
+ );
+}
+
+#[gpui::test]
+async fn test_registration_with_unchanged_options_does_not_refresh(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+ let (project, fake_server) =
+ setup_dynamic_registration_test(cx, lsp::ServerCapabilities::default()).await;
+ let server_id = fake_server.server.server_id();
+ let method = "textDocument/codeLens";
+
+ let options = lsp::CodeLensOptions {
+ resolve_provider: Some(true),
+ };
+
+ let (refresh_events, _refresh_events_subscription) = observe_refresh_events(&project, cx);
+ register_capability(
+ &fake_server,
+ method,
+ "lens-a",
+ serde_json::to_value(options).ok(),
+ )
+ .await;
+ cx.executor().run_until_parked();
+ assert_eq!(
+ refresh_events.lock().drain(..).collect::<Vec<_>>(),
+ vec![format!("code_lens({server_id})")],
+ "expected the first registration to refresh",
+ );
+
+ register_capability(
+ &fake_server,
+ method,
+ "lens-a",
+ serde_json::to_value(options).ok(),
+ )
+ .await;
+ cx.executor().run_until_parked();
+ assert_eq!(
+ refresh_events.lock().as_slice(),
+ &[] as &[String],
+ "expected a registration with options identical to the active ones to not refresh",
+ );
+
+ unregister_capabilities(&fake_server, method, &["lens-a"]).await;
+ cx.executor().run_until_parked();
+ assert_eq!(
+ refresh_events.lock().drain(..).collect::<Vec<_>>(),
+ vec![format!("code_lens({server_id})")],
+ "expected the last unregistration to clear the capability and refresh",
+ );
+ assert_eq!(
+ server_capabilities(&project, server_id, cx).code_lens_provider,
+ None,
+ "expected the code lens provider to be cleared after unregistering the last registration",
+ );
+}
+
+#[gpui::test]
+async fn test_selector_only_registration_change_refreshes_cached_lsp_data(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx);
+ let (project, fake_server) =
+ setup_dynamic_registration_test(cx, lsp::ServerCapabilities::default()).await;
+ let server_id = fake_server.server.server_id();
+ let method = "textDocument/codeLens";
+ let registration_options = |scheme: &str| {
+ json!({
+ "documentSelector": [{ "language": "rust", "scheme": scheme }],
+ "resolveProvider": true,
+ })
};
+
+ let (refresh_events, _refresh_events_subscription) = observe_refresh_events(&project, cx);
register_capability(
&fake_server,
method,
- "inlay-hint-dynamic",
- serde_json::to_value(&dynamic_options).ok(),
+ "lens",
+ Some(registration_options("file")),
)
.await;
cx.executor().run_until_parked();
assert_eq!(
- server_capabilities(&project, server_id, cx).inlay_hint_provider,
- Some(lsp::OneOf::Right(
- lsp::InlayHintServerCapabilities::Options(dynamic_options)
- )),
- "expected the dynamic registration's options to override the static capability",
+ refresh_events.lock().drain(..).collect::<Vec<_>>(),
+ vec![format!("code_lens({server_id})")],
);
- unregister_capabilities(&fake_server, method, &["unknown-id", "inlay-hint-dynamic"]).await;
+ register_capability(
+ &fake_server,
+ method,
+ "lens",
+ Some(registration_options("untitled")),
+ )
+ .await;
cx.executor().run_until_parked();
assert_eq!(
- server_capabilities(&project, server_id, cx).inlay_hint_provider,
- Some(lsp::OneOf::Left(true)),
- "expected the static capability to be restored after unregistering the last dynamic registration, despite an unknown ID earlier in the batch",
+ refresh_events.lock().drain(..).collect::<Vec<_>>(),
+ vec![format!("code_lens({server_id})")],
+ "expected changing only the document selector to invalidate cached LSP data",
);
}
#[gpui::test]
-async fn test_multi_registration_duplicate_id_keeps_order(cx: &mut gpui::TestAppContext) {
+async fn test_duplicate_content_registration_changes_do_not_refresh(cx: &mut gpui::TestAppContext) {
init_test(cx);
let (project, fake_server) =
setup_dynamic_registration_test(cx, lsp::ServerCapabilities::default()).await;
let server_id = fake_server.server.server_id();
- let method = "textDocument/inlayHint";
-
- let options_a = lsp::InlayHintOptions {
- resolve_provider: Some(true),
- ..lsp::InlayHintOptions::default()
+ let method = "textDocument/codeLens";
+ let registration_options = |scheme: &str| {
+ json!({
+ "documentSelector": [{ "language": "rust", "scheme": scheme }],
+ "resolveProvider": true,
+ })
};
- let options_b = lsp::InlayHintOptions {
- resolve_provider: Some(false),
- ..lsp::InlayHintOptions::default()
+ let expected_options = lsp::CodeLensOptions {
+ resolve_provider: Some(true),
};
- let options_a_replacement = lsp::InlayHintOptions::default();
let (refresh_events, _refresh_events_subscription) = observe_refresh_events(&project, cx);
register_capability(
&fake_server,
method,
- "inlay-hint-a",
- serde_json::to_value(&options_a).ok(),
+ "lens-a",
+ Some(registration_options("file")),
)
.await;
register_capability(
&fake_server,
method,
- "inlay-hint-b",
- serde_json::to_value(&options_b).ok(),
+ "lens-b",
+ Some(registration_options("untitled")),
)
.await;
cx.executor().run_until_parked();
assert_eq!(
refresh_events.lock().drain(..).collect::<Vec<_>>(),
vec![
- format!("inlay_hints({server_id})"),
- format!("inlay_hints({server_id})"),
+ format!("code_lens({server_id})"),
+ format!("code_lens({server_id})"),
],
- "expected both registrations to trigger a refresh",
+ "expected registrations with distinct selectors to refresh",
);
register_capability(
&fake_server,
method,
- "inlay-hint-a",
- serde_json::to_value(&options_a_replacement).ok(),
+ "lens-a",
+ Some(registration_options("untitled")),
)
.await;
cx.executor().run_until_parked();
assert_eq!(
- server_capabilities(&project, server_id, cx).inlay_hint_provider,
- Some(lsp::OneOf::Right(
- lsp::InlayHintServerCapabilities::Options(options_b)
- )),
- "expected the latest distinct registration to stay active after a duplicate ID replaced an older one",
+ server_capabilities(&project, server_id, cx).code_lens_provider,
+ Some(expected_options),
+ "expected the active code lens options to survive a duplicate ID replacement",
+ );
+ assert_eq!(
+ refresh_events.lock().drain(..).collect::<Vec<_>>(),
+ vec![format!("code_lens({server_id})")],
+ "expected a selector change of any registration to refresh",
+ );
+
+ unregister_capabilities(&fake_server, method, &["lens-b"]).await;
+ cx.executor().run_until_parked();
+ assert_eq!(
+ server_capabilities(&project, server_id, cx).code_lens_provider,
+ Some(expected_options),
+ "expected the duplicate-content registration to keep the capability active",
);
assert_eq!(
refresh_events.lock().as_slice(),
&[] as &[String],
- "expected no refresh after a duplicate ID replaced an inactive registration",
+ "expected removing a registration whose content a remaining one duplicates to not refresh",
);
- unregister_capabilities(&fake_server, method, &["inlay-hint-b"]).await;
+ register_capability(
+ &fake_server,
+ method,
+ "lens-c",
+ Some(registration_options("untitled")),
+ )
+ .await;
cx.executor().run_until_parked();
assert_eq!(
- server_capabilities(&project, server_id, cx).inlay_hint_provider,
- Some(lsp::OneOf::Right(
- lsp::InlayHintServerCapabilities::Options(options_a_replacement)
- )),
- "expected the replaced registration's options to be restored",
+ refresh_events.lock().as_slice(),
+ &[] as &[String],
+ "expected a new registration with content identical to an existing one to not refresh",
);
- unregister_capabilities(&fake_server, method, &["inlay-hint-a"]).await;
+ unregister_capabilities(&fake_server, method, &["lens-a"]).await;
cx.executor().run_until_parked();
assert_eq!(
- server_capabilities(&project, server_id, cx).inlay_hint_provider,
+ server_capabilities(&project, server_id, cx).code_lens_provider,
+ Some(expected_options),
+ "expected the capability to survive removing one of two identical registrations",
+ );
+ assert_eq!(
+ refresh_events.lock().as_slice(),
+ &[] as &[String],
+ "expected removing one of two identical registrations to not refresh",
+ );
+
+ unregister_capabilities(&fake_server, method, &["lens-c"]).await;
+ cx.executor().run_until_parked();
+ assert_eq!(
+ server_capabilities(&project, server_id, cx).code_lens_provider,
None,
- "expected inlay hint provider to be cleared after unregistering the last registration",
+ "expected the code lens provider to be cleared after unregistering the last registration",
+ );
+ assert_eq!(
+ refresh_events.lock().drain(..).collect::<Vec<_>>(),
+ vec![format!("code_lens({server_id})")],
+ "expected the last unregistration to clear the capability and refresh",
);
}
#[gpui::test]
-async fn test_registration_with_unchanged_options_does_not_refresh(cx: &mut gpui::TestAppContext) {
+async fn test_selector_aware_routing_with_duplicate_content_registrations(
+ cx: &mut gpui::TestAppContext,
+) {
init_test(cx);
let (project, fake_server) =
setup_dynamic_registration_test(cx, lsp::ServerCapabilities::default()).await;
let server_id = fake_server.server.server_id();
- let method = "textDocument/codeLens";
+ let method = "textDocument/completion";
- let options = lsp::CodeLensOptions {
- resolve_provider: Some(true),
+ let (buffer, _lsp_handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/the-root/a.rs"), cx)
+ })
+ .await
+ .unwrap();
+ let buffer_triggers = |cx: &mut gpui::TestAppContext| {
+ buffer.read_with(cx, |buffer, _| buffer.completion_triggers().clone())
+ };
+ let registration_options = |scheme: &str, trigger: &str| {
+ json!({
+ "documentSelector": [{ "language": "rust", "scheme": scheme }],
+ "triggerCharacters": [trigger],
+ })
+ };
+ let colon_options = lsp::CompletionOptions {
+ trigger_characters: Some(vec![":".to_string()]),
+ ..lsp::CompletionOptions::default()
};
- let (refresh_events, _refresh_events_subscription) = observe_refresh_events(&project, cx);
register_capability(
&fake_server,
method,
- "lens-a",
- serde_json::to_value(options).ok(),
+ "completion-a",
+ Some(registration_options("file", ".")),
)
.await;
cx.executor().run_until_parked();
assert_eq!(
- refresh_events.lock().drain(..).collect::<Vec<_>>(),
- vec![format!("code_lens({server_id})")],
- "expected the first registration to refresh",
+ buffer_triggers(cx),
+ BTreeSet::from([".".to_string()]),
+ "expected the matching registration's triggers to apply to the buffer",
);
register_capability(
&fake_server,
method,
- "lens-b",
- serde_json::to_value(options).ok(),
+ "completion-b",
+ Some(registration_options("untitled", ":")),
)
.await;
cx.executor().run_until_parked();
assert_eq!(
- refresh_events.lock().as_slice(),
- &[] as &[String],
- "expected a registration with options identical to the active ones to not refresh",
+ buffer_triggers(cx),
+ BTreeSet::from([".".to_string()]),
+ "expected the non-matching registration's triggers to be excluded from the buffer",
+ );
+ assert_eq!(
+ server_capabilities(&project, server_id, cx).completion_provider,
+ Some(colon_options.clone()),
+ "expected the latest registration's options to be active",
);
- unregister_capabilities(&fake_server, method, &["lens-b"]).await;
+ register_capability(
+ &fake_server,
+ method,
+ "completion-a",
+ Some(registration_options("untitled", ":")),
+ )
+ .await;
cx.executor().run_until_parked();
assert_eq!(
- refresh_events.lock().as_slice(),
- &[] as &[String],
- "expected an unregistration that restores identical options to not refresh",
+ buffer_triggers(cx),
+ BTreeSet::new(),
+ "expected re-registering with a non-matching selector to remove the triggers from the buffer",
);
assert_eq!(
- server_capabilities(&project, server_id, cx).code_lens_provider,
- Some(options),
- "expected the remaining registration's options to stay active",
+ server_capabilities(&project, server_id, cx).completion_provider,
+ Some(colon_options.clone()),
+ "expected the active options to survive a duplicate ID replacement of an older registration",
);
- unregister_capabilities(&fake_server, method, &["lens-a"]).await;
+ unregister_capabilities(&fake_server, method, &["completion-b"]).await;
cx.executor().run_until_parked();
assert_eq!(
- refresh_events.lock().drain(..).collect::<Vec<_>>(),
- vec![format!("code_lens({server_id})")],
- "expected the last unregistration to clear the capability and refresh",
+ buffer_triggers(cx),
+ BTreeSet::new(),
+ "expected the remaining duplicate-content registration to still not match the buffer",
);
assert_eq!(
- server_capabilities(&project, server_id, cx).code_lens_provider,
+ server_capabilities(&project, server_id, cx).completion_provider,
+ Some(colon_options),
+ "expected the capability to survive removing one of two identical registrations",
+ );
+
+ unregister_capabilities(&fake_server, method, &["completion-a"]).await;
+ cx.executor().run_until_parked();
+ assert_eq!(
+ buffer_triggers(cx),
+ BTreeSet::new(),
+ "expected no completion triggers after unregistering the last registration",
+ );
+ assert_eq!(
+ server_capabilities(&project, server_id, cx).completion_provider,
None,
- "expected the code lens provider to be cleared after unregistering the last registration",
+ "expected the completion provider to be cleared after unregistering the last registration",
);
}
@@ -566,8 +1342,8 @@ async fn test_multi_registration_completion_triggers(cx: &mut gpui::TestAppConte
cx.executor().run_until_parked();
assert_eq!(
buffer_triggers(cx),
- BTreeSet::from([":".to_string()]),
- "expected the second registration's triggers to replace the first ones",
+ BTreeSet::from([".".to_string(), ":".to_string()]),
+ "expected global dynamic registrations to union their triggers",
);
let options_a_replacement = lsp::CompletionOptions {
@@ -584,8 +1360,8 @@ async fn test_multi_registration_completion_triggers(cx: &mut gpui::TestAppConte
cx.executor().run_until_parked();
assert_eq!(
buffer_triggers(cx),
- BTreeSet::from([":".to_string()]),
- "expected the active registration's triggers to stay applied after a duplicate ID replaced an inactive one",
+ BTreeSet::from(["!".to_string(), ":".to_string()]),
+ "expected replacing a registration to update its triggers without dropping the others",
);
unregister_capabilities(&fake_server, method, &["completion-b"]).await;
@@ -649,9 +1425,9 @@ async fn test_multi_registration_middle_removal(cx: &mut gpui::TestAppContext) {
"expected the latest registration to stay active after removing an older one from the middle",
);
assert_eq!(
- refresh_events.lock().as_slice(),
- &[] as &[String],
- "expected no refresh after removing an inactive registration",
+ refresh_events.lock().drain(..).collect::<Vec<_>>(),
+ vec![format!("inlay_hints({server_id})")],
+ "expected removing an inactive registration to refresh selector-aware caches",
);
unregister_capabilities(&fake_server, method, &["inlay-hint-b"]).await;
@@ -820,8 +1596,8 @@ async fn test_multi_registration_completion_static_restore(cx: &mut gpui::TestAp
cx.executor().run_until_parked();
assert_eq!(
buffer_triggers(cx),
- BTreeSet::from([":".to_string()]),
- "expected the dynamic registration's triggers to override the static ones",
+ BTreeSet::from([".".to_string(), ":".to_string()]),
+ "expected the dynamic registration's triggers to union with the static ones",
);
unregister_capabilities(&fake_server, method, &["completion-dynamic"]).await;
@@ -1322,6 +2098,87 @@ async fn test_dynamic_registration_refreshes_lsp_data(cx: &mut gpui::TestAppCont
);
}
+#[gpui::test]
+async fn test_semantic_tokens_server_set_shrink_invalidates_completed_task(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx);
+ let (project, fake_server) =
+ setup_dynamic_registration_test(cx, lsp::ServerCapabilities::default()).await;
+ let server_id = fake_server.server.server_id();
+ let method = "textDocument/semanticTokens";
+ let (buffer, _lsp_handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/the-root/a.rs"), cx)
+ })
+ .await
+ .unwrap();
+
+ register_capability(
+ &fake_server,
+ method,
+ "semantic-tokens",
+ serde_json::to_value(lsp::SemanticTokensRegistrationOptions {
+ text_document_registration_options: lsp::TextDocumentRegistrationOptions {
+ document_selector: None,
+ },
+ semantic_tokens_options: lsp::SemanticTokensOptions {
+ legend: lsp::SemanticTokensLegend {
+ token_types: vec!["keyword".into()],
+ token_modifiers: Vec::new(),
+ },
+ full: Some(lsp::SemanticTokensFullOptions::Bool(true)),
+ ..lsp::SemanticTokensOptions::default()
+ },
+ static_registration_options: lsp::StaticRegistrationOptions::default(),
+ })
+ .ok(),
+ )
+ .await;
+ fake_server.set_request_handler::<lsp::request::SemanticTokensFullRequest, _, _>(
+ |_, _| async move {
+ Ok(Some(lsp::SemanticTokensResult::Tokens(
+ lsp::SemanticTokens {
+ result_id: None,
+ data: vec![0, 0, 2, 0, 0],
+ },
+ )))
+ },
+ );
+ cx.executor().run_until_parked();
+
+ let lsp_store = project.read_with(cx, |project, _| project.lsp_store());
+ let initial_tokens = lsp_store
+ .update(cx, |lsp_store, cx| {
+ lsp_store.semantic_tokens(buffer.clone(), cx)
+ })
+ .await
+ .unwrap();
+ assert_eq!(
+ initial_tokens
+ .tokens
+ .as_ref()
+ .map(|tokens| tokens.keys().copied().collect::<HashSet<_>>()),
+ Some(HashSet::from_iter([server_id])),
+ );
+
+ unregister_capabilities(&fake_server, method, &["semantic-tokens"]).await;
+ cx.executor().run_until_parked();
+
+ let tokens_after_unregistration = lsp_store
+ .update(cx, |lsp_store, cx| {
+ lsp_store.semantic_tokens(buffer.clone(), cx)
+ })
+ .await
+ .unwrap();
+ assert!(
+ tokens_after_unregistration
+ .tokens
+ .is_none_or(|tokens| tokens.is_empty()),
+ "expected the completed semantic-token task to drop the inapplicable server",
+ );
+}
+
#[gpui::test]
async fn test_semantic_tokens_refresh_invalidates_only_the_refreshed_server(
cx: &mut gpui::TestAppContext,
diff --git a/crates/project/tests/integration/project_tests.rs b/crates/project/tests/integration/project_tests.rs
index ca0b200b775..5acd7d2536c 100644
--- a/crates/project/tests/integration/project_tests.rs
+++ b/crates/project/tests/integration/project_tests.rs
@@ -6936,30 +6936,29 @@ async fn test_completions_with_text_edit(cx: &mut gpui::TestAppContext) {
}
#[gpui::test]
-async fn test_completions_with_edit_ranges(cx: &mut gpui::TestAppContext) {
+async fn test_dynamic_completion_registration_honors_document_selector(
+ cx: &mut gpui::TestAppContext,
+) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
- fs.insert_tree(
- path!("/dir"),
- json!({
- "a.ts": "",
- }),
- )
- .await;
+ fs.insert_tree(path!("/dir"), json!({ "a.rs": "let value = foo" }))
+ .await;
let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
-
let language_registry = project.read_with(cx, |project, _| project.languages().clone());
- language_registry.add(typescript_lang());
+ language_registry.add(rust_lang());
let mut fake_language_servers = language_registry.register_fake_lsp(
- "TypeScript",
+ "Rust",
FakeLspAdapter {
capabilities: lsp::ServerCapabilities {
- completion_provider: Some(lsp::CompletionOptions {
- trigger_characters: Some(vec![".".to_string()]),
- ..Default::default()
- }),
+ text_document_sync: Some(lsp::TextDocumentSyncCapability::Options(
+ lsp::TextDocumentSyncOptions {
+ open_close: Some(true),
+ change: Some(lsp::TextDocumentSyncKind::FULL),
+ ..lsp::TextDocumentSyncOptions::default()
+ },
+ )),
..Default::default()
},
..Default::default()
@@ -6967,242 +6966,348 @@ async fn test_completions_with_edit_ranges(cx: &mut gpui::TestAppContext) {
);
let (buffer, _handle) = project
- .update(cx, |p, cx| {
- p.open_local_buffer_with_lsp(path!("/dir/a.ts"), cx)
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/a.rs"), cx)
})
.await
.unwrap();
let fake_server = fake_language_servers.next().await.unwrap();
cx.executor().run_until_parked();
- let text = "let a = obj.fqn";
- // Test 1: When text_edit is None but text_edit_text exists with default edit_range
- {
- buffer.update(cx, |buffer, cx| buffer.set_text(text, cx));
- let completions = project.update(cx, |project, cx| {
- project.completions(&buffer, text.len(), DEFAULT_COMPLETION_CONTEXT, cx)
- });
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "untitled-completion".to_string(),
+ method: "textDocument/completion".to_string(),
+ register_options: serde_json::to_value(lsp::CompletionRegistrationOptions {
+ text_document_registration_options: lsp::TextDocumentRegistrationOptions {
+ document_selector: Some(vec![lsp::DocumentFilter {
+ language: Some("rust".to_string()),
+ scheme: Some("untitled".to_string()),
+ pattern: None,
+ }]),
+ },
+ completion_options: lsp::CompletionOptions {
+ trigger_characters: Some(vec![".".to_string()]),
+ ..lsp::CompletionOptions::default()
+ },
+ })
+ .ok(),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
- fake_server
- .set_request_handler::<lsp::request::Completion, _, _>(|_, _| async {
- Ok(Some(lsp::CompletionResponse::List(lsp::CompletionList {
- is_incomplete: false,
- item_defaults: Some(lsp::CompletionListItemDefaults {
- edit_range: Some(lsp::CompletionListItemDefaultsEditRange::Range(
- lsp::Range::new(
- lsp::Position::new(0, text.len() as u32 - 3),
- lsp::Position::new(0, text.len() as u32),
- ),
- )),
- ..Default::default()
- }),
- items: vec![lsp::CompletionItem {
- label: "labelText".into(),
- text_edit_text: Some("textEditText".into()),
- text_edit: None,
+ assert!(buffer.read_with(cx, |buffer, _| buffer.completion_triggers().is_empty()));
+
+ let completion_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _completion_requests = fake_server.set_request_handler::<lsp::request::Completion, _, _>({
+ let completion_request_count = completion_request_count.clone();
+ move |_, _| {
+ completion_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move {
+ Ok(Some(lsp::CompletionResponse::Array(vec![
+ lsp::CompletionItem {
+ label: "matched".into(),
..Default::default()
- }],
- })))
- })
- .next()
- .await;
+ },
+ ])))
+ }
+ }
+ });
- let completions = completions
- .await
- .unwrap()
- .into_iter()
- .flat_map(|response| response.completions)
- .collect::<Vec<_>>();
- let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
+ let completions = project
+ .update(cx, |project, cx| {
+ project.completions(&buffer, 15, DEFAULT_COMPLETION_CONTEXT, cx)
+ })
+ .await
+ .unwrap();
+ assert!(completions.is_empty());
+ assert_eq!(completion_request_count.load(atomic::Ordering::SeqCst), 0);
- assert_eq!(completions.len(), 1);
- assert_eq!(completions[0].new_text, "textEditText");
- assert_eq!(
- completions[0].replace_range.to_offset(&snapshot),
- text.len() - 3..text.len()
- );
- }
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "file-completion".to_string(),
+ method: "textDocument/completion".to_string(),
+ register_options: serde_json::to_value(lsp::CompletionRegistrationOptions {
+ text_document_registration_options: lsp::TextDocumentRegistrationOptions {
+ document_selector: Some(vec![lsp::DocumentFilter {
+ language: Some("rust".to_string()),
+ scheme: Some("file".to_string()),
+ pattern: None,
+ }]),
+ },
+ completion_options: lsp::CompletionOptions {
+ trigger_characters: Some(vec![":".to_string()]),
+ ..lsp::CompletionOptions::default()
+ },
+ })
+ .ok(),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
- // Test 2: When both text_edit and text_edit_text are None with default edit_range
- {
- buffer.update(cx, |buffer, cx| buffer.set_text(text, cx));
- let completions = project.update(cx, |project, cx| {
- project.completions(&buffer, text.len(), DEFAULT_COMPLETION_CONTEXT, cx)
- });
+ assert_eq!(
+ buffer.read_with(cx, |buffer, _| buffer.completion_triggers().clone()),
+ BTreeSet::from([":".to_string()])
+ );
- fake_server
- .set_request_handler::<lsp::request::Completion, _, _>(|_, _| async {
- Ok(Some(lsp::CompletionResponse::List(lsp::CompletionList {
- is_incomplete: false,
- item_defaults: Some(lsp::CompletionListItemDefaults {
- edit_range: Some(lsp::CompletionListItemDefaultsEditRange::Range(
- lsp::Range::new(
- lsp::Position::new(0, text.len() as u32 - 3),
- lsp::Position::new(0, text.len() as u32),
- ),
- )),
- ..Default::default()
- }),
- items: vec![lsp::CompletionItem {
- label: "labelText".into(),
- text_edit_text: None,
- insert_text: Some("irrelevant".into()),
- text_edit: None,
- ..Default::default()
- }],
- })))
- })
- .next()
- .await;
+ let completions = project
+ .update(cx, |project, cx| {
+ project.completions(&buffer, 15, DEFAULT_COMPLETION_CONTEXT, cx)
+ })
+ .await
+ .unwrap()
+ .into_iter()
+ .flat_map(|response| response.completions)
+ .collect::<Vec<_>>();
- let completions = completions
- .await
- .unwrap()
- .into_iter()
- .flat_map(|response| response.completions)
- .collect::<Vec<_>>();
- let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
+ assert_eq!(completions.len(), 1);
+ assert_eq!(completions[0].new_text, "matched");
+ assert_eq!(completion_request_count.load(atomic::Ordering::SeqCst), 1);
- assert_eq!(completions.len(), 1);
- assert_eq!(completions[0].new_text, "labelText");
- assert_eq!(
- completions[0].replace_range.to_offset(&snapshot),
- text.len() - 3..text.len()
- );
- }
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "second-file-completion".to_string(),
+ method: "textDocument/completion".to_string(),
+ register_options: serde_json::to_value(lsp::CompletionRegistrationOptions {
+ text_document_registration_options: lsp::TextDocumentRegistrationOptions {
+ document_selector: Some(vec![lsp::DocumentFilter {
+ language: Some("rust".to_string()),
+ scheme: Some("file".to_string()),
+ pattern: None,
+ }]),
+ },
+ completion_options: lsp::CompletionOptions {
+ trigger_characters: Some(vec!["!".to_string()]),
+ ..lsp::CompletionOptions::default()
+ },
+ })
+ .ok(),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ assert_eq!(
+ buffer.read_with(cx, |buffer, _| buffer.completion_triggers().clone()),
+ BTreeSet::from(["!".to_string(), ":".to_string()])
+ );
+
+ fake_server
+ .request::<lsp::request::UnregisterCapability>(
+ lsp::UnregistrationParams {
+ unregisterations: vec![lsp::Unregistration {
+ id: "file-completion".to_string(),
+ method: "textDocument/completion".to_string(),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ assert_eq!(
+ buffer.read_with(cx, |buffer, _| buffer.completion_triggers().clone()),
+ BTreeSet::from(["!".to_string()])
+ );
+ let completions = project
+ .update(cx, |project, cx| {
+ project.completions(&buffer, 15, DEFAULT_COMPLETION_CONTEXT, cx)
+ })
+ .await
+ .unwrap();
+ assert_eq!(completions.len(), 1);
+ assert_eq!(completion_request_count.load(atomic::Ordering::SeqCst), 2);
+
+ fake_server
+ .request::<lsp::request::UnregisterCapability>(
+ lsp::UnregistrationParams {
+ unregisterations: vec![lsp::Unregistration {
+ id: "second-file-completion".to_string(),
+ method: "textDocument/completion".to_string(),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ assert!(buffer.read_with(cx, |buffer, _| buffer.completion_triggers().is_empty()));
+ let completions = project
+ .update(cx, |project, cx| {
+ project.completions(&buffer, 15, DEFAULT_COMPLETION_CONTEXT, cx)
+ })
+ .await
+ .unwrap();
+ assert!(completions.is_empty());
+ assert_eq!(completion_request_count.load(atomic::Ordering::SeqCst), 2);
}
#[gpui::test]
-async fn test_completions_without_edit_ranges(cx: &mut gpui::TestAppContext) {
+async fn test_dynamic_diagnostic_registrations_honor_their_own_document_selectors(
+ cx: &mut gpui::TestAppContext,
+) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
- fs.insert_tree(
- path!("/dir"),
- json!({
- "a.ts": "",
- }),
- )
- .await;
+ fs.insert_tree(path!("/dir"), json!({ "a.rs": "let value = foo" }))
+ .await;
let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
-
let language_registry = project.read_with(cx, |project, _| project.languages().clone());
- language_registry.add(typescript_lang());
+ language_registry.add(rust_lang());
let mut fake_language_servers = language_registry.register_fake_lsp(
- "TypeScript",
+ "Rust",
FakeLspAdapter {
capabilities: lsp::ServerCapabilities {
- completion_provider: Some(lsp::CompletionOptions {
- trigger_characters: Some(vec![":".to_string()]),
- ..Default::default()
- }),
+ text_document_sync: Some(lsp::TextDocumentSyncCapability::Options(
+ lsp::TextDocumentSyncOptions {
+ open_close: Some(true),
+ change: Some(lsp::TextDocumentSyncKind::FULL),
+ ..lsp::TextDocumentSyncOptions::default()
+ },
+ )),
..Default::default()
},
..Default::default()
},
);
- let (buffer, _handle) = project
- .update(cx, |p, cx| {
- p.open_local_buffer_with_lsp(path!("/dir/a.ts"), cx)
+ let (_buffer, _handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/a.rs"), cx)
})
.await
.unwrap();
-
let fake_server = fake_language_servers.next().await.unwrap();
cx.executor().run_until_parked();
- // Test 1: When text_edit is None but insert_text exists (no edit_range in defaults)
- let text = "let a = b.fqn";
- buffer.update(cx, |buffer, cx| buffer.set_text(text, cx));
- let completions = project.update(cx, |project, cx| {
- project.completions(&buffer, text.len(), DEFAULT_COMPLETION_CONTEXT, cx)
- });
+ let file_diagnostic_requests = Arc::new(atomic::AtomicUsize::new(0));
+ let untitled_diagnostic_requests = Arc::new(atomic::AtomicUsize::new(0));
+ let _diagnostic_requests = fake_server
+ .set_request_handler::<lsp::request::DocumentDiagnosticRequest, _, _>({
+ let file_diagnostic_requests = file_diagnostic_requests.clone();
+ let untitled_diagnostic_requests = untitled_diagnostic_requests.clone();
+ move |params, _| {
+ match params.identifier.as_deref() {
+ Some("file") => {
+ file_diagnostic_requests.fetch_add(1, atomic::Ordering::SeqCst);
+ }
+ Some("untitled") => {
+ untitled_diagnostic_requests.fetch_add(1, atomic::Ordering::SeqCst);
+ }
+ identifier => panic!("unexpected diagnostic identifier: {identifier:?}"),
+ }
+ async {
+ Ok(lsp::DocumentDiagnosticReportResult::Report(
+ lsp::DocumentDiagnosticReport::Full(
+ lsp::RelatedFullDocumentDiagnosticReport {
+ related_documents: None,
+ full_document_diagnostic_report:
+ lsp::FullDocumentDiagnosticReport {
+ result_id: None,
+ items: Vec::new(),
+ },
+ },
+ ),
+ ))
+ }
+ }
+ });
- fake_server
- .set_request_handler::<lsp::request::Completion, _, _>(|_, _| async move {
- Ok(Some(lsp::CompletionResponse::Array(vec![
- lsp::CompletionItem {
- label: "fullyQualifiedName?".into(),
- insert_text: Some("fullyQualifiedName".into()),
- ..Default::default()
- },
- ])))
+ let diagnostic_registration = |identifier: &str, scheme: &str| {
+ serde_json::to_value(lsp::DiagnosticRegistrationOptions {
+ text_document_registration_options: lsp::TextDocumentRegistrationOptions {
+ document_selector: Some(vec![lsp::DocumentFilter {
+ language: Some("rust".to_string()),
+ scheme: Some(scheme.to_string()),
+ pattern: None,
+ }]),
+ },
+ diagnostic_options: lsp::DiagnosticOptions {
+ identifier: Some(identifier.to_string()),
+ inter_file_dependencies: false,
+ workspace_diagnostics: false,
+ ..lsp::DiagnosticOptions::default()
+ },
+ static_registration_options: lsp::StaticRegistrationOptions::default(),
})
- .next()
- .await;
- let completions = completions
- .await
- .unwrap()
- .into_iter()
- .flat_map(|response| response.completions)
- .collect::<Vec<_>>();
- let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
- assert_eq!(completions.len(), 1);
- assert_eq!(completions[0].new_text, "fullyQualifiedName");
- assert_eq!(
- completions[0].replace_range.to_offset(&snapshot),
- text.len() - 3..text.len()
- );
-
- // Test 2: When both text_edit and insert_text are None (no edit_range in defaults)
- let text = "let a = \"atoms/cmp\"";
- buffer.update(cx, |buffer, cx| buffer.set_text(text, cx));
- let completions = project.update(cx, |project, cx| {
- project.completions(&buffer, text.len() - 1, DEFAULT_COMPLETION_CONTEXT, cx)
- });
-
+ .ok()
+ };
fake_server
- .set_request_handler::<lsp::request::Completion, _, _>(|_, _| async move {
- Ok(Some(lsp::CompletionResponse::Array(vec![
- lsp::CompletionItem {
- label: "component".into(),
- ..Default::default()
- },
- ])))
- })
- .next()
- .await;
- let completions = completions
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![
+ lsp::Registration {
+ id: "untitled-diagnostics".to_string(),
+ method: "textDocument/diagnostic".to_string(),
+ register_options: diagnostic_registration("untitled", "untitled"),
+ },
+ lsp::Registration {
+ id: "file-diagnostics".to_string(),
+ method: "textDocument/diagnostic".to_string(),
+ register_options: diagnostic_registration("file", "file"),
+ },
+ ],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
.await
- .unwrap()
- .into_iter()
- .flat_map(|response| response.completions)
- .collect::<Vec<_>>();
- let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
- assert_eq!(completions.len(), 1);
- assert_eq!(completions[0].new_text, "component");
+ .into_response()
+ .unwrap();
+ cx.executor().advance_clock(Duration::from_secs(1));
+ cx.executor().run_until_parked();
+
+ assert_eq!(file_diagnostic_requests.load(atomic::Ordering::SeqCst), 1);
assert_eq!(
- completions[0].replace_range.to_offset(&snapshot),
- text.len() - 4..text.len() - 1
+ untitled_diagnostic_requests.load(atomic::Ordering::SeqCst),
+ 0
);
}
#[gpui::test]
-async fn test_completions_with_carriage_returns(cx: &mut gpui::TestAppContext) {
+async fn test_unregistering_dynamic_completion_preserves_static_capability(
+ cx: &mut gpui::TestAppContext,
+) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
- fs.insert_tree(
- path!("/dir"),
- json!({
- "a.ts": "",
- }),
- )
- .await;
+ fs.insert_tree(path!("/dir"), json!({ "a.rs": "let value = foo" }))
+ .await;
let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
-
let language_registry = project.read_with(cx, |project, _| project.languages().clone());
- language_registry.add(typescript_lang());
+ language_registry.add(rust_lang());
let mut fake_language_servers = language_registry.register_fake_lsp(
- "TypeScript",
+ "Rust",
FakeLspAdapter {
capabilities: lsp::ServerCapabilities {
completion_provider: Some(lsp::CompletionOptions {
- trigger_characters: Some(vec![":".to_string()]),
+ trigger_characters: Some(vec![".".to_string()]),
..Default::default()
}),
..Default::default()
@@ -7212,131 +7317,288 @@ async fn test_completions_with_carriage_returns(cx: &mut gpui::TestAppContext) {
);
let (buffer, _handle) = project
- .update(cx, |p, cx| {
- p.open_local_buffer_with_lsp(path!("/dir/a.ts"), cx)
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/a.rs"), cx)
})
.await
.unwrap();
-
let fake_server = fake_language_servers.next().await.unwrap();
cx.executor().run_until_parked();
- let text = "let a = b.fqn";
- buffer.update(cx, |buffer, cx| buffer.set_text(text, cx));
- let completions = project.update(cx, |project, cx| {
- project.completions(&buffer, text.len(), DEFAULT_COMPLETION_CONTEXT, cx)
- });
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "dynamic-completion".to_string(),
+ method: "textDocument/completion".to_string(),
+ register_options: serde_json::to_value(lsp::CompletionRegistrationOptions {
+ text_document_registration_options: lsp::TextDocumentRegistrationOptions {
+ document_selector: Some(vec![lsp::DocumentFilter {
+ language: Some("rust".to_string()),
+ scheme: Some("file".to_string()),
+ pattern: None,
+ }]),
+ },
+ completion_options: lsp::CompletionOptions {
+ trigger_characters: Some(vec![":".to_string()]),
+ ..lsp::CompletionOptions::default()
+ },
+ })
+ .ok(),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ assert_eq!(
+ buffer.read_with(cx, |buffer, _| buffer.completion_triggers().clone()),
+ BTreeSet::from([".".to_string(), ":".to_string()])
+ );
fake_server
- .set_request_handler::<lsp::request::Completion, _, _>(|_, _| async move {
- Ok(Some(lsp::CompletionResponse::Array(vec![
- lsp::CompletionItem {
- label: "fullyQualifiedName?".into(),
- insert_text: Some("fully\rQualified\r\nName".into()),
- ..Default::default()
- },
- ])))
- })
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "global-completion".to_string(),
+ method: "textDocument/completion".to_string(),
+ register_options: serde_json::to_value(lsp::CompletionRegistrationOptions {
+ text_document_registration_options: lsp::TextDocumentRegistrationOptions {
+ document_selector: None,
+ },
+ completion_options: lsp::CompletionOptions {
+ trigger_characters: Some(vec!["@".to_string()]),
+ ..lsp::CompletionOptions::default()
+ },
+ })
+ .ok(),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ assert_eq!(
+ buffer.read_with(cx, |buffer, _| buffer.completion_triggers().clone()),
+ BTreeSet::from([".".to_string(), ":".to_string(), "@".to_string()]),
+ "expected static triggers to stay active alongside a global dynamic registration",
+ );
+
+ fake_server
+ .request::<lsp::request::UnregisterCapability>(
+ lsp::UnregistrationParams {
+ unregisterations: vec![lsp::Unregistration {
+ id: "global-completion".to_string(),
+ method: "textDocument/completion".to_string(),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ assert_eq!(
+ buffer.read_with(cx, |buffer, _| buffer.completion_triggers().clone()),
+ BTreeSet::from([".".to_string(), ":".to_string()])
+ );
+
+ fake_server
+ .request::<lsp::request::UnregisterCapability>(
+ lsp::UnregistrationParams {
+ unregisterations: vec![lsp::Unregistration {
+ id: "dynamic-completion".to_string(),
+ method: "textDocument/completion".to_string(),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ assert_eq!(
+ buffer.read_with(cx, |buffer, _| buffer.completion_triggers().clone()),
+ BTreeSet::from([".".to_string()])
+ );
+
+ let mut completion_request =
+ fake_server.set_request_handler::<lsp::request::Completion, _, _>(|_, _| async {
+ Ok(Some(lsp::CompletionResponse::Array(Vec::new())))
+ });
+ let completions = project.update(cx, |project, cx| {
+ project.completions(&buffer, 15, DEFAULT_COMPLETION_CONTEXT, cx)
+ });
+ completion_request
.next()
- .await;
- let completions = completions
.await
- .unwrap()
- .into_iter()
- .flat_map(|response| response.completions)
- .collect::<Vec<_>>();
- assert_eq!(completions.len(), 1);
- assert_eq!(completions[0].new_text, "fully\nQualified\nName");
+ .expect("The static completion provider should remain active");
+ assert!(
+ completions
+ .await
+ .unwrap()
+ .into_iter()
+ .flat_map(|response| response.completions)
+ .next()
+ .is_none()
+ );
}
#[gpui::test]
-async fn test_supports_range_formatting_ignores_unrelated_language_servers(
- cx: &mut gpui::TestAppContext,
-) {
+async fn test_completions_with_edit_ranges(cx: &mut gpui::TestAppContext) {
init_test(cx);
- cx.update(|cx| {
- SettingsStore::update_global(cx, |store, cx| {
- store.update_user_settings(cx, |settings| {
- settings.project.all_languages.defaults.formatter = Some(FormatterList::Single(
- Formatter::LanguageServer(settings::LanguageServerFormatterSpecifier::Current),
- ));
- });
- });
- });
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
path!("/dir"),
json!({
"a.ts": "",
- "b.rs": "",
}),
)
.await;
let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+
let language_registry = project.read_with(cx, |project, _| project.languages().clone());
language_registry.add(typescript_lang());
- language_registry.add(rust_lang());
-
- let mut typescript_language_servers = language_registry.register_fake_lsp(
+ let mut fake_language_servers = language_registry.register_fake_lsp(
"TypeScript",
FakeLspAdapter {
- name: "typescript-fake-language-server",
- capabilities: lsp::ServerCapabilities {
- document_range_formatting_provider: Some(lsp::OneOf::Left(true)),
- ..lsp::ServerCapabilities::default()
- },
- ..FakeLspAdapter::default()
- },
- );
- let mut rust_language_servers = language_registry.register_fake_lsp(
- "Rust",
- FakeLspAdapter {
- name: "rust-fake-language-server",
capabilities: lsp::ServerCapabilities {
- document_formatting_provider: Some(lsp::OneOf::Left(true)),
- document_range_formatting_provider: Some(lsp::OneOf::Left(false)),
+ completion_provider: Some(lsp::CompletionOptions {
+ trigger_characters: Some(vec![".".to_string()]),
+ ..lsp::CompletionOptions::default()
+ }),
..lsp::ServerCapabilities::default()
},
..FakeLspAdapter::default()
},
);
- let (typescript_buffer, _typescript_handle) = project
- .update(cx, |project, cx| {
- project.open_local_buffer_with_lsp(path!("/dir/a.ts"), cx)
- })
- .await
- .unwrap();
- let (rust_buffer, _rust_handle) = project
- .update(cx, |project, cx| {
- project.open_local_buffer_with_lsp(path!("/dir/b.rs"), cx)
+ let (buffer, _handle) = project
+ .update(cx, |p, cx| {
+ p.open_local_buffer_with_lsp(path!("/dir/a.ts"), cx)
})
.await
.unwrap();
- let _typescript_language_server = typescript_language_servers.next().await.unwrap();
- let _rust_language_server = rust_language_servers.next().await.unwrap();
+ let fake_server = fake_language_servers.next().await.unwrap();
cx.executor().run_until_parked();
+ let text = "let a = obj.fqn";
- assert!(project.read_with(cx, |project, cx| {
- project.supports_range_formatting(&typescript_buffer, cx)
- }));
- assert!(!project.read_with(cx, |project, cx| {
- project.supports_range_formatting(&rust_buffer, cx)
- }));
+ // Test 1: When text_edit is None but text_edit_text exists with default edit_range
+ {
+ buffer.update(cx, |buffer, cx| buffer.set_text(text, cx));
+ let completions = project.update(cx, |project, cx| {
+ project.completions(&buffer, text.len(), DEFAULT_COMPLETION_CONTEXT, cx)
+ });
+
+ fake_server
+ .set_request_handler::<lsp::request::Completion, _, _>(|_, _| async {
+ Ok(Some(lsp::CompletionResponse::List(lsp::CompletionList {
+ is_incomplete: false,
+ item_defaults: Some(lsp::CompletionListItemDefaults {
+ edit_range: Some(lsp::CompletionListItemDefaultsEditRange::Range(
+ lsp::Range::new(
+ lsp::Position::new(0, text.len() as u32 - 3),
+ lsp::Position::new(0, text.len() as u32),
+ ),
+ )),
+ ..lsp::CompletionListItemDefaults::default()
+ }),
+ items: vec![lsp::CompletionItem {
+ label: "labelText".into(),
+ text_edit_text: Some("textEditText".into()),
+ text_edit: None,
+ ..lsp::CompletionItem::default()
+ }],
+ })))
+ })
+ .next()
+ .await;
+
+ let completions = completions
+ .await
+ .unwrap()
+ .into_iter()
+ .flat_map(|response| response.completions)
+ .collect::<Vec<_>>();
+ let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
+
+ assert_eq!(completions.len(), 1);
+ assert_eq!(completions[0].new_text, "textEditText");
+ assert_eq!(
+ completions[0].replace_range.to_offset(&snapshot),
+ text.len() - 3..text.len()
+ );
+ }
+
+ // Test 2: When both text_edit and text_edit_text are None with default edit_range
+ {
+ buffer.update(cx, |buffer, cx| buffer.set_text(text, cx));
+ let completions = project.update(cx, |project, cx| {
+ project.completions(&buffer, text.len(), DEFAULT_COMPLETION_CONTEXT, cx)
+ });
+
+ fake_server
+ .set_request_handler::<lsp::request::Completion, _, _>(|_, _| async {
+ Ok(Some(lsp::CompletionResponse::List(lsp::CompletionList {
+ is_incomplete: false,
+ item_defaults: Some(lsp::CompletionListItemDefaults {
+ edit_range: Some(lsp::CompletionListItemDefaultsEditRange::Range(
+ lsp::Range::new(
+ lsp::Position::new(0, text.len() as u32 - 3),
+ lsp::Position::new(0, text.len() as u32),
+ ),
+ )),
+ ..lsp::CompletionListItemDefaults::default()
+ }),
+ items: vec![lsp::CompletionItem {
+ label: "labelText".into(),
+ text_edit_text: None,
+ insert_text: Some("irrelevant".into()),
+ text_edit: None,
+ ..lsp::CompletionItem::default()
+ }],
+ })))
+ })
+ .next()
+ .await;
+
+ let completions = completions
+ .await
+ .unwrap()
+ .into_iter()
+ .flat_map(|response| response.completions)
+ .collect::<Vec<_>>();
+ let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
+
+ assert_eq!(completions.len(), 1);
+ assert_eq!(completions[0].new_text, "labelText");
+ assert_eq!(
+ completions[0].replace_range.to_offset(&snapshot),
+ text.len() - 3..text.len()
+ );
+ }
}
-#[gpui::test(iterations = 10)]
-async fn test_apply_code_actions_with_commands(cx: &mut gpui::TestAppContext) {
+#[gpui::test]
+async fn test_completions_without_edit_ranges(cx: &mut gpui::TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
path!("/dir"),
json!({
- "a.ts": "a",
+ "a.ts": "",
}),
)
.await;
@@ -7349,15 +7611,9 @@ async fn test_apply_code_actions_with_commands(cx: &mut gpui::TestAppContext) {
"TypeScript",
FakeLspAdapter {
capabilities: lsp::ServerCapabilities {
- code_action_provider: Some(lsp::CodeActionProviderCapability::Options(
- lsp::CodeActionOptions {
- resolve_provider: Some(true),
- ..lsp::CodeActionOptions::default()
- },
- )),
- execute_command_provider: Some(lsp::ExecuteCommandOptions {
- commands: vec!["_the/command".to_string()],
- ..lsp::ExecuteCommandOptions::default()
+ completion_provider: Some(lsp::CompletionOptions {
+ trigger_characters: Some(vec![":".to_string()]),
+ ..lsp::CompletionOptions::default()
}),
..lsp::ServerCapabilities::default()
},
@@ -7375,1916 +7631,3572 @@ async fn test_apply_code_actions_with_commands(cx: &mut gpui::TestAppContext) {
let fake_server = fake_language_servers.next().await.unwrap();
cx.executor().run_until_parked();
- // Language server returns code actions that contain commands, and not edits.
- let actions = project.update(cx, |project, cx| {
- project.code_actions(&buffer, 0..0, None, cx)
+ // Test 1: When text_edit is None but insert_text exists (no edit_range in defaults)
+ let text = "let a = b.fqn";
+ buffer.update(cx, |buffer, cx| buffer.set_text(text, cx));
+ let completions = project.update(cx, |project, cx| {
+ project.completions(&buffer, text.len(), DEFAULT_COMPLETION_CONTEXT, cx)
});
+
fake_server
- .set_request_handler::<lsp::request::CodeActionRequest, _, _>(|_, _| async move {
- Ok(Some(vec![
- lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
- title: "The code action".into(),
- data: Some(serde_json::json!({
- "command": "_the/command",
- })),
- ..lsp::CodeAction::default()
- }),
- lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
- title: "two".into(),
- ..lsp::CodeAction::default()
- }),
- ]))
+ .set_request_handler::<lsp::request::Completion, _, _>(|_, _| async move {
+ Ok(Some(lsp::CompletionResponse::Array(vec![
+ lsp::CompletionItem {
+ label: "fullyQualifiedName?".into(),
+ insert_text: Some("fullyQualifiedName".into()),
+ ..lsp::CompletionItem::default()
+ },
+ ])))
})
.next()
.await;
+ let completions = completions
+ .await
+ .unwrap()
+ .into_iter()
+ .flat_map(|response| response.completions)
+ .collect::<Vec<_>>();
+ let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
+ assert_eq!(completions.len(), 1);
+ assert_eq!(completions[0].new_text, "fullyQualifiedName");
+ assert_eq!(
+ completions[0].replace_range.to_offset(&snapshot),
+ text.len() - 3..text.len()
+ );
- let action = actions.await.unwrap().unwrap()[0].clone();
- let apply = project.update(cx, |project, cx| {
- project.apply_code_action(buffer.clone(), action, true, cx)
+ // Test 2: When both text_edit and insert_text are None (no edit_range in defaults)
+ let text = "let a = \"atoms/cmp\"";
+ buffer.update(cx, |buffer, cx| buffer.set_text(text, cx));
+ let completions = project.update(cx, |project, cx| {
+ project.completions(&buffer, text.len() - 1, DEFAULT_COMPLETION_CONTEXT, cx)
});
- // Resolving the code action does not populate its edits. In absence of
- // edits, we must execute the given command.
- fake_server.set_request_handler::<lsp::request::CodeActionResolveRequest, _, _>(
- |mut action, _| async move {
- if action.data.is_some() {
- action.command = Some(lsp::Command {
- title: "The command".into(),
- command: "_the/command".into(),
- arguments: Some(vec![json!("the-argument")]),
- });
- }
- Ok(action)
- },
- );
-
- // While executing the command, the language server sends the editor
- // a `workspaceEdit` request.
fake_server
- .set_request_handler::<lsp::request::ExecuteCommand, _, _>({
- let fake = fake_server.clone();
- move |params, _| {
- assert_eq!(params.command, "_the/command");
- let fake = fake.clone();
- async move {
- fake.server
- .request::<lsp::request::ApplyWorkspaceEdit>(
- lsp::ApplyWorkspaceEditParams {
- label: None,
- edit: lsp::WorkspaceEdit {
- changes: Some(
- [(
- lsp::Uri::from_file_path(path!("/dir/a.ts")).unwrap(),
- vec![lsp::TextEdit {
- range: lsp::Range::new(
- lsp::Position::new(0, 0),
- lsp::Position::new(0, 0),
- ),
- new_text: "X".into(),
- }],
- )]
- .into_iter()
- .collect(),
- ),
- ..Default::default()
- },
- },
- DEFAULT_LSP_REQUEST_TIMEOUT,
- )
- .await
- .into_response()
- .unwrap();
- Ok(Some(json!(null)))
- }
- }
+ .set_request_handler::<lsp::request::Completion, _, _>(|_, _| async move {
+ Ok(Some(lsp::CompletionResponse::Array(vec![
+ lsp::CompletionItem {
+ label: "component".into(),
+ ..lsp::CompletionItem::default()
+ },
+ ])))
})
.next()
.await;
-
- // Applying the code action returns a project transaction containing the edits
- // sent by the language server in its `workspaceEdit` request.
- let transaction = apply.await.unwrap();
- assert!(transaction.0.contains_key(&buffer));
- buffer.update(cx, |buffer, cx| {
- assert_eq!(buffer.text(), "Xa");
- buffer.undo(cx);
- assert_eq!(buffer.text(), "a");
- });
+ let completions = completions
+ .await
+ .unwrap()
+ .into_iter()
+ .flat_map(|response| response.completions)
+ .collect::<Vec<_>>();
+ let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
+ assert_eq!(completions.len(), 1);
+ assert_eq!(completions[0].new_text, "component");
+ assert_eq!(
+ completions[0].replace_range.to_offset(&snapshot),
+ text.len() - 4..text.len() - 1
+ );
}
#[gpui::test]
-async fn test_rename_file_to_new_directory(cx: &mut gpui::TestAppContext) {
- init_test(cx);
- let fs = FakeFs::new(cx.background_executor.clone());
- let expected_contents = "content";
- fs.as_fake()
- .insert_tree(
- "/root",
- json!({
- "test.txt": expected_contents
- }),
- )
- .await;
-
- let project = Project::test(fs, [path!("/root").as_ref()], cx).await;
-
- let (worktree, entry_id) = project.read_with(cx, |project, cx| {
- let worktree = project.worktrees(cx).next().unwrap();
- let entry_id = worktree
- .read(cx)
- .entry_for_path(rel_path("test.txt"))
- .unwrap()
- .id;
- (worktree, entry_id)
- });
- let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
- let _result = project
- .update(cx, |project, cx| {
- project.rename_entry(
- entry_id,
- (worktree_id, rel_path("dir1/dir2/dir3/test.txt")).into(),
- cx,
- )
- })
- .await
- .unwrap();
- worktree.read_with(cx, |worktree, _| {
- assert!(
- worktree.entry_for_path(rel_path("test.txt")).is_none(),
- "Old file should have been removed"
- );
- assert!(
- worktree
- .entry_for_path(rel_path("dir1/dir2/dir3/test.txt"))
- .is_some(),
- "Whole directory hierarchy and the new file should have been created"
- );
- });
- assert_eq!(
- worktree
- .update(cx, |worktree, cx| {
- worktree.load_file(rel_path("dir1/dir2/dir3/test.txt"), cx)
- })
- .await
- .unwrap()
- .text
- .to_string(),
- expected_contents,
- "Moved file's contents should be preserved"
- );
-
- let entry_id = worktree.read_with(cx, |worktree, _| {
- worktree
- .entry_for_path(rel_path("dir1/dir2/dir3/test.txt"))
- .unwrap()
- .id
- });
-
- let _result = project
- .update(cx, |project, cx| {
- project.rename_entry(
- entry_id,
- (worktree_id, rel_path("dir1/dir2/test.txt")).into(),
- cx,
- )
- })
- .await
- .unwrap();
- worktree.read_with(cx, |worktree, _| {
- assert!(
- worktree.entry_for_path(rel_path("test.txt")).is_none(),
- "First file should not reappear"
- );
- assert!(
- worktree
- .entry_for_path(rel_path("dir1/dir2/dir3/test.txt"))
- .is_none(),
- "Old file should have been removed"
- );
- assert!(
- worktree
- .entry_for_path(rel_path("dir1/dir2/test.txt"))
- .is_some(),
- "No error should have occurred after moving into existing directory"
- );
- });
- assert_eq!(
- worktree
- .update(cx, |worktree, cx| {
- worktree.load_file(rel_path("dir1/dir2/test.txt"), cx)
- })
- .await
- .unwrap()
- .text
- .to_string(),
- expected_contents,
- "Moved file's contents should be preserved"
- );
-}
-
-#[gpui::test(iterations = 10)]
-async fn test_save_file(cx: &mut gpui::TestAppContext) {
+async fn test_completions_with_carriage_returns(cx: &mut gpui::TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
path!("/dir"),
json!({
- "file1": "the old contents",
+ "a.ts": "",
}),
)
.await;
- let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
- let buffer = project
- .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file1"), cx))
- .await
- .unwrap();
- buffer.update(cx, |buffer, cx| {
- assert_eq!(buffer.text(), "the old contents");
- buffer.edit([(0..0, "a line of text.\n".repeat(10 * 1024))], None, cx);
- });
-
- project
- .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
- .await
- .unwrap();
-
- let new_text = fs
- .load(Path::new(path!("/dir/file1")))
- .await
- .unwrap()
- .replace("\r\n", "\n");
- assert_eq!(new_text, buffer.update(cx, |buffer, _| buffer.text()));
-}
-
-#[gpui::test(iterations = 10)]
-async fn test_save_file_spawns_language_server(cx: &mut gpui::TestAppContext) {
- // Issue: #24349
- init_test(cx);
-
- let fs = FakeFs::new(cx.executor());
- fs.insert_tree(path!("/dir"), json!({})).await;
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
- let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
let language_registry = project.read_with(cx, |project, _| project.languages().clone());
-
- language_registry.add(rust_lang());
- let mut fake_rust_servers = language_registry.register_fake_lsp(
- "Rust",
+ language_registry.add(typescript_lang());
+ let mut fake_language_servers = language_registry.register_fake_lsp(
+ "TypeScript",
FakeLspAdapter {
- name: "the-rust-language-server",
capabilities: lsp::ServerCapabilities {
completion_provider: Some(lsp::CompletionOptions {
- trigger_characters: Some(vec![".".to_string(), "::".to_string()]),
+ trigger_characters: Some(vec![":".to_string()]),
..Default::default()
}),
- text_document_sync: Some(lsp::TextDocumentSyncCapability::Options(
- lsp::TextDocumentSyncOptions {
- save: Some(lsp::TextDocumentSyncSaveOptions::Supported(true)),
- ..Default::default()
- },
- )),
..Default::default()
},
..Default::default()
},
);
- let buffer = project
- .update(cx, |this, cx| this.create_buffer(None, false, cx))
- .unwrap()
- .await;
- project.update(cx, |this, cx| {
- this.register_buffer_with_language_servers(&buffer, cx);
- buffer.update(cx, |buffer, cx| {
- assert!(!this.has_language_servers_for(buffer, cx));
+ let (buffer, _handle) = project
+ .update(cx, |p, cx| {
+ p.open_local_buffer_with_lsp(path!("/dir/a.ts"), cx)
})
+ .await
+ .unwrap();
+
+ let fake_server = fake_language_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+
+ let text = "let a = b.fqn";
+ buffer.update(cx, |buffer, cx| buffer.set_text(text, cx));
+ let completions = project.update(cx, |project, cx| {
+ project.completions(&buffer, text.len(), DEFAULT_COMPLETION_CONTEXT, cx)
});
- project
- .update(cx, |this, cx| {
- let worktree_id = this.worktrees(cx).next().unwrap().read(cx).id();
- this.save_buffer_as(
- buffer.clone(),
- ProjectPath {
- worktree_id,
- path: rel_path("file.rs").into(),
+ fake_server
+ .set_request_handler::<lsp::request::Completion, _, _>(|_, _| async move {
+ Ok(Some(lsp::CompletionResponse::Array(vec![
+ lsp::CompletionItem {
+ label: "fullyQualifiedName?".into(),
+ insert_text: Some("fully\rQualified\r\nName".into()),
+ ..lsp::CompletionItem::default()
},
- cx,
- )
+ ])))
})
+ .next()
+ .await;
+ let completions = completions
.await
- .unwrap();
- // A server is started up, and it is notified about Rust files.
- let mut fake_rust_server = fake_rust_servers.next().await.unwrap();
- assert_eq!(
- fake_rust_server
- .receive_notification::<lsp::notification::DidOpenTextDocument>()
- .await
- .text_document,
- lsp::TextDocumentItem {
- uri: lsp::Uri::from_file_path(path!("/dir/file.rs")).unwrap(),
- version: 0,
- text: "".to_string(),
- language_id: "rust".to_string(),
- }
- );
-
- project.update(cx, |this, cx| {
- buffer.update(cx, |buffer, cx| {
- assert!(this.has_language_servers_for(buffer, cx));
- })
- });
+ .unwrap()
+ .into_iter()
+ .flat_map(|response| response.completions)
+ .collect::<Vec<_>>();
+ assert_eq!(completions.len(), 1);
+ assert_eq!(completions[0].new_text, "fully\nQualified\nName");
}
-#[gpui::test(iterations = 30)]
-async fn test_file_changes_multiple_times_on_disk(cx: &mut gpui::TestAppContext) {
+#[gpui::test]
+async fn test_supports_range_formatting_ignores_unrelated_language_servers(
+ cx: &mut gpui::TestAppContext,
+) {
init_test(cx);
+ cx.update(|cx| {
+ SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, |settings| {
+ settings.project.all_languages.defaults.formatter = Some(FormatterList::Single(
+ Formatter::LanguageServer(settings::LanguageServerFormatterSpecifier::Current),
+ ));
+ });
+ });
+ });
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
path!("/dir"),
json!({
- "file1": "the original contents",
+ "a.ts": "",
+ "b.rs": "",
}),
)
.await;
- let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
- let worktree = project.read_with(cx, |project, cx| project.worktrees(cx).next().unwrap());
- let buffer = project
- .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file1"), cx))
- .await
- .unwrap();
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(typescript_lang());
+ language_registry.add(rust_lang());
- // Change the buffer's file on disk, and then wait for the file change
- // to be detected by the worktree, so that the buffer starts reloading.
- fs.save(
- path!("/dir/file1").as_ref(),
- &"the first contents".into(),
- Default::default(),
- )
- .await
- .unwrap();
- worktree.next_event(cx).await;
-
- // Change the buffer's file again. Depending on the random seed, the
- // previous file change may still be in progress.
- fs.save(
- path!("/dir/file1").as_ref(),
- &"the second contents".into(),
- Default::default(),
- )
- .await
- .unwrap();
- worktree.next_event(cx).await;
-
- cx.executor().run_until_parked();
- let on_disk_text = fs.load(Path::new(path!("/dir/file1"))).await.unwrap();
- buffer.read_with(cx, |buffer, _| {
- assert_eq!(buffer.text(), on_disk_text);
- assert!(!buffer.is_dirty(), "buffer should not be dirty");
- assert!(!buffer.has_conflict(), "buffer should not be dirty");
- });
-}
-
-#[gpui::test(iterations = 30)]
-async fn test_edit_buffer_while_it_reloads(cx: &mut gpui::TestAppContext) {
- init_test(cx);
-
- let fs = FakeFs::new(cx.executor());
- fs.insert_tree(
- path!("/dir"),
- json!({
- "file1": "the original contents",
- }),
- )
- .await;
+ let mut typescript_language_servers = language_registry.register_fake_lsp(
+ "TypeScript",
+ FakeLspAdapter {
+ name: "typescript-fake-language-server",
+ capabilities: lsp::ServerCapabilities {
+ document_range_formatting_provider: Some(lsp::OneOf::Left(true)),
+ ..lsp::ServerCapabilities::default()
+ },
+ ..FakeLspAdapter::default()
+ },
+ );
+ let mut rust_language_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ name: "rust-fake-language-server",
+ capabilities: lsp::ServerCapabilities {
+ document_formatting_provider: Some(lsp::OneOf::Left(true)),
+ document_range_formatting_provider: Some(lsp::OneOf::Left(false)),
+ ..lsp::ServerCapabilities::default()
+ },
+ ..FakeLspAdapter::default()
+ },
+ );
- let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
- let worktree = project.read_with(cx, |project, cx| project.worktrees(cx).next().unwrap());
- let buffer = project
- .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file1"), cx))
+ let (typescript_buffer, _typescript_handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/a.ts"), cx)
+ })
.await
.unwrap();
-
- // Change the buffer's file on disk, and then wait for the file change
- // to be detected by the worktree, so that the buffer starts reloading.
- fs.save(
- path!("/dir/file1").as_ref(),
- &"the first contents".into(),
- Default::default(),
- )
- .await
- .unwrap();
- worktree.next_event(cx).await;
-
- cx.executor()
- .spawn(cx.executor().simulate_random_delay())
- .await;
-
- // Perform a noop edit, causing the buffer's version to increase.
- buffer.update(cx, |buffer, cx| {
- buffer.edit([(0..0, " ")], None, cx);
- buffer.undo(cx);
- });
-
- cx.executor().run_until_parked();
- let on_disk_text = fs.load(Path::new(path!("/dir/file1"))).await.unwrap();
- buffer.read_with(cx, |buffer, _| {
- let buffer_text = buffer.text();
- if buffer_text == on_disk_text {
- assert!(
- !buffer.is_dirty() && !buffer.has_conflict(),
- "buffer shouldn't be dirty. text: {buffer_text:?}, disk text: {on_disk_text:?}",
- );
- }
- // If the file change occurred while the buffer was processing the first
- // change, the buffer will be in a conflicting state.
- else {
- assert!(buffer.is_dirty(), "buffer should report that it is dirty. text: {buffer_text:?}, disk text: {on_disk_text:?}");
- assert!(buffer.has_conflict(), "buffer should report that it is dirty. text: {buffer_text:?}, disk text: {on_disk_text:?}");
- }
- });
-}
-
-#[gpui::test]
-async fn test_save_in_single_file_worktree(cx: &mut gpui::TestAppContext) {
- init_test(cx);
-
- let fs = FakeFs::new(cx.executor());
- fs.insert_tree(
- path!("/dir"),
- json!({
- "file1": "the old contents",
- }),
- )
- .await;
-
- let project = Project::test(fs.clone(), [path!("/dir/file1").as_ref()], cx).await;
- let buffer = project
- .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file1"), cx))
+ let (rust_buffer, _rust_handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/b.rs"), cx)
+ })
.await
.unwrap();
- buffer.update(cx, |buffer, cx| {
- buffer.edit([(0..0, "a line of text.\n".repeat(10 * 1024))], None, cx);
- });
- project
- .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
- .await
- .unwrap();
+ let _typescript_language_server = typescript_language_servers.next().await.unwrap();
+ let _rust_language_server = rust_language_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
- let new_text = fs
- .load(Path::new(path!("/dir/file1")))
- .await
- .unwrap()
- .replace("\r\n", "\n");
- assert_eq!(new_text, buffer.update(cx, |buffer, _| buffer.text()));
+ assert!(project.read_with(cx, |project, cx| {
+ project.supports_range_formatting(&typescript_buffer, cx)
+ }));
+ assert!(!project.read_with(cx, |project, cx| {
+ project.supports_range_formatting(&rust_buffer, cx)
+ }));
}
#[gpui::test]
-async fn test_save_as(cx: &mut gpui::TestAppContext) {
+async fn test_range_formatting_prefers_range_capable_current_server(cx: &mut gpui::TestAppContext) {
init_test(cx);
+ cx.update(|cx| {
+ SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, |settings| {
+ settings.project.all_languages.defaults.formatter = Some(FormatterList::Single(
+ Formatter::LanguageServer(settings::LanguageServerFormatterSpecifier::Current),
+ ));
+ });
+ });
+ });
let fs = FakeFs::new(cx.executor());
- fs.insert_tree("/dir", json!({})).await;
-
- let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
-
- let languages = project.update(cx, |project, _| project.languages().clone());
- languages.add(rust_lang());
+ fs.insert_tree(path!("/dir"), json!({ "a.rs": "let value = 1;" }))
+ .await;
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+ let mut full_format_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ name: "full-format-server",
+ capabilities: lsp::ServerCapabilities {
+ document_formatting_provider: Some(lsp::OneOf::Left(true)),
+ ..lsp::ServerCapabilities::default()
+ },
+ ..FakeLspAdapter::default()
+ },
+ );
+ let mut range_format_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ name: "range-format-server",
+ capabilities: lsp::ServerCapabilities {
+ document_range_formatting_provider: Some(lsp::OneOf::Left(true)),
+ ..lsp::ServerCapabilities::default()
+ },
+ ..FakeLspAdapter::default()
+ },
+ );
- let buffer = project.update(cx, |project, cx| {
- project.create_local_buffer("", None, false, cx)
- });
- buffer.update(cx, |buffer, cx| {
- buffer.edit([(0..0, "abc")], None, cx);
- assert!(buffer.is_dirty());
- assert!(!buffer.has_conflict());
- assert_eq!(buffer.language().unwrap().name(), "Plain Text");
- });
- project
+ let (buffer, _handle) = project
.update(cx, |project, cx| {
- let worktree_id = project.worktrees(cx).next().unwrap().read(cx).id();
- let path = ProjectPath {
- worktree_id,
- path: rel_path("file1.rs").into(),
- };
- project.save_buffer_as(buffer.clone(), path, cx)
+ project.open_local_buffer_with_lsp(path!("/dir/a.rs"), cx)
})
.await
.unwrap();
- assert_eq!(fs.load(Path::new("/dir/file1.rs")).await.unwrap(), "abc");
-
+ let full_format_server = full_format_servers.next().await.unwrap();
+ let range_format_server = range_format_servers.next().await.unwrap();
cx.executor().run_until_parked();
- buffer.update(cx, |buffer, cx| {
- assert_eq!(
- buffer.file().unwrap().full_path(cx),
- Path::new("dir/file1.rs")
- );
- assert!(!buffer.is_dirty());
- assert!(!buffer.has_conflict());
- assert_eq!(buffer.language().unwrap().name(), "Rust");
- });
- let opened_buffer = project
+ let full_format_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _full_format_requests = full_format_server
+ .set_request_handler::<lsp::request::Formatting, _, _>({
+ let full_format_request_count = full_format_request_count.clone();
+ move |_, _| {
+ full_format_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+ let range_format_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _range_format_requests = range_format_server
+ .set_request_handler::<lsp::request::RangeFormatting, _, _>({
+ let range_format_request_count = range_format_request_count.clone();
+ move |_, _| {
+ range_format_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+
+ let (buffer_id, range) = buffer.read_with(cx, |buffer, _| {
+ (
+ buffer.remote_id(),
+ buffer.anchor_before(0)..buffer.anchor_after(buffer.len()),
+ )
+ });
+ project
.update(cx, |project, cx| {
- project.open_local_buffer("/dir/file1.rs", cx)
+ project.format(
+ HashSet::from_iter([buffer]),
+ project::lsp_store::LspFormatTarget::Ranges(std::collections::BTreeMap::from_iter(
+ [(buffer_id, vec![range])],
+ )),
+ false,
+ project::lsp_store::FormatTrigger::Manual,
+ cx,
+ )
})
.await
.unwrap();
- assert_eq!(opened_buffer, buffer);
+
+ assert_eq!(
+ range_format_request_count.load(atomic::Ordering::SeqCst),
+ 1,
+ "expected the range-capable server to handle the range formatting request",
+ );
+ assert_eq!(
+ full_format_request_count.load(atomic::Ordering::SeqCst),
+ 0,
+ "expected manual range formatting not to use the full-format-only server",
+ );
}
-#[gpui::test]
-async fn test_save_as_existing_file(cx: &mut gpui::TestAppContext) {
+#[gpui::test(iterations = 10)]
+async fn test_apply_code_actions_with_commands(cx: &mut gpui::TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
- let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
-
fs.insert_tree(
path!("/dir"),
json!({
- "data_a.txt": "data about a"
+ "a.ts": "a",
}),
)
.await;
- let buffer = project
- .update(cx, |project, cx| {
- project.open_local_buffer(path!("/dir/data_a.txt"), cx)
- })
- .await
- .unwrap();
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
- buffer.update(cx, |buffer, cx| {
- buffer.edit([(11..12, "b")], None, cx);
- });
-
- // Save buffer's contents as a new file and confirm that the buffer's now
- // associated with `data_b.txt` instead of `data_a.txt`, confirming that the
- // file associated with the buffer has now been updated to `data_b.txt`
- project
- .update(cx, |project, cx| {
- let worktree_id = project.worktrees(cx).next().unwrap().read(cx).id();
- let new_path = ProjectPath {
- worktree_id,
- path: rel_path("data_b.txt").into(),
- };
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(typescript_lang());
+ let mut fake_language_servers = language_registry.register_fake_lsp(
+ "TypeScript",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities {
+ code_action_provider: Some(lsp::CodeActionProviderCapability::Options(
+ lsp::CodeActionOptions {
+ resolve_provider: Some(true),
+ ..lsp::CodeActionOptions::default()
+ },
+ )),
+ execute_command_provider: Some(lsp::ExecuteCommandOptions {
+ commands: vec!["_the/command".to_string()],
+ ..lsp::ExecuteCommandOptions::default()
+ }),
+ ..lsp::ServerCapabilities::default()
+ },
+ ..FakeLspAdapter::default()
+ },
+ );
- project.save_buffer_as(buffer.clone(), new_path, cx)
+ let (buffer, _handle) = project
+ .update(cx, |p, cx| {
+ p.open_local_buffer_with_lsp(path!("/dir/a.ts"), cx)
})
.await
.unwrap();
- buffer.update(cx, |buffer, cx| {
- assert_eq!(
- buffer.file().unwrap().full_path(cx),
- Path::new("dir/data_b.txt")
- )
- });
+ let fake_server = fake_language_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
- // Open the original `data_a.txt` file, confirming that its contents are
- // unchanged and the resulting buffer's associated file is `data_a.txt`.
- let original_buffer = project
- .update(cx, |project, cx| {
- project.open_local_buffer(path!("/dir/data_a.txt"), cx)
+ // Language server returns code actions that contain commands, and not edits.
+ let actions = project.update(cx, |project, cx| {
+ project.code_actions(&buffer, 0..0, None, cx)
+ });
+ fake_server
+ .set_request_handler::<lsp::request::CodeActionRequest, _, _>(|_, _| async move {
+ Ok(Some(vec![
+ lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
+ title: "The code action".into(),
+ data: Some(serde_json::json!({
+ "command": "_the/command",
+ })),
+ ..lsp::CodeAction::default()
+ }),
+ lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
+ title: "two".into(),
+ ..lsp::CodeAction::default()
+ }),
+ ]))
})
- .await
- .unwrap();
+ .next()
+ .await;
- original_buffer.update(cx, |buffer, cx| {
- assert_eq!(buffer.text(), "data about a");
- assert_eq!(
- buffer.file().unwrap().full_path(cx),
- Path::new("dir/data_a.txt")
- )
+ let action = actions.await.unwrap().unwrap()[0].clone();
+ let apply = project.update(cx, |project, cx| {
+ project.apply_code_action(buffer.clone(), action, true, cx)
});
-}
-
-#[gpui::test(retries = 5)]
-async fn test_rescan_and_remote_updates(cx: &mut gpui::TestAppContext) {
- use worktree::WorktreeModelHandle as _;
-
- init_test(cx);
- cx.executor().allow_parking();
- let dir = TempTree::new(json!({
- "a": {
- "file1": "",
- "file2": "",
- "file3": "",
- },
- "b": {
- "c": {
- "file4": "",
- "file5": "",
+ // Resolving the code action does not populate its edits. In absence of
+ // edits, we must execute the given command.
+ fake_server.set_request_handler::<lsp::request::CodeActionResolveRequest, _, _>(
+ |mut action, _| async move {
+ if action.data.is_some() {
+ action.command = Some(lsp::Command {
+ title: "The command".into(),
+ command: "_the/command".into(),
+ arguments: Some(vec![json!("the-argument")]),
+ });
}
- }
- }));
-
- let project = Project::test(Arc::new(RealFs::new(None, cx.executor())), [dir.path()], cx).await;
+ Ok(action)
+ },
+ );
- let buffer_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
- let buffer = project.update(cx, |p, cx| p.open_local_buffer(dir.path().join(path), cx));
- async move { buffer.await.unwrap() }
- };
- let id_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
- project.update(cx, |project, cx| {
- let tree = project.worktrees(cx).next().unwrap();
- tree.read(cx)
- .entry_for_path(rel_path(path))
- .unwrap_or_else(|| panic!("no entry for path {}", path))
- .id
+ // While executing the command, the language server sends the editor
+ // a `workspaceEdit` request.
+ fake_server
+ .set_request_handler::<lsp::request::ExecuteCommand, _, _>({
+ let fake = fake_server.clone();
+ move |params, _| {
+ assert_eq!(params.command, "_the/command");
+ let fake = fake.clone();
+ async move {
+ fake.server
+ .request::<lsp::request::ApplyWorkspaceEdit>(
+ lsp::ApplyWorkspaceEditParams {
+ label: None,
+ edit: lsp::WorkspaceEdit {
+ changes: Some(
+ [(
+ lsp::Uri::from_file_path(path!("/dir/a.ts")).unwrap(),
+ vec![lsp::TextEdit {
+ range: lsp::Range::new(
+ lsp::Position::new(0, 0),
+ lsp::Position::new(0, 0),
+ ),
+ new_text: "X".into(),
+ }],
+ )]
+ .into_iter()
+ .collect(),
+ ),
+ ..lsp::WorkspaceEdit::default()
+ },
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ Ok(Some(json!(null)))
+ }
+ }
})
- };
-
- let buffer2 = buffer_for_path("a/file2", cx).await;
- let buffer3 = buffer_for_path("a/file3", cx).await;
- let buffer4 = buffer_for_path("b/c/file4", cx).await;
- let buffer5 = buffer_for_path("b/c/file5", cx).await;
-
- let file2_id = id_for_path("a/file2", cx);
- let file3_id = id_for_path("a/file3", cx);
- let file4_id = id_for_path("b/c/file4", cx);
-
- // Create a remote copy of this worktree.
- let tree = project.update(cx, |project, cx| project.worktrees(cx).next().unwrap());
- let metadata = tree.update(cx, |tree, _| tree.metadata_proto());
+ .next()
+ .await;
- let updates = Arc::new(Mutex::new(Vec::new()));
- tree.update(cx, |tree, cx| {
- let updates = updates.clone();
- tree.observe_updates(0, cx, move |update| {
- updates.lock().push(update);
- async { true }
- });
+ // Applying the code action returns a project transaction containing the edits
+ // sent by the language server in its `workspaceEdit` request.
+ let transaction = apply.await.unwrap();
+ assert!(transaction.0.contains_key(&buffer));
+ buffer.update(cx, |buffer, cx| {
+ assert_eq!(buffer.text(), "Xa");
+ buffer.undo(cx);
+ assert_eq!(buffer.text(), "a");
});
+}
- let remote = cx.update(|cx| {
- Worktree::remote(
- 0,
- ReplicaId::REMOTE_SERVER,
- metadata,
- project.read(cx).client().into(),
- project.read(cx).path_style(cx),
- cx,
+#[gpui::test]
+async fn test_rename_file_to_new_directory(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+ let fs = FakeFs::new(cx.background_executor.clone());
+ let expected_contents = "content";
+ fs.as_fake()
+ .insert_tree(
+ "/root",
+ json!({
+ "test.txt": expected_contents
+ }),
)
- });
-
- cx.executor().run_until_parked();
-
- cx.update(|cx| {
- assert!(!buffer2.read(cx).is_dirty());
- assert!(!buffer3.read(cx).is_dirty());
- assert!(!buffer4.read(cx).is_dirty());
- assert!(!buffer5.read(cx).is_dirty());
- });
+ .await;
- // Rename and delete files and directories.
- tree.flush_fs_events(cx).await;
- std::fs::rename(dir.path().join("a/file3"), dir.path().join("b/c/file3")).unwrap();
- std::fs::remove_file(dir.path().join("b/c/file5")).unwrap();
- std::fs::rename(dir.path().join("b/c"), dir.path().join("d")).unwrap();
- std::fs::rename(dir.path().join("a/file2"), dir.path().join("a/file2.new")).unwrap();
- tree.flush_fs_events(cx).await;
+ let project = Project::test(fs, [path!("/root").as_ref()], cx).await;
- cx.update(|app| {
- assert_eq!(
- tree.read(app).paths().collect::<Vec<_>>(),
- vec![
- rel_path("a"),
- rel_path("a/file1"),
- rel_path("a/file2.new"),
- rel_path("b"),
- rel_path("d"),
- rel_path("d/file3"),
- rel_path("d/file4"),
- ]
- );
+ let (worktree, entry_id) = project.read_with(cx, |project, cx| {
+ let worktree = project.worktrees(cx).next().unwrap();
+ let entry_id = worktree
+ .read(cx)
+ .entry_for_path(rel_path("test.txt"))
+ .unwrap()
+ .id;
+ (worktree, entry_id)
});
-
- assert_eq!(id_for_path("a/file2.new", cx), file2_id);
- assert_eq!(id_for_path("d/file3", cx), file3_id);
- assert_eq!(id_for_path("d/file4", cx), file4_id);
-
- cx.update(|cx| {
- assert_eq!(
- buffer2.read(cx).file().unwrap().path().as_ref(),
- rel_path("a/file2.new")
- );
- assert_eq!(
- buffer3.read(cx).file().unwrap().path().as_ref(),
- rel_path("d/file3")
- );
- assert_eq!(
- buffer4.read(cx).file().unwrap().path().as_ref(),
- rel_path("d/file4")
- );
- assert_eq!(
- buffer5.read(cx).file().unwrap().path().as_ref(),
- rel_path("b/c/file5")
- );
-
- assert_matches!(
- buffer2.read(cx).file().unwrap().disk_state(),
- DiskState::Present { .. }
- );
- assert_matches!(
- buffer3.read(cx).file().unwrap().disk_state(),
- DiskState::Present { .. }
- );
- assert_matches!(
- buffer4.read(cx).file().unwrap().disk_state(),
- DiskState::Present { .. }
- );
- assert_eq!(
- buffer5.read(cx).file().unwrap().disk_state(),
- DiskState::Deleted
+ let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
+ let _result = project
+ .update(cx, |project, cx| {
+ project.rename_entry(
+ entry_id,
+ (worktree_id, rel_path("dir1/dir2/dir3/test.txt")).into(),
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+ worktree.read_with(cx, |worktree, _| {
+ assert!(
+ worktree.entry_for_path(rel_path("test.txt")).is_none(),
+ "Old file should have been removed"
);
- });
-
- // Update the remote worktree. Check that it becomes consistent with the
- // local worktree.
- cx.executor().run_until_parked();
-
- remote.update(cx, |remote, _| {
- for update in updates.lock().drain(..) {
- remote.as_remote_mut().unwrap().update_from_remote(update);
- }
- });
- cx.executor().run_until_parked();
- remote.update(cx, |remote, _| {
- assert_eq!(
- remote.paths().collect::<Vec<_>>(),
- vec![
- rel_path("a"),
- rel_path("a/file1"),
- rel_path("a/file2.new"),
- rel_path("b"),
- rel_path("d"),
- rel_path("d/file3"),
- rel_path("d/file4"),
- ]
+ assert!(
+ worktree
+ .entry_for_path(rel_path("dir1/dir2/dir3/test.txt"))
+ .is_some(),
+ "Whole directory hierarchy and the new file should have been created"
);
});
-}
-
-#[cfg(target_os = "linux")]
-#[gpui::test(retries = 5)]
-async fn test_recreated_directory_receives_child_events(cx: &mut gpui::TestAppContext) {
- init_test(cx);
- cx.executor().allow_parking();
-
- let dir = TempTree::new(json!({}));
- let project = Project::test(Arc::new(RealFs::new(None, cx.executor())), [dir.path()], cx).await;
- let tree = project.update(cx, |project, cx| project.worktrees(cx).next().unwrap());
-
- tree.flush_fs_events(cx).await;
-
- let repro_dir = dir.path().join("repro");
- std::fs::create_dir(&repro_dir).unwrap();
- tree.flush_fs_events(cx).await;
-
- cx.update(|cx| {
- assert!(tree.read(cx).entry_for_path(rel_path("repro")).is_some());
- });
-
- std::fs::remove_dir_all(&repro_dir).unwrap();
- tree.flush_fs_events(cx).await;
-
- cx.update(|cx| {
- assert!(tree.read(cx).entry_for_path(rel_path("repro")).is_none());
- });
-
- std::fs::create_dir(&repro_dir).unwrap();
- tree.flush_fs_events(cx).await;
+ assert_eq!(
+ worktree
+ .update(cx, |worktree, cx| {
+ worktree.load_file(rel_path("dir1/dir2/dir3/test.txt"), cx)
+ })
+ .await
+ .unwrap()
+ .text
+ .to_string(),
+ expected_contents,
+ "Moved file's contents should be preserved"
+ );
- cx.update(|cx| {
- assert!(tree.read(cx).entry_for_path(rel_path("repro")).is_some());
+ let entry_id = worktree.read_with(cx, |worktree, _| {
+ worktree
+ .entry_for_path(rel_path("dir1/dir2/dir3/test.txt"))
+ .unwrap()
+ .id
});
- std::fs::write(repro_dir.join("repro-marker"), "").unwrap();
- tree.flush_fs_events(cx).await;
-
- cx.update(|cx| {
+ let _result = project
+ .update(cx, |project, cx| {
+ project.rename_entry(
+ entry_id,
+ (worktree_id, rel_path("dir1/dir2/test.txt")).into(),
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+ worktree.read_with(cx, |worktree, _| {
assert!(
- tree.read(cx)
- .entry_for_path(rel_path("repro/repro-marker"))
- .is_some()
+ worktree.entry_for_path(rel_path("test.txt")).is_none(),
+ "First file should not reappear"
+ );
+ assert!(
+ worktree
+ .entry_for_path(rel_path("dir1/dir2/dir3/test.txt"))
+ .is_none(),
+ "Old file should have been removed"
+ );
+ assert!(
+ worktree
+ .entry_for_path(rel_path("dir1/dir2/test.txt"))
+ .is_some(),
+ "No error should have occurred after moving into existing directory"
);
});
+ assert_eq!(
+ worktree
+ .update(cx, |worktree, cx| {
+ worktree.load_file(rel_path("dir1/dir2/test.txt"), cx)
+ })
+ .await
+ .unwrap()
+ .text
+ .to_string(),
+ expected_contents,
+ "Moved file's contents should be preserved"
+ );
}
#[gpui::test(iterations = 10)]
-async fn test_buffer_identity_across_renames(cx: &mut gpui::TestAppContext) {
+async fn test_save_file(cx: &mut gpui::TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
path!("/dir"),
json!({
- "a": {
- "file1": "",
- }
+ "file1": "the old contents",
}),
)
.await;
- let project = Project::test(fs, [Path::new(path!("/dir"))], cx).await;
- let tree = project.update(cx, |project, cx| project.worktrees(cx).next().unwrap());
- let tree_id = tree.update(cx, |tree, _| tree.id());
-
- let id_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
- project.update(cx, |project, cx| {
- let tree = project.worktrees(cx).next().unwrap();
- tree.read(cx)
- .entry_for_path(rel_path(path))
- .unwrap_or_else(|| panic!("no entry for path {}", path))
- .id
- })
- };
-
- let dir_id = id_for_path("a", cx);
- let file_id = id_for_path("a/file1", cx);
+ let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
let buffer = project
- .update(cx, |p, cx| {
- p.open_buffer((tree_id, rel_path("a/file1")), cx)
- })
+ .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file1"), cx))
.await
.unwrap();
- buffer.update(cx, |buffer, _| assert!(!buffer.is_dirty()));
+ buffer.update(cx, |buffer, cx| {
+ assert_eq!(buffer.text(), "the old contents");
+ buffer.edit([(0..0, "a line of text.\n".repeat(10 * 1024))], None, cx);
+ });
project
- .update(cx, |project, cx| {
- project.rename_entry(dir_id, (tree_id, rel_path("b")).into(), cx)
- })
- .unwrap()
+ .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
.await
- .into_included()
.unwrap();
- cx.executor().run_until_parked();
- assert_eq!(id_for_path("b", cx), dir_id);
- assert_eq!(id_for_path("b/file1", cx), file_id);
- buffer.update(cx, |buffer, _| assert!(!buffer.is_dirty()));
+ let new_text = fs
+ .load(Path::new(path!("/dir/file1")))
+ .await
+ .unwrap()
+ .replace("\r\n", "\n");
+ assert_eq!(new_text, buffer.update(cx, |buffer, _| buffer.text()));
}
-#[gpui::test]
-async fn test_buffer_deduping(cx: &mut gpui::TestAppContext) {
+#[gpui::test(iterations = 10)]
+async fn test_save_file_spawns_language_server(cx: &mut gpui::TestAppContext) {
+ // Issue: #24349
init_test(cx);
let fs = FakeFs::new(cx.executor());
- fs.insert_tree(
- "/dir",
- json!({
- "a.txt": "a-contents",
- "b.txt": "b-contents",
- }),
- )
- .await;
-
- let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
-
- // Spawn multiple tasks to open paths, repeating some paths.
- let (buffer_a_1, buffer_b, buffer_a_2) = project.update(cx, |p, cx| {
- (
- p.open_local_buffer("/dir/a.txt", cx),
- p.open_local_buffer("/dir/b.txt", cx),
- p.open_local_buffer("/dir/a.txt", cx),
- )
- });
+ fs.insert_tree(path!("/dir"), json!({})).await;
- let buffer_a_1 = buffer_a_1.await.unwrap();
- let buffer_a_2 = buffer_a_2.await.unwrap();
- let buffer_b = buffer_b.await.unwrap();
- assert_eq!(buffer_a_1.update(cx, |b, _| b.text()), "a-contents");
- assert_eq!(buffer_b.update(cx, |b, _| b.text()), "b-contents");
+ let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
- // There is only one buffer per path.
- let buffer_a_id = buffer_a_1.entity_id();
- assert_eq!(buffer_a_2.entity_id(), buffer_a_id);
+ language_registry.add(rust_lang());
+ let mut fake_rust_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ name: "the-rust-language-server",
+ capabilities: lsp::ServerCapabilities {
+ completion_provider: Some(lsp::CompletionOptions {
+ trigger_characters: Some(vec![".".to_string(), "::".to_string()]),
+ ..lsp::CompletionOptions::default()
+ }),
+ text_document_sync: Some(lsp::TextDocumentSyncCapability::Options(
+ lsp::TextDocumentSyncOptions {
+ save: Some(lsp::TextDocumentSyncSaveOptions::Supported(true)),
+ ..lsp::TextDocumentSyncOptions::default()
+ },
+ )),
+ ..lsp::ServerCapabilities::default()
+ },
+ ..FakeLspAdapter::default()
+ },
+ );
- // Open the same path again while it is still open.
- drop(buffer_a_1);
- let buffer_a_3 = project
- .update(cx, |p, cx| p.open_local_buffer("/dir/a.txt", cx))
+ let buffer = project
+ .update(cx, |this, cx| this.create_buffer(None, false, cx))
+ .unwrap()
+ .await;
+ project.update(cx, |this, cx| {
+ this.register_buffer_with_language_servers(&buffer, cx);
+ buffer.update(cx, |buffer, cx| {
+ assert!(!this.has_language_servers_for(buffer, cx));
+ })
+ });
+
+ project
+ .update(cx, |this, cx| {
+ let worktree_id = this.worktrees(cx).next().unwrap().read(cx).id();
+ this.save_buffer_as(
+ buffer.clone(),
+ ProjectPath {
+ worktree_id,
+ path: rel_path("file.rs").into(),
+ },
+ cx,
+ )
+ })
.await
.unwrap();
+ // A server is started up, and it is notified about Rust files.
+ let mut fake_rust_server = fake_rust_servers.next().await.unwrap();
+ assert_eq!(
+ fake_rust_server
+ .receive_notification::<lsp::notification::DidOpenTextDocument>()
+ .await
+ .text_document,
+ lsp::TextDocumentItem {
+ uri: lsp::Uri::from_file_path(path!("/dir/file.rs")).unwrap(),
+ version: 0,
+ text: "".to_string(),
+ language_id: "rust".to_string(),
+ }
+ );
- // There's still only one buffer per path.
- assert_eq!(buffer_a_3.entity_id(), buffer_a_id);
+ project.update(cx, |this, cx| {
+ buffer.update(cx, |buffer, cx| {
+ assert!(this.has_language_servers_for(buffer, cx));
+ })
+ });
}
-#[gpui::test]
-async fn test_buffer_is_dirty(cx: &mut gpui::TestAppContext) {
+#[gpui::test(iterations = 30)]
+async fn test_file_changes_multiple_times_on_disk(cx: &mut gpui::TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
path!("/dir"),
json!({
- "file1": "abc",
- "file2": "def",
- "file3": "ghi",
+ "file1": "the original contents",
}),
)
.await;
let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
-
- let buffer1 = project
+ let worktree = project.read_with(cx, |project, cx| project.worktrees(cx).next().unwrap());
+ let buffer = project
.update(cx, |p, cx| p.open_local_buffer(path!("/dir/file1"), cx))
.await
.unwrap();
- let events = Arc::new(Mutex::new(Vec::new()));
-
- // initially, the buffer isn't dirty.
- buffer1.update(cx, |buffer, cx| {
- cx.subscribe(&buffer1, {
- let events = events.clone();
- move |_, _, event, _| match event {
- BufferEvent::Operation { .. } => {}
- _ => events.lock().push(event.clone()),
- }
- })
- .detach();
- assert!(!buffer.is_dirty());
- assert!(events.lock().is_empty());
+ // Change the buffer's file on disk, and then wait for the file change
+ // to be detected by the worktree, so that the buffer starts reloading.
+ fs.save(
+ path!("/dir/file1").as_ref(),
+ &"the first contents".into(),
+ LineEnding::default(),
+ )
+ .await
+ .unwrap();
+ worktree.next_event(cx).await;
- buffer.edit([(1..2, "")], None, cx);
- });
+ // Change the buffer's file again. Depending on the random seed, the
+ // previous file change may still be in progress.
+ fs.save(
+ path!("/dir/file1").as_ref(),
+ &"the second contents".into(),
+ LineEnding::default(),
+ )
+ .await
+ .unwrap();
+ worktree.next_event(cx).await;
- // after the first edit, the buffer is dirty, and emits a dirtied event.
- buffer1.update(cx, |buffer, cx| {
- assert!(buffer.text() == "ac");
- assert!(buffer.is_dirty());
- assert_eq!(
- *events.lock(),
- &[
- language::BufferEvent::Edited {
- source: language::BufferEditSource::User
- },
- language::BufferEvent::DirtyChanged
- ]
- );
- events.lock().clear();
- buffer.did_save(
- buffer.version(),
- buffer.file().unwrap().disk_state().mtime(),
- cx,
- );
+ cx.executor().run_until_parked();
+ let on_disk_text = fs.load(Path::new(path!("/dir/file1"))).await.unwrap();
+ buffer.read_with(cx, |buffer, _| {
+ assert_eq!(buffer.text(), on_disk_text);
+ assert!(!buffer.is_dirty(), "buffer should not be dirty");
+ assert!(!buffer.has_conflict(), "buffer should not be dirty");
});
+}
- // after saving, the buffer is not dirty, and emits a saved event.
- buffer1.update(cx, |buffer, cx| {
- assert!(!buffer.is_dirty());
- assert_eq!(*events.lock(), &[language::BufferEvent::Saved]);
- events.lock().clear();
+#[gpui::test(iterations = 30)]
+async fn test_edit_buffer_while_it_reloads(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
- buffer.edit([(1..1, "B")], None, cx);
- buffer.edit([(2..2, "D")], None, cx);
- });
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/dir"),
+ json!({
+ "file1": "the original contents",
+ }),
+ )
+ .await;
- // after editing again, the buffer is dirty, and emits another dirty event.
- buffer1.update(cx, |buffer, cx| {
- assert!(buffer.text() == "aBDc");
- assert!(buffer.is_dirty());
- assert_eq!(
- *events.lock(),
- &[
- language::BufferEvent::Edited {
- source: language::BufferEditSource::User
- },
- language::BufferEvent::DirtyChanged,
- language::BufferEvent::Edited {
- source: language::BufferEditSource::User
- },
- ],
- );
- events.lock().clear();
+ let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
+ let worktree = project.read_with(cx, |project, cx| project.worktrees(cx).next().unwrap());
+ let buffer = project
+ .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file1"), cx))
+ .await
+ .unwrap();
- // After restoring the buffer to its previously-saved state,
- // the buffer is not considered dirty anymore.
- buffer.edit([(1..3, "")], None, cx);
- assert!(buffer.text() == "ac");
- assert!(!buffer.is_dirty());
- });
+ // Change the buffer's file on disk, and then wait for the file change
+ // to be detected by the worktree, so that the buffer starts reloading.
+ fs.save(
+ path!("/dir/file1").as_ref(),
+ &"the first contents".into(),
+ LineEnding::default(),
+ )
+ .await
+ .unwrap();
+ worktree.next_event(cx).await;
- assert_eq!(
- *events.lock(),
- &[
- language::BufferEvent::Edited {
- source: language::BufferEditSource::User
- },
- language::BufferEvent::DirtyChanged
- ]
- );
+ cx.executor()
+ .spawn(cx.executor().simulate_random_delay())
+ .await;
- // When a file is deleted, it is not considered dirty.
- let events = Arc::new(Mutex::new(Vec::new()));
- let buffer2 = project
- .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file2"), cx))
- .await
- .unwrap();
- buffer2.update(cx, |_, cx| {
- cx.subscribe(&buffer2, {
- let events = events.clone();
- move |_, _, event, _| match event {
- BufferEvent::Operation { .. } => {}
- _ => events.lock().push(event.clone()),
- }
- })
- .detach();
+ // Perform a noop edit, causing the buffer's version to increase.
+ buffer.update(cx, |buffer, cx| {
+ buffer.edit([(0..0, " ")], None, cx);
+ buffer.undo(cx);
});
- fs.remove_file(path!("/dir/file2").as_ref(), Default::default())
- .await
- .unwrap();
cx.executor().run_until_parked();
- buffer2.update(cx, |buffer, _| assert!(!buffer.is_dirty()));
- assert_eq!(
- mem::take(&mut *events.lock()),
- &[language::BufferEvent::FileHandleChanged]
- );
-
- // Buffer becomes dirty when edited.
- buffer2.update(cx, |buffer, cx| {
- buffer.edit([(2..3, "")], None, cx);
- assert_eq!(buffer.is_dirty(), true);
- });
- assert_eq!(
- mem::take(&mut *events.lock()),
- &[
- language::BufferEvent::Edited {
- source: language::BufferEditSource::User
- },
- language::BufferEvent::DirtyChanged
- ]
- );
-
- // Buffer becomes clean again when all of its content is removed, because
- // the file was deleted.
- buffer2.update(cx, |buffer, cx| {
- buffer.edit([(0..2, "")], None, cx);
- assert_eq!(buffer.is_empty(), true);
- assert_eq!(buffer.is_dirty(), false);
- });
- assert_eq!(
- *events.lock(),
- &[
- language::BufferEvent::Edited {
- source: language::BufferEditSource::User
- },
- language::BufferEvent::DirtyChanged
- ]
- );
-
- // When a file is already dirty when deleted, we don't emit a Dirtied event.
- let events = Arc::new(Mutex::new(Vec::new()));
- let buffer3 = project
- .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file3"), cx))
- .await
- .unwrap();
- buffer3.update(cx, |_, cx| {
- cx.subscribe(&buffer3, {
- let events = events.clone();
- move |_, _, event, _| match event {
- BufferEvent::Operation { .. } => {}
- _ => events.lock().push(event.clone()),
- }
- })
- .detach();
- });
-
- buffer3.update(cx, |buffer, cx| {
- buffer.edit([(0..0, "x")], None, cx);
- });
- events.lock().clear();
- fs.remove_file(path!("/dir/file3").as_ref(), Default::default())
- .await
- .unwrap();
- cx.executor().run_until_parked();
- assert_eq!(*events.lock(), &[language::BufferEvent::FileHandleChanged]);
- cx.update(|cx| assert!(buffer3.read(cx).is_dirty()));
-}
+ let on_disk_text = fs.load(Path::new(path!("/dir/file1"))).await.unwrap();
+ buffer.read_with(cx, |buffer, _| {
+ let buffer_text = buffer.text();
+ if buffer_text == on_disk_text {
+ assert!(
+ !buffer.is_dirty() && !buffer.has_conflict(),
+ "buffer shouldn't be dirty. text: {buffer_text:?}, disk text: {on_disk_text:?}",
+ );
+ }
+ // If the file change occurred while the buffer was processing the first
+ // change, the buffer will be in a conflicting state.
+ else {
+ assert!(buffer.is_dirty(), "buffer should report that it is dirty. text: {buffer_text:?}, disk text: {on_disk_text:?}");
+ assert!(buffer.has_conflict(), "buffer should report that it is dirty. text: {buffer_text:?}, disk text: {on_disk_text:?}");
+ }
+ });
+}
#[gpui::test]
-async fn test_dirty_buffer_reloads_after_undo(cx: &mut gpui::TestAppContext) {
+async fn test_save_in_single_file_worktree(cx: &mut gpui::TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
path!("/dir"),
json!({
- "file.txt": "version 1",
+ "file1": "the old contents",
}),
)
.await;
- let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
+ let project = Project::test(fs.clone(), [path!("/dir/file1").as_ref()], cx).await;
let buffer = project
- .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file.txt"), cx))
+ .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file1"), cx))
.await
.unwrap();
-
- buffer.read_with(cx, |buffer, _| {
- assert_eq!(buffer.text(), "version 1");
- assert!(!buffer.is_dirty());
- });
-
- // User makes an edit, making the buffer dirty.
buffer.update(cx, |buffer, cx| {
- buffer.edit([(0..0, "user edit: ")], None, cx);
+ buffer.edit([(0..0, "a line of text.\n".repeat(10 * 1024))], None, cx);
});
- buffer.read_with(cx, |buffer, _| {
- assert!(buffer.is_dirty());
- assert_eq!(buffer.text(), "user edit: version 1");
- });
+ project
+ .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
+ .await
+ .unwrap();
- // External tool writes new content while buffer is dirty.
- // file_updated() updates the File but suppresses ReloadNeeded.
- fs.save(
- path!("/dir/file.txt").as_ref(),
- &"version 2 from external tool".into(),
- Default::default(),
- )
- .await
- .unwrap();
- cx.executor().run_until_parked();
+ let new_text = fs
+ .load(Path::new(path!("/dir/file1")))
+ .await
+ .unwrap()
+ .replace("\r\n", "\n");
+ assert_eq!(new_text, buffer.update(cx, |buffer, _| buffer.text()));
+}
- buffer.read_with(cx, |buffer, _| {
- assert!(buffer.has_conflict());
- assert_eq!(buffer.text(), "user edit: version 1");
- });
+#[gpui::test]
+async fn test_save_as(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
- // User undoes their edit. Buffer becomes clean, but disk has different
- // content. did_edit() detects the dirty->clean transition and checks if
- // disk changed while dirty. Since mtime differs from saved_mtime, it
- // emits ReloadNeeded.
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree("/dir", json!({})).await;
+
+ let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
+
+ let languages = project.update(cx, |project, _| project.languages().clone());
+ languages.add(rust_lang());
+
+ let buffer = project.update(cx, |project, cx| {
+ project.create_local_buffer("", None, false, cx)
+ });
buffer.update(cx, |buffer, cx| {
- buffer.undo(cx);
+ buffer.edit([(0..0, "abc")], None, cx);
+ assert!(buffer.is_dirty());
+ assert!(!buffer.has_conflict());
+ assert_eq!(buffer.language().unwrap().name(), "Plain Text");
});
- cx.executor().run_until_parked();
+ project
+ .update(cx, |project, cx| {
+ let worktree_id = project.worktrees(cx).next().unwrap().read(cx).id();
+ let path = ProjectPath {
+ worktree_id,
+ path: rel_path("file1.rs").into(),
+ };
+ project.save_buffer_as(buffer.clone(), path, cx)
+ })
+ .await
+ .unwrap();
+ assert_eq!(fs.load(Path::new("/dir/file1.rs")).await.unwrap(), "abc");
- buffer.read_with(cx, |buffer, _| {
+ cx.executor().run_until_parked();
+ buffer.update(cx, |buffer, cx| {
assert_eq!(
- buffer.text(),
- "version 2 from external tool",
- "buffer should reload from disk after undo makes it clean"
+ buffer.file().unwrap().full_path(cx),
+ Path::new("dir/file1.rs")
);
assert!(!buffer.is_dirty());
+ assert!(!buffer.has_conflict());
+ assert_eq!(buffer.language().unwrap().name(), "Rust");
});
+
+ let opened_buffer = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer("/dir/file1.rs", cx)
+ })
+ .await
+ .unwrap();
+ assert_eq!(opened_buffer, buffer);
}
#[gpui::test]
-async fn test_buffer_file_change_to_binary_fails(cx: &mut gpui::TestAppContext) {
+async fn test_save_as_existing_file(cx: &mut gpui::TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
+ let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
+
fs.insert_tree(
path!("/dir"),
json!({
- "file.txt": "",
+ "data_a.txt": "data about a"
}),
)
.await;
- let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
let buffer = project
- .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file.txt"), cx))
+ .update(cx, |project, cx| {
+ project.open_local_buffer(path!("/dir/data_a.txt"), cx)
+ })
.await
.unwrap();
- fs.write(
- path!("/dir/file.txt").as_ref(),
- b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01",
- )
- .await
- .unwrap();
- cx.executor().run_until_parked();
-
- // Test that existing buffer is left untouched
- buffer.read_with(cx, |buffer, _| {
- assert_eq!(buffer.text(), "");
+ buffer.update(cx, |buffer, cx| {
+ buffer.edit([(11..12, "b")], None, cx);
});
-}
-#[gpui::test]
-async fn test_buffer_file_changes_on_disk(cx: &mut gpui::TestAppContext) {
- init_test(cx);
+ // Save buffer's contents as a new file and confirm that the buffer's now
+ // associated with `data_b.txt` instead of `data_a.txt`, confirming that the
+ // file associated with the buffer has now been updated to `data_b.txt`
+ project
+ .update(cx, |project, cx| {
+ let worktree_id = project.worktrees(cx).next().unwrap().read(cx).id();
+ let new_path = ProjectPath {
+ worktree_id,
+ path: rel_path("data_b.txt").into(),
+ };
- let (initial_contents, initial_offsets) =
- marked_text_offsets("one twoˇ\nthree ˇfourˇ five\nsixˇ seven\n");
- let fs = FakeFs::new(cx.executor());
- fs.insert_tree(
- path!("/dir"),
- json!({
- "the-file": initial_contents,
- }),
- )
- .await;
- let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
- let buffer = project
- .update(cx, |p, cx| p.open_local_buffer(path!("/dir/the-file"), cx))
+ project.save_buffer_as(buffer.clone(), new_path, cx)
+ })
.await
.unwrap();
- let anchors = initial_offsets
- .iter()
- .map(|offset| buffer.update(cx, |b, _| b.anchor_before(offset)))
- .collect::<Vec<_>>();
+ buffer.update(cx, |buffer, cx| {
+ assert_eq!(
+ buffer.file().unwrap().full_path(cx),
+ Path::new("dir/data_b.txt")
+ )
+ });
- // Change the file on disk, adding two new lines of text, and removing
- // one line.
- buffer.update(cx, |buffer, _| {
- assert!(!buffer.is_dirty());
- assert!(!buffer.has_conflict());
+ // Open the original `data_a.txt` file, confirming that its contents are
+ // unchanged and the resulting buffer's associated file is `data_a.txt`.
+ let original_buffer = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer(path!("/dir/data_a.txt"), cx)
+ })
+ .await
+ .unwrap();
+
+ original_buffer.update(cx, |buffer, cx| {
+ assert_eq!(buffer.text(), "data about a");
+ assert_eq!(
+ buffer.file().unwrap().full_path(cx),
+ Path::new("dir/data_a.txt")
+ )
});
+}
- let (new_contents, new_offsets) =
- marked_text_offsets("oneˇ\nthree ˇFOURˇ five\nsixtyˇ seven\n");
- fs.save(
- path!("/dir/the-file").as_ref(),
- &new_contents.as_str().into(),
- LineEnding::Unix,
- )
- .await
- .unwrap();
+#[gpui::test(retries = 5)]
+async fn test_rescan_and_remote_updates(cx: &mut gpui::TestAppContext) {
+ use worktree::WorktreeModelHandle as _;
+
+ init_test(cx);
+ cx.executor().allow_parking();
+
+ let dir = TempTree::new(json!({
+ "a": {
+ "file1": "",
+ "file2": "",
+ "file3": "",
+ },
+ "b": {
+ "c": {
+ "file4": "",
+ "file5": "",
+ }
+ }
+ }));
+
+ let project = Project::test(Arc::new(RealFs::new(None, cx.executor())), [dir.path()], cx).await;
+
+ let buffer_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
+ let buffer = project.update(cx, |p, cx| p.open_local_buffer(dir.path().join(path), cx));
+ async move { buffer.await.unwrap() }
+ };
+ let id_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
+ project.update(cx, |project, cx| {
+ let tree = project.worktrees(cx).next().unwrap();
+ tree.read(cx)
+ .entry_for_path(rel_path(path))
+ .unwrap_or_else(|| panic!("no entry for path {}", path))
+ .id
+ })
+ };
+
+ let buffer2 = buffer_for_path("a/file2", cx).await;
+ let buffer3 = buffer_for_path("a/file3", cx).await;
+ let buffer4 = buffer_for_path("b/c/file4", cx).await;
+ let buffer5 = buffer_for_path("b/c/file5", cx).await;
+
+ let file2_id = id_for_path("a/file2", cx);
+ let file3_id = id_for_path("a/file3", cx);
+ let file4_id = id_for_path("b/c/file4", cx);
+
+ // Create a remote copy of this worktree.
+ let tree = project.update(cx, |project, cx| project.worktrees(cx).next().unwrap());
+ let metadata = tree.update(cx, |tree, _| tree.metadata_proto());
+
+ let updates = Arc::new(Mutex::new(Vec::new()));
+ tree.update(cx, |tree, cx| {
+ let updates = updates.clone();
+ tree.observe_updates(0, cx, move |update| {
+ updates.lock().push(update);
+ async { true }
+ });
+ });
+
+ let remote = cx.update(|cx| {
+ Worktree::remote(
+ 0,
+ ReplicaId::REMOTE_SERVER,
+ metadata,
+ project.read(cx).client().into(),
+ project.read(cx).path_style(cx),
+ cx,
+ )
+ });
- // Because the buffer was not modified, it is reloaded from disk. Its
- // contents are edited according to the diff between the old and new
- // file contents.
cx.executor().run_until_parked();
- buffer.update(cx, |buffer, _| {
- assert_eq!(buffer.text(), new_contents);
- assert!(!buffer.is_dirty());
- assert!(!buffer.has_conflict());
- let anchor_offsets = anchors
- .iter()
- .map(|anchor| anchor.to_offset(&*buffer))
- .collect::<Vec<_>>();
- assert_eq!(anchor_offsets, new_offsets);
+ cx.update(|cx| {
+ assert!(!buffer2.read(cx).is_dirty());
+ assert!(!buffer3.read(cx).is_dirty());
+ assert!(!buffer4.read(cx).is_dirty());
+ assert!(!buffer5.read(cx).is_dirty());
});
- // Modify the buffer
- buffer.update(cx, |buffer, cx| {
- buffer.edit([(0..0, " ")], None, cx);
- assert!(buffer.is_dirty());
- assert!(!buffer.has_conflict());
+ // Rename and delete files and directories.
+ tree.flush_fs_events(cx).await;
+ std::fs::rename(dir.path().join("a/file3"), dir.path().join("b/c/file3")).unwrap();
+ std::fs::remove_file(dir.path().join("b/c/file5")).unwrap();
+ std::fs::rename(dir.path().join("b/c"), dir.path().join("d")).unwrap();
+ std::fs::rename(dir.path().join("a/file2"), dir.path().join("a/file2.new")).unwrap();
+ tree.flush_fs_events(cx).await;
+
+ cx.update(|app| {
+ assert_eq!(
+ tree.read(app).paths().collect::<Vec<_>>(),
+ vec![
+ rel_path("a"),
+ rel_path("a/file1"),
+ rel_path("a/file2.new"),
+ rel_path("b"),
+ rel_path("d"),
+ rel_path("d/file3"),
+ rel_path("d/file4"),
+ ]
+ );
});
- // Change the file on disk again, adding blank lines to the beginning.
- fs.save(
- path!("/dir/the-file").as_ref(),
- &"\n\n\nAAAA\naaa\nBB\nbbbbb\n".into(),
- LineEnding::Unix,
- )
- .await
- .unwrap();
+ assert_eq!(id_for_path("a/file2.new", cx), file2_id);
+ assert_eq!(id_for_path("d/file3", cx), file3_id);
+ assert_eq!(id_for_path("d/file4", cx), file4_id);
- // Because the buffer is modified, it doesn't reload from disk, but is
- // marked as having a conflict.
+ cx.update(|cx| {
+ assert_eq!(
+ buffer2.read(cx).file().unwrap().path().as_ref(),
+ rel_path("a/file2.new")
+ );
+ assert_eq!(
+ buffer3.read(cx).file().unwrap().path().as_ref(),
+ rel_path("d/file3")
+ );
+ assert_eq!(
+ buffer4.read(cx).file().unwrap().path().as_ref(),
+ rel_path("d/file4")
+ );
+ assert_eq!(
+ buffer5.read(cx).file().unwrap().path().as_ref(),
+ rel_path("b/c/file5")
+ );
+
+ assert_matches!(
+ buffer2.read(cx).file().unwrap().disk_state(),
+ DiskState::Present { .. }
+ );
+ assert_matches!(
+ buffer3.read(cx).file().unwrap().disk_state(),
+ DiskState::Present { .. }
+ );
+ assert_matches!(
+ buffer4.read(cx).file().unwrap().disk_state(),
+ DiskState::Present { .. }
+ );
+ assert_eq!(
+ buffer5.read(cx).file().unwrap().disk_state(),
+ DiskState::Deleted
+ );
+ });
+
+ // Update the remote worktree. Check that it becomes consistent with the
+ // local worktree.
cx.executor().run_until_parked();
- buffer.update(cx, |buffer, _| {
- assert_eq!(buffer.text(), " ".to_string() + &new_contents);
- assert!(buffer.has_conflict());
+
+ remote.update(cx, |remote, _| {
+ for update in updates.lock().drain(..) {
+ remote.as_remote_mut().unwrap().update_from_remote(update);
+ }
+ });
+ cx.executor().run_until_parked();
+ remote.update(cx, |remote, _| {
+ assert_eq!(
+ remote.paths().collect::<Vec<_>>(),
+ vec![
+ rel_path("a"),
+ rel_path("a/file1"),
+ rel_path("a/file2.new"),
+ rel_path("b"),
+ rel_path("d"),
+ rel_path("d/file3"),
+ rel_path("d/file4"),
+ ]
+ );
});
}
-#[gpui::test]
-async fn test_buffer_line_endings(cx: &mut gpui::TestAppContext) {
+#[cfg(target_os = "linux")]
+#[gpui::test(retries = 5)]
+async fn test_recreated_directory_receives_child_events(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+ cx.executor().allow_parking();
+
+ let dir = TempTree::new(json!({}));
+ let project = Project::test(Arc::new(RealFs::new(None, cx.executor())), [dir.path()], cx).await;
+ let tree = project.update(cx, |project, cx| project.worktrees(cx).next().unwrap());
+
+ tree.flush_fs_events(cx).await;
+
+ let repro_dir = dir.path().join("repro");
+ std::fs::create_dir(&repro_dir).unwrap();
+ tree.flush_fs_events(cx).await;
+
+ cx.update(|cx| {
+ assert!(tree.read(cx).entry_for_path(rel_path("repro")).is_some());
+ });
+
+ std::fs::remove_dir_all(&repro_dir).unwrap();
+ tree.flush_fs_events(cx).await;
+
+ cx.update(|cx| {
+ assert!(tree.read(cx).entry_for_path(rel_path("repro")).is_none());
+ });
+
+ std::fs::create_dir(&repro_dir).unwrap();
+ tree.flush_fs_events(cx).await;
+
+ cx.update(|cx| {
+ assert!(tree.read(cx).entry_for_path(rel_path("repro")).is_some());
+ });
+
+ std::fs::write(repro_dir.join("repro-marker"), "").unwrap();
+ tree.flush_fs_events(cx).await;
+
+ cx.update(|cx| {
+ assert!(
+ tree.read(cx)
+ .entry_for_path(rel_path("repro/repro-marker"))
+ .is_some()
+ );
+ });
+}
+
+#[gpui::test(iterations = 10)]
+async fn test_buffer_identity_across_renames(cx: &mut gpui::TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
path!("/dir"),
json!({
- "file1": "a\nb\nc\n",
- "file2": "one\r\ntwo\r\nthree\r\n",
+ "a": {
+ "file1": "",
+ }
}),
)
.await;
- let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
- let buffer1 = project
- .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file1"), cx))
- .await
- .unwrap();
- let buffer2 = project
- .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file2"), cx))
- .await
- .unwrap();
+ let project = Project::test(fs, [Path::new(path!("/dir"))], cx).await;
+ let tree = project.update(cx, |project, cx| project.worktrees(cx).next().unwrap());
+ let tree_id = tree.update(cx, |tree, _| tree.id());
- buffer1.update(cx, |buffer, _| {
- assert_eq!(buffer.text(), "a\nb\nc\n");
- assert_eq!(buffer.line_ending(), LineEnding::Unix);
- });
- buffer2.update(cx, |buffer, _| {
- assert_eq!(buffer.text(), "one\ntwo\nthree\n");
- assert_eq!(buffer.line_ending(), LineEnding::Windows);
- });
+ let id_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
+ project.update(cx, |project, cx| {
+ let tree = project.worktrees(cx).next().unwrap();
+ tree.read(cx)
+ .entry_for_path(rel_path(path))
+ .unwrap_or_else(|| panic!("no entry for path {}", path))
+ .id
+ })
+ };
- // Change a file's line endings on disk from unix to windows. The buffer's
- // state updates correctly.
- fs.save(
- path!("/dir/file1").as_ref(),
- &"aaa\nb\nc\n".into(),
- LineEnding::Windows,
- )
- .await
- .unwrap();
- cx.executor().run_until_parked();
- buffer1.update(cx, |buffer, _| {
- assert_eq!(buffer.text(), "aaa\nb\nc\n");
- assert_eq!(buffer.line_ending(), LineEnding::Windows);
- });
+ let dir_id = id_for_path("a", cx);
+ let file_id = id_for_path("a/file1", cx);
+ let buffer = project
+ .update(cx, |p, cx| {
+ p.open_buffer((tree_id, rel_path("a/file1")), cx)
+ })
+ .await
+ .unwrap();
+ buffer.update(cx, |buffer, _| assert!(!buffer.is_dirty()));
- // Save a file with windows line endings. The file is written correctly.
- buffer2.update(cx, |buffer, cx| {
- buffer.set_text("one\ntwo\nthree\nfour\n", cx);
- });
project
- .update(cx, |project, cx| project.save_buffer(buffer2, cx))
+ .update(cx, |project, cx| {
+ project.rename_entry(dir_id, (tree_id, rel_path("b")).into(), cx)
+ })
+ .unwrap()
.await
+ .into_included()
.unwrap();
- assert_eq!(
- fs.load(path!("/dir/file2").as_ref()).await.unwrap(),
- "one\r\ntwo\r\nthree\r\nfour\r\n",
- );
+ cx.executor().run_until_parked();
+
+ assert_eq!(id_for_path("b", cx), dir_id);
+ assert_eq!(id_for_path("b/file1", cx), file_id);
+ buffer.update(cx, |buffer, _| assert!(!buffer.is_dirty()));
}
#[gpui::test]
-async fn test_line_ending_user_settings_on_format(cx: &mut gpui::TestAppContext) {
+async fn test_buffer_deduping(cx: &mut gpui::TestAppContext) {
init_test(cx);
- let cases = [
- (
- "default",
- None,
- [
- ("crlf_file.rs", LineEnding::Windows),
- ("lf_file.rs", LineEnding::Unix),
- ("no_newline.rs", LineEnding::default()),
- ],
- ),
- (
- "detect",
- Some(LineEndingSetting::Detect),
- [
- ("crlf_file.rs", LineEnding::Windows),
- ("lf_file.rs", LineEnding::Unix),
- ("no_newline.rs", LineEnding::default()),
- ],
- ),
- (
- "prefer_lf",
- Some(LineEndingSetting::PreferLf),
- [
- ("crlf_file.rs", LineEnding::Windows),
- ("lf_file.rs", LineEnding::Unix),
- ("no_newline.rs", LineEnding::Unix),
- ],
- ),
- (
- "prefer_crlf",
- Some(LineEndingSetting::PreferCrlf),
- [
- ("crlf_file.rs", LineEnding::Windows),
- ("lf_file.rs", LineEnding::Unix),
- ("no_newline.rs", LineEnding::Windows),
- ],
- ),
- (
- "enforce_lf",
- Some(LineEndingSetting::EnforceLf),
- [
- ("crlf_file.rs", LineEnding::Unix),
- ("lf_file.rs", LineEnding::Unix),
- ("no_newline.rs", LineEnding::Unix),
- ],
- ),
- (
- "enforce_crlf",
- Some(LineEndingSetting::EnforceCrlf),
- [
- ("crlf_file.rs", LineEnding::Windows),
- ("lf_file.rs", LineEnding::Windows),
- ("no_newline.rs", LineEnding::Windows),
- ],
- ),
- ];
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ "/dir",
+ json!({
+ "a.txt": "a-contents",
+ "b.txt": "b-contents",
+ }),
+ )
+ .await;
- for (case_name, line_ending_setting, expected_line_endings) in cases {
- let fs = FakeFs::new(cx.executor());
- fs.insert_tree(
- path!("/dir"),
- json!({
- "crlf_file.rs": "one\r\ntwo\r\nthree\r\n",
- "lf_file.rs": "one\ntwo\nthree\n",
- "no_newline.rs": "single line",
- }),
+ let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
+
+ // Spawn multiple tasks to open paths, repeating some paths.
+ let (buffer_a_1, buffer_b, buffer_a_2) = project.update(cx, |p, cx| {
+ (
+ p.open_local_buffer("/dir/a.txt", cx),
+ p.open_local_buffer("/dir/b.txt", cx),
+ p.open_local_buffer("/dir/a.txt", cx),
)
- .await;
+ });
- let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
- let language_registry = project.read_with(cx, |project, _| project.languages().clone());
- language_registry.add(rust_lang());
- let worktree_id = project.update(cx, |project, cx| {
- project.worktrees(cx).next().unwrap().read(cx).id()
- });
+ let buffer_a_1 = buffer_a_1.await.unwrap();
+ let buffer_a_2 = buffer_a_2.await.unwrap();
+ let buffer_b = buffer_b.await.unwrap();
+ assert_eq!(buffer_a_1.update(cx, |b, _| b.text()), "a-contents");
+ assert_eq!(buffer_b.update(cx, |b, _| b.text()), "b-contents");
- cx.update(|cx| {
- SettingsStore::update_global(cx, |store, cx| {
- store.update_user_settings(cx, |settings| {
- settings.project.all_languages.defaults.line_ending = line_ending_setting;
- });
- });
- });
- cx.executor().run_until_parked();
+ // There is only one buffer per path.
+ let buffer_a_id = buffer_a_1.entity_id();
+ assert_eq!(buffer_a_2.entity_id(), buffer_a_id);
- assert_line_endings_after_format(
- cx,
- &project,
- worktree_id,
- case_name,
- &expected_line_endings,
- )
- .await;
- }
+ // Open the same path again while it is still open.
+ drop(buffer_a_1);
+ let buffer_a_3 = project
+ .update(cx, |p, cx| p.open_local_buffer("/dir/a.txt", cx))
+ .await
+ .unwrap();
+
+ // There's still only one buffer per path.
+ assert_eq!(buffer_a_3.entity_id(), buffer_a_id);
}
#[gpui::test]
-async fn test_line_ending_editorconfig_on_format_and_save(cx: &mut gpui::TestAppContext) {
+async fn test_buffer_is_dirty(cx: &mut gpui::TestAppContext) {
init_test(cx);
- let cases = [
- (
- "editorconfig lf",
- "lf",
- "crlf_file.rs",
- LineEnding::Windows,
- [
- ("crlf_file.rs", LineEnding::Unix),
- ("lf_file.rs", LineEnding::Unix),
- ("no_newline.rs", LineEnding::Unix),
- ],
- "one\ntwo\nthree\n",
- ),
- (
- "editorconfig crlf",
- "crlf",
- "lf_file.rs",
- LineEnding::Unix,
- [
- ("crlf_file.rs", LineEnding::Windows),
- ("lf_file.rs", LineEnding::Windows),
- ("no_newline.rs", LineEnding::Windows),
- ],
- "one\r\ntwo\r\nthree\r\n",
- ),
- ];
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/dir"),
+ json!({
+ "file1": "abc",
+ "file2": "def",
+ "file3": "ghi",
+ }),
+ )
+ .await;
- for (
- case_name,
- editorconfig_end_of_line,
- buffer_path,
- initial_line_ending,
- expected_line_endings,
- expected_saved_contents,
- ) in cases
- {
- let file_system = FakeFs::new(cx.executor());
- file_system
- .insert_tree(
- path!("/dir"),
- json!({
- ".editorconfig": format!("root = true\n[*.rs]\nend_of_line = {editorconfig_end_of_line}\n"),
- "crlf_file.rs": "one\r\ntwo\r\nthree\r\n",
- "lf_file.rs": "one\ntwo\nthree\n",
- "no_newline.rs": "single line",
- }),
- )
- .await;
+ let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
- let project = Project::test(file_system.clone(), [path!("/dir").as_ref()], cx).await;
- let language_registry = project.read_with(cx, |project, _| project.languages().clone());
- language_registry.add(rust_lang());
- cx.executor().run_until_parked();
- let worktree_id = project.update(cx, |project, cx| {
- project.worktrees(cx).next().unwrap().read(cx).id()
- });
+ let buffer1 = project
+ .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file1"), cx))
+ .await
+ .unwrap();
+ let events = Arc::new(Mutex::new(Vec::new()));
- let buffer = project
- .update(cx, |project, cx| {
- project.open_buffer((worktree_id, rel_path(buffer_path)), cx)
- })
- .await
- .unwrap();
- buffer.update(cx, |buffer, _| {
- assert_eq!(buffer.line_ending(), initial_line_ending);
- });
+ // initially, the buffer isn't dirty.
+ buffer1.update(cx, |buffer, cx| {
+ cx.subscribe(&buffer1, {
+ let events = events.clone();
+ move |_, _, event, _| match event {
+ BufferEvent::Operation { .. } => {}
+ _ => events.lock().push(event.clone()),
+ }
+ })
+ .detach();
- assert_line_endings_after_format(
+ assert!(!buffer.is_dirty());
+ assert!(events.lock().is_empty());
+
+ buffer.edit([(1..2, "")], None, cx);
+ });
+
+ // after the first edit, the buffer is dirty, and emits a dirtied event.
+ buffer1.update(cx, |buffer, cx| {
+ assert!(buffer.text() == "ac");
+ assert!(buffer.is_dirty());
+ assert_eq!(
+ *events.lock(),
+ &[
+ language::BufferEvent::Edited {
+ source: language::BufferEditSource::User
+ },
+ language::BufferEvent::DirtyChanged
+ ]
+ );
+ events.lock().clear();
+ buffer.did_save(
+ buffer.version(),
+ buffer.file().unwrap().disk_state().mtime(),
cx,
- &project,
- worktree_id,
- case_name,
- &expected_line_endings,
- )
- .await;
+ );
+ });
- project
- .update(cx, |project, cx| project.save_buffer(buffer, cx))
- .await
- .unwrap();
- let saved_path = PathBuf::from(path!("/dir")).join(buffer_path);
+ // after saving, the buffer is not dirty, and emits a saved event.
+ buffer1.update(cx, |buffer, cx| {
+ assert!(!buffer.is_dirty());
+ assert_eq!(*events.lock(), &[language::BufferEvent::Saved]);
+ events.lock().clear();
+
+ buffer.edit([(1..1, "B")], None, cx);
+ buffer.edit([(2..2, "D")], None, cx);
+ });
+
+ // after editing again, the buffer is dirty, and emits another dirty event.
+ buffer1.update(cx, |buffer, cx| {
+ assert!(buffer.text() == "aBDc");
+ assert!(buffer.is_dirty());
assert_eq!(
- file_system.load(&saved_path).await.unwrap(),
- expected_saved_contents,
+ *events.lock(),
+ &[
+ language::BufferEvent::Edited {
+ source: language::BufferEditSource::User
+ },
+ language::BufferEvent::DirtyChanged,
+ language::BufferEvent::Edited {
+ source: language::BufferEditSource::User
+ },
+ ],
);
- }
-}
+ events.lock().clear();
-#[gpui::test]
-async fn test_line_ending_initialization_for_new_buffers(cx: &mut gpui::TestAppContext) {
- init_test(cx);
+ // After restoring the buffer to its previously-saved state,
+ // the buffer is not considered dirty anymore.
+ buffer.edit([(1..3, "")], None, cx);
+ assert!(buffer.text() == "ac");
+ assert!(!buffer.is_dirty());
+ });
- let cases = [
- (Some(LineEndingSetting::Detect), LineEnding::default()),
- (Some(LineEndingSetting::PreferLf), LineEnding::Unix),
- (Some(LineEndingSetting::PreferCrlf), LineEnding::Windows),
- (Some(LineEndingSetting::EnforceLf), LineEnding::Unix),
- (Some(LineEndingSetting::EnforceCrlf), LineEnding::Windows),
- ];
+ assert_eq!(
+ *events.lock(),
+ &[
+ language::BufferEvent::Edited {
+ source: language::BufferEditSource::User
+ },
+ language::BufferEvent::DirtyChanged
+ ]
+ );
- for (line_ending_setting, expected_line_ending) in cases {
- let fs = FakeFs::new(cx.executor());
- fs.insert_tree(path!("/dir"), json!({})).await;
+ // When a file is deleted, it is not considered dirty.
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let buffer2 = project
+ .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file2"), cx))
+ .await
+ .unwrap();
+ buffer2.update(cx, |_, cx| {
+ cx.subscribe(&buffer2, {
+ let events = events.clone();
+ move |_, _, event, _| match event {
+ BufferEvent::Operation { .. } => {}
+ _ => events.lock().push(event.clone()),
+ }
+ })
+ .detach();
+ });
- let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
- cx.update(|cx| {
- SettingsStore::update_global(cx, |store, cx| {
- store.update_user_settings(cx, |settings| {
- settings.project.all_languages.defaults.line_ending = line_ending_setting;
- });
- });
- });
- cx.executor().run_until_parked();
+ fs.remove_file(path!("/dir/file2").as_ref(), fs::RemoveOptions::default())
+ .await
+ .unwrap();
+ cx.executor().run_until_parked();
+ buffer2.update(cx, |buffer, _| assert!(!buffer.is_dirty()));
+ assert_eq!(
+ mem::take(&mut *events.lock()),
+ &[language::BufferEvent::FileHandleChanged]
+ );
- let created_buffer = project
- .update(cx, |project, cx| project.create_buffer(None, false, cx))
- .unwrap()
- .await;
- created_buffer.update(cx, |buffer, _| {
- assert_eq!(buffer.line_ending(), expected_line_ending);
- });
+ // Buffer becomes dirty when edited.
+ buffer2.update(cx, |buffer, cx| {
+ buffer.edit([(2..3, "")], None, cx);
+ assert_eq!(buffer.is_dirty(), true);
+ });
+ assert_eq!(
+ mem::take(&mut *events.lock()),
+ &[
+ language::BufferEvent::Edited {
+ source: language::BufferEditSource::User
+ },
+ language::BufferEvent::DirtyChanged
+ ]
+ );
- let local_buffer = project.update(cx, |project, cx| {
- project.create_local_buffer("single line", None, false, cx)
- });
- local_buffer.update(cx, |buffer, _| {
- assert_eq!(buffer.line_ending(), expected_line_ending);
- });
+ // Buffer becomes clean again when all of its content is removed, because
+ // the file was deleted.
+ buffer2.update(cx, |buffer, cx| {
+ buffer.edit([(0..2, "")], None, cx);
+ assert_eq!(buffer.is_empty(), true);
+ assert_eq!(buffer.is_dirty(), false);
+ });
+ assert_eq!(
+ *events.lock(),
+ &[
+ language::BufferEvent::Edited {
+ source: language::BufferEditSource::User
+ },
+ language::BufferEvent::DirtyChanged
+ ]
+ );
- let opened_missing_buffer = project
- .update(cx, |project, cx| {
- project.open_local_buffer(path!("/dir/new_file.rs"), cx)
- })
- .await
- .unwrap();
- opened_missing_buffer.update(cx, |buffer, _| {
- assert_eq!(buffer.line_ending(), expected_line_ending);
- });
- }
-}
+ // When a file is already dirty when deleted, we don't emit a Dirtied event.
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let buffer3 = project
+ .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file3"), cx))
+ .await
+ .unwrap();
+ buffer3.update(cx, |_, cx| {
+ cx.subscribe(&buffer3, {
+ let events = events.clone();
+ move |_, _, event, _| match event {
+ BufferEvent::Operation { .. } => {}
+ _ => events.lock().push(event.clone()),
+ }
+ })
+ .detach();
+ });
-async fn assert_line_endings_after_format(
- cx: &mut gpui::TestAppContext,
- project: &Entity<Project>,
- worktree_id: WorktreeId,
- case_name: &str,
- expected_line_endings: &[(&str, LineEnding)],
-) {
- for (path, expected_line_ending) in expected_line_endings {
- let buffer = project
- .update(cx, |project, cx| {
- project.open_buffer((worktree_id, rel_path(path)), cx)
- })
- .await
- .unwrap();
- let mut buffers = HashSet::default();
- buffers.insert(buffer.clone());
- project
- .update(cx, |project, cx| {
- project.format(
- buffers,
- project::lsp_store::LspFormatTarget::Buffers,
- false,
- project::lsp_store::FormatTrigger::Save,
- cx,
- )
- })
- .await
- .unwrap();
- buffer.update(cx, |buffer, _| {
- assert_eq!(
- buffer.line_ending(),
- *expected_line_ending,
- "unexpected line ending for {path} in {case_name}"
- );
- });
- }
+ buffer3.update(cx, |buffer, cx| {
+ buffer.edit([(0..0, "x")], None, cx);
+ });
+ events.lock().clear();
+ fs.remove_file(path!("/dir/file3").as_ref(), fs::RemoveOptions::default())
+ .await
+ .unwrap();
+ cx.executor().run_until_parked();
+ assert_eq!(*events.lock(), &[language::BufferEvent::FileHandleChanged]);
+ cx.update(|cx| assert!(buffer3.read(cx).is_dirty()));
}
#[gpui::test]
-async fn test_grouped_diagnostics(cx: &mut gpui::TestAppContext) {
+async fn test_dirty_buffer_reloads_after_undo(cx: &mut gpui::TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
path!("/dir"),
json!({
- "a.rs": "
- fn foo(mut v: Vec<usize>) {
- for x in &v {
- v.push(1);
- }
- }
- "
- .unindent(),
+ "file.txt": "version 1",
}),
)
.await;
let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
- let lsp_store = project.read_with(cx, |project, _| project.lsp_store());
let buffer = project
- .update(cx, |p, cx| p.open_local_buffer(path!("/dir/a.rs"), cx))
+ .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file.txt"), cx))
+ .await
+ .unwrap();
+
+ buffer.read_with(cx, |buffer, _| {
+ assert_eq!(buffer.text(), "version 1");
+ assert!(!buffer.is_dirty());
+ });
+
+ // User makes an edit, making the buffer dirty.
+ buffer.update(cx, |buffer, cx| {
+ buffer.edit([(0..0, "user edit: ")], None, cx);
+ });
+
+ buffer.read_with(cx, |buffer, _| {
+ assert!(buffer.is_dirty());
+ assert_eq!(buffer.text(), "user edit: version 1");
+ });
+
+ // External tool writes new content while buffer is dirty.
+ // file_updated() updates the File but suppresses ReloadNeeded.
+ fs.save(
+ path!("/dir/file.txt").as_ref(),
+ &"version 2 from external tool".into(),
+ LineEnding::default(),
+ )
+ .await
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ buffer.read_with(cx, |buffer, _| {
+ assert!(buffer.has_conflict());
+ assert_eq!(buffer.text(), "user edit: version 1");
+ });
+
+ // User undoes their edit. Buffer becomes clean, but disk has different
+ // content. did_edit() detects the dirty->clean transition and checks if
+ // disk changed while dirty. Since mtime differs from saved_mtime, it
+ // emits ReloadNeeded.
+ buffer.update(cx, |buffer, cx| {
+ buffer.undo(cx);
+ });
+ cx.executor().run_until_parked();
+
+ buffer.read_with(cx, |buffer, _| {
+ assert_eq!(
+ buffer.text(),
+ "version 2 from external tool",
+ "buffer should reload from disk after undo makes it clean"
+ );
+ assert!(!buffer.is_dirty());
+ });
+}
+
+#[gpui::test]
+async fn test_buffer_file_change_to_binary_fails(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/dir"),
+ json!({
+ "file.txt": "",
+ }),
+ )
+ .await;
+
+ let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
+ let buffer = project
+ .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file.txt"), cx))
+ .await
+ .unwrap();
+
+ fs.write(
+ path!("/dir/file.txt").as_ref(),
+ b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01",
+ )
+ .await
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ // Test that existing buffer is left untouched
+ buffer.read_with(cx, |buffer, _| {
+ assert_eq!(buffer.text(), "");
+ });
+}
+
+#[gpui::test]
+async fn test_buffer_file_changes_on_disk(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+
+ let (initial_contents, initial_offsets) =
+ marked_text_offsets("one twoˇ\nthree ˇfourˇ five\nsixˇ seven\n");
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/dir"),
+ json!({
+ "the-file": initial_contents,
+ }),
+ )
+ .await;
+ let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
+ let buffer = project
+ .update(cx, |p, cx| p.open_local_buffer(path!("/dir/the-file"), cx))
+ .await
+ .unwrap();
+
+ let anchors = initial_offsets
+ .iter()
+ .map(|offset| buffer.update(cx, |b, _| b.anchor_before(offset)))
+ .collect::<Vec<_>>();
+
+ // Change the file on disk, adding two new lines of text, and removing
+ // one line.
+ buffer.update(cx, |buffer, _| {
+ assert!(!buffer.is_dirty());
+ assert!(!buffer.has_conflict());
+ });
+
+ let (new_contents, new_offsets) =
+ marked_text_offsets("oneˇ\nthree ˇFOURˇ five\nsixtyˇ seven\n");
+ fs.save(
+ path!("/dir/the-file").as_ref(),
+ &new_contents.as_str().into(),
+ LineEnding::Unix,
+ )
+ .await
+ .unwrap();
+
+ // Because the buffer was not modified, it is reloaded from disk. Its
+ // contents are edited according to the diff between the old and new
+ // file contents.
+ cx.executor().run_until_parked();
+ buffer.update(cx, |buffer, _| {
+ assert_eq!(buffer.text(), new_contents);
+ assert!(!buffer.is_dirty());
+ assert!(!buffer.has_conflict());
+
+ let anchor_offsets = anchors
+ .iter()
+ .map(|anchor| anchor.to_offset(&*buffer))
+ .collect::<Vec<_>>();
+ assert_eq!(anchor_offsets, new_offsets);
+ });
+
+ // Modify the buffer
+ buffer.update(cx, |buffer, cx| {
+ buffer.edit([(0..0, " ")], None, cx);
+ assert!(buffer.is_dirty());
+ assert!(!buffer.has_conflict());
+ });
+
+ // Change the file on disk again, adding blank lines to the beginning.
+ fs.save(
+ path!("/dir/the-file").as_ref(),
+ &"\n\n\nAAAA\naaa\nBB\nbbbbb\n".into(),
+ LineEnding::Unix,
+ )
+ .await
+ .unwrap();
+
+ // Because the buffer is modified, it doesn't reload from disk, but is
+ // marked as having a conflict.
+ cx.executor().run_until_parked();
+ buffer.update(cx, |buffer, _| {
+ assert_eq!(buffer.text(), " ".to_string() + &new_contents);
+ assert!(buffer.has_conflict());
+ });
+}
+
+#[gpui::test]
+async fn test_buffer_line_endings(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/dir"),
+ json!({
+ "file1": "a\nb\nc\n",
+ "file2": "one\r\ntwo\r\nthree\r\n",
+ }),
+ )
+ .await;
+
+ let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
+ let buffer1 = project
+ .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file1"), cx))
+ .await
+ .unwrap();
+ let buffer2 = project
+ .update(cx, |p, cx| p.open_local_buffer(path!("/dir/file2"), cx))
+ .await
+ .unwrap();
+
+ buffer1.update(cx, |buffer, _| {
+ assert_eq!(buffer.text(), "a\nb\nc\n");
+ assert_eq!(buffer.line_ending(), LineEnding::Unix);
+ });
+ buffer2.update(cx, |buffer, _| {
+ assert_eq!(buffer.text(), "one\ntwo\nthree\n");
+ assert_eq!(buffer.line_ending(), LineEnding::Windows);
+ });
+
+ // Change a file's line endings on disk from unix to windows. The buffer's
+ // state updates correctly.
+ fs.save(
+ path!("/dir/file1").as_ref(),
+ &"aaa\nb\nc\n".into(),
+ LineEnding::Windows,
+ )
+ .await
+ .unwrap();
+ cx.executor().run_until_parked();
+ buffer1.update(cx, |buffer, _| {
+ assert_eq!(buffer.text(), "aaa\nb\nc\n");
+ assert_eq!(buffer.line_ending(), LineEnding::Windows);
+ });
+
+ // Save a file with windows line endings. The file is written correctly.
+ buffer2.update(cx, |buffer, cx| {
+ buffer.set_text("one\ntwo\nthree\nfour\n", cx);
+ });
+ project
+ .update(cx, |project, cx| project.save_buffer(buffer2, cx))
+ .await
+ .unwrap();
+ assert_eq!(
+ fs.load(path!("/dir/file2").as_ref()).await.unwrap(),
+ "one\r\ntwo\r\nthree\r\nfour\r\n",
+ );
+}
+
+#[gpui::test]
+async fn test_line_ending_user_settings_on_format(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+
+ let cases = [
+ (
+ "default",
+ None,
+ [
+ ("crlf_file.rs", LineEnding::Windows),
+ ("lf_file.rs", LineEnding::Unix),
+ ("no_newline.rs", LineEnding::default()),
+ ],
+ ),
+ (
+ "detect",
+ Some(LineEndingSetting::Detect),
+ [
+ ("crlf_file.rs", LineEnding::Windows),
+ ("lf_file.rs", LineEnding::Unix),
+ ("no_newline.rs", LineEnding::default()),
+ ],
+ ),
+ (
+ "prefer_lf",
+ Some(LineEndingSetting::PreferLf),
+ [
+ ("crlf_file.rs", LineEnding::Windows),
+ ("lf_file.rs", LineEnding::Unix),
+ ("no_newline.rs", LineEnding::Unix),
+ ],
+ ),
+ (
+ "prefer_crlf",
+ Some(LineEndingSetting::PreferCrlf),
+ [
+ ("crlf_file.rs", LineEnding::Windows),
+ ("lf_file.rs", LineEnding::Unix),
+ ("no_newline.rs", LineEnding::Windows),
+ ],
+ ),
+ (
+ "enforce_lf",
+ Some(LineEndingSetting::EnforceLf),
+ [
+ ("crlf_file.rs", LineEnding::Unix),
+ ("lf_file.rs", LineEnding::Unix),
+ ("no_newline.rs", LineEnding::Unix),
+ ],
+ ),
+ (
+ "enforce_crlf",
+ Some(LineEndingSetting::EnforceCrlf),
+ [
+ ("crlf_file.rs", LineEnding::Windows),
+ ("lf_file.rs", LineEnding::Windows),
+ ("no_newline.rs", LineEnding::Windows),
+ ],
+ ),
+ ];
+
+ for (case_name, line_ending_setting, expected_line_endings) in cases {
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/dir"),
+ json!({
+ "crlf_file.rs": "one\r\ntwo\r\nthree\r\n",
+ "lf_file.rs": "one\ntwo\nthree\n",
+ "no_newline.rs": "single line",
+ }),
+ )
+ .await;
+
+ let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+ let worktree_id = project.update(cx, |project, cx| {
+ project.worktrees(cx).next().unwrap().read(cx).id()
+ });
+
+ cx.update(|cx| {
+ SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, |settings| {
+ settings.project.all_languages.defaults.line_ending = line_ending_setting;
+ });
+ });
+ });
+ cx.executor().run_until_parked();
+
+ assert_line_endings_after_format(
+ cx,
+ &project,
+ worktree_id,
+ case_name,
+ &expected_line_endings,
+ )
+ .await;
+ }
+}
+
+#[gpui::test]
+async fn test_line_ending_editorconfig_on_format_and_save(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+
+ let cases = [
+ (
+ "editorconfig lf",
+ "lf",
+ "crlf_file.rs",
+ LineEnding::Windows,
+ [
+ ("crlf_file.rs", LineEnding::Unix),
+ ("lf_file.rs", LineEnding::Unix),
+ ("no_newline.rs", LineEnding::Unix),
+ ],
+ "one\ntwo\nthree\n",
+ ),
+ (
+ "editorconfig crlf",
+ "crlf",
+ "lf_file.rs",
+ LineEnding::Unix,
+ [
+ ("crlf_file.rs", LineEnding::Windows),
+ ("lf_file.rs", LineEnding::Windows),
+ ("no_newline.rs", LineEnding::Windows),
+ ],
+ "one\r\ntwo\r\nthree\r\n",
+ ),
+ ];
+
+ for (
+ case_name,
+ editorconfig_end_of_line,
+ buffer_path,
+ initial_line_ending,
+ expected_line_endings,
+ expected_saved_contents,
+ ) in cases
+ {
+ let file_system = FakeFs::new(cx.executor());
+ file_system
+ .insert_tree(
+ path!("/dir"),
+ json!({
+ ".editorconfig": format!("root = true\n[*.rs]\nend_of_line = {editorconfig_end_of_line}\n"),
+ "crlf_file.rs": "one\r\ntwo\r\nthree\r\n",
+ "lf_file.rs": "one\ntwo\nthree\n",
+ "no_newline.rs": "single line",
+ }),
+ )
+ .await;
+
+ let project = Project::test(file_system.clone(), [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+ cx.executor().run_until_parked();
+ let worktree_id = project.update(cx, |project, cx| {
+ project.worktrees(cx).next().unwrap().read(cx).id()
+ });
+
+ let buffer = project
+ .update(cx, |project, cx| {
+ project.open_buffer((worktree_id, rel_path(buffer_path)), cx)
+ })
+ .await
+ .unwrap();
+ buffer.update(cx, |buffer, _| {
+ assert_eq!(buffer.line_ending(), initial_line_ending);
+ });
+
+ assert_line_endings_after_format(
+ cx,
+ &project,
+ worktree_id,
+ case_name,
+ &expected_line_endings,
+ )
+ .await;
+
+ project
+ .update(cx, |project, cx| project.save_buffer(buffer, cx))
+ .await
+ .unwrap();
+ let saved_path = PathBuf::from(path!("/dir")).join(buffer_path);
+ assert_eq!(
+ file_system.load(&saved_path).await.unwrap(),
+ expected_saved_contents,
+ );
+ }
+}
+
+#[gpui::test]
+async fn test_line_ending_initialization_for_new_buffers(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+
+ let cases = [
+ (Some(LineEndingSetting::Detect), LineEnding::default()),
+ (Some(LineEndingSetting::PreferLf), LineEnding::Unix),
+ (Some(LineEndingSetting::PreferCrlf), LineEnding::Windows),
+ (Some(LineEndingSetting::EnforceLf), LineEnding::Unix),
+ (Some(LineEndingSetting::EnforceCrlf), LineEnding::Windows),
+ ];
+
+ for (line_ending_setting, expected_line_ending) in cases {
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(path!("/dir"), json!({})).await;
+
+ let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
+ cx.update(|cx| {
+ SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, |settings| {
+ settings.project.all_languages.defaults.line_ending = line_ending_setting;
+ });
+ });
+ });
+ cx.executor().run_until_parked();
+
+ let created_buffer = project
+ .update(cx, |project, cx| project.create_buffer(None, false, cx))
+ .unwrap()
+ .await;
+ created_buffer.update(cx, |buffer, _| {
+ assert_eq!(buffer.line_ending(), expected_line_ending);
+ });
+
+ let local_buffer = project.update(cx, |project, cx| {
+ project.create_local_buffer("single line", None, false, cx)
+ });
+ local_buffer.update(cx, |buffer, _| {
+ assert_eq!(buffer.line_ending(), expected_line_ending);
+ });
+
+ let opened_missing_buffer = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer(path!("/dir/new_file.rs"), cx)
+ })
+ .await
+ .unwrap();
+ opened_missing_buffer.update(cx, |buffer, _| {
+ assert_eq!(buffer.line_ending(), expected_line_ending);
+ });
+ }
+}
+
+async fn assert_line_endings_after_format(
+ cx: &mut gpui::TestAppContext,
+ project: &Entity<Project>,
+ worktree_id: WorktreeId,
+ case_name: &str,
+ expected_line_endings: &[(&str, LineEnding)],
+) {
+ for (path, expected_line_ending) in expected_line_endings {
+ let buffer = project
+ .update(cx, |project, cx| {
+ project.open_buffer((worktree_id, rel_path(path)), cx)
+ })
+ .await
+ .unwrap();
+ let mut buffers = HashSet::default();
+ buffers.insert(buffer.clone());
+ project
+ .update(cx, |project, cx| {
+ project.format(
+ buffers,
+ project::lsp_store::LspFormatTarget::Buffers,
+ false,
+ project::lsp_store::FormatTrigger::Save,
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+ buffer.update(cx, |buffer, _| {
+ assert_eq!(
+ buffer.line_ending(),
+ *expected_line_ending,
+ "unexpected line ending for {path} in {case_name}"
+ );
+ });
+ }
+}
+
+#[gpui::test]
+async fn test_grouped_diagnostics(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/dir"),
+ json!({
+ "a.rs": "
+ fn foo(mut v: Vec<usize>) {
+ for x in &v {
+ v.push(1);
+ }
+ }
+ "
+ .unindent(),
+ }),
+ )
+ .await;
+
+ let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
+ let lsp_store = project.read_with(cx, |project, _| project.lsp_store());
+ let buffer = project
+ .update(cx, |p, cx| p.open_local_buffer(path!("/dir/a.rs"), cx))
+ .await
+ .unwrap();
+
+ let buffer_uri = Uri::from_file_path(path!("/dir/a.rs")).unwrap();
+ let error_1_related_information: Arc<[lsp::DiagnosticRelatedInformation]> =
+ Arc::from([lsp::DiagnosticRelatedInformation {
+ location: lsp::Location {
+ uri: buffer_uri.clone(),
+ range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
+ },
+ message: "error 1 hint 1".to_string(),
+ }]);
+ let error_2_related_information: Arc<[lsp::DiagnosticRelatedInformation]> = Arc::from([
+ lsp::DiagnosticRelatedInformation {
+ location: lsp::Location {
+ uri: buffer_uri.clone(),
+ range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
+ },
+ message: "error 2 hint 1".to_string(),
+ },
+ lsp::DiagnosticRelatedInformation {
+ location: lsp::Location {
+ uri: buffer_uri.clone(),
+ range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
+ },
+ message: "error 2 hint 2".to_string(),
+ },
+ ]);
+ let error_1_hint_related_information: Arc<[lsp::DiagnosticRelatedInformation]> =
+ Arc::from([lsp::DiagnosticRelatedInformation {
+ location: lsp::Location {
+ uri: buffer_uri.clone(),
+ range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
+ },
+ message: "original diagnostic".to_string(),
+ }]);
+ let error_2_hint_related_information: Arc<[lsp::DiagnosticRelatedInformation]> =
+ Arc::from([lsp::DiagnosticRelatedInformation {
+ location: lsp::Location {
+ uri: buffer_uri.clone(),
+ range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
+ },
+ message: "original diagnostic".to_string(),
+ }]);
+ let message = lsp::PublishDiagnosticsParams {
+ uri: buffer_uri,
+ diagnostics: vec![
+ lsp::Diagnostic {
+ range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
+ severity: Some(DiagnosticSeverity::WARNING),
+ message: lsp::DiagnosticMessage::from("error 1"),
+ related_information: Some(error_1_related_information.to_vec()),
+ ..lsp::Diagnostic::default()
+ },
+ lsp::Diagnostic {
+ range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
+ severity: Some(DiagnosticSeverity::HINT),
+ message: lsp::DiagnosticMessage::from("error 1 hint 1"),
+ related_information: Some(error_1_hint_related_information.to_vec()),
+ ..lsp::Diagnostic::default()
+ },
+ lsp::Diagnostic {
+ range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
+ severity: Some(DiagnosticSeverity::ERROR),
+ message: lsp::DiagnosticMessage::from("error 2"),
+ related_information: Some(error_2_related_information.to_vec()),
+ ..lsp::Diagnostic::default()
+ },
+ lsp::Diagnostic {
+ range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
+ severity: Some(DiagnosticSeverity::HINT),
+ message: lsp::DiagnosticMessage::from("error 2 hint 1"),
+ related_information: Some(error_2_hint_related_information.to_vec()),
+ ..lsp::Diagnostic::default()
+ },
+ lsp::Diagnostic {
+ range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
+ severity: Some(DiagnosticSeverity::HINT),
+ message: lsp::DiagnosticMessage::from("error 2 hint 2"),
+ related_information: Some(error_2_hint_related_information.to_vec()),
+ ..lsp::Diagnostic::default()
+ },
+ ],
+ version: None,
+ };
+
+ lsp_store
+ .update(cx, |lsp_store, cx| {
+ lsp_store.update_diagnostics(
+ LanguageServerId(0),
+ message,
+ None,
+ DiagnosticSourceKind::Pushed,
+ &[],
+ cx,
+ )
+ })
+ .unwrap();
+ let buffer = buffer.update(cx, |buffer, _| buffer.snapshot());
+
+ assert_eq!(
+ buffer
+ .diagnostic_entries_in_range(0..buffer.len(), false)
+ .map(|entry| entry.clone().map_coordinates(|range| {
+ range.start.to_point(&buffer)..range.end.to_point(&buffer)
+ }))
+ .collect::<Vec<_>>(),
+ &[
+ DiagnosticEntry {
+ range: Point::new(1, 8)..Point::new(1, 9),
+ related_information: expected_related_information(&error_1_related_information),
+ diagnostic: Diagnostic {
+ severity: DiagnosticSeverity::WARNING,
+ message: "error 1".into(),
+ group_id: 1,
+ is_primary: true,
+ source_kind: DiagnosticSourceKind::Pushed,
+ ..Diagnostic::default()
+ },
+ },
+ DiagnosticEntry {
+ range: Point::new(1, 8)..Point::new(1, 9),
+ related_information: expected_related_information(
+ &error_1_hint_related_information
+ ),
+ diagnostic: Diagnostic {
+ severity: DiagnosticSeverity::HINT,
+ message: "error 1 hint 1".into(),
+ group_id: 1,
+ is_primary: false,
+ source_kind: DiagnosticSourceKind::Pushed,
+ ..Diagnostic::default()
+ },
+ },
+ DiagnosticEntry {
+ range: Point::new(1, 13)..Point::new(1, 15),
+ related_information: expected_related_information(
+ &error_2_hint_related_information
+ ),
+ diagnostic: Diagnostic {
+ severity: DiagnosticSeverity::HINT,
+ message: "error 2 hint 1".into(),
+ group_id: 0,
+ is_primary: false,
+ source_kind: DiagnosticSourceKind::Pushed,
+ ..Diagnostic::default()
+ },
+ },
+ DiagnosticEntry {
+ range: Point::new(1, 13)..Point::new(1, 15),
+ related_information: expected_related_information(
+ &error_2_hint_related_information
+ ),
+ diagnostic: Diagnostic {
+ severity: DiagnosticSeverity::HINT,
+ message: "error 2 hint 2".into(),
+ group_id: 0,
+ is_primary: false,
+ source_kind: DiagnosticSourceKind::Pushed,
+ ..Diagnostic::default()
+ },
+ },
+ DiagnosticEntry {
+ range: Point::new(2, 8)..Point::new(2, 17),
+ related_information: expected_related_information(&error_2_related_information),
+ diagnostic: Diagnostic {
+ severity: DiagnosticSeverity::ERROR,
+ message: "error 2".into(),
+ group_id: 0,
+ is_primary: true,
+ source_kind: DiagnosticSourceKind::Pushed,
+ ..Diagnostic::default()
+ },
+ }
+ ]
+ );
+
+ assert_eq!(
+ buffer.diagnostic_group::<Point>(0).collect::<Vec<_>>(),
+ &[
+ DiagnosticEntry {
+ range: Point::new(1, 13)..Point::new(1, 15),
+ related_information: expected_related_information(
+ &error_2_hint_related_information
+ ),
+ diagnostic: Diagnostic {
+ severity: DiagnosticSeverity::HINT,
+ message: "error 2 hint 1".into(),
+ group_id: 0,
+ is_primary: false,
+ source_kind: DiagnosticSourceKind::Pushed,
+ ..Diagnostic::default()
+ },
+ },
+ DiagnosticEntry {
+ range: Point::new(1, 13)..Point::new(1, 15),
+ related_information: expected_related_information(
+ &error_2_hint_related_information
+ ),
+ diagnostic: Diagnostic {
+ severity: DiagnosticSeverity::HINT,
+ message: "error 2 hint 2".into(),
+ group_id: 0,
+ is_primary: false,
+ source_kind: DiagnosticSourceKind::Pushed,
+ ..Diagnostic::default()
+ },
+ },
+ DiagnosticEntry {
+ range: Point::new(2, 8)..Point::new(2, 17),
+ related_information: expected_related_information(&error_2_related_information),
+ diagnostic: Diagnostic {
+ severity: DiagnosticSeverity::ERROR,
+ message: "error 2".into(),
+ group_id: 0,
+ is_primary: true,
+ source_kind: DiagnosticSourceKind::Pushed,
+ ..Diagnostic::default()
+ },
+ }
+ ]
+ );
+
+ assert_eq!(
+ buffer.diagnostic_group::<Point>(1).collect::<Vec<_>>(),
+ &[
+ DiagnosticEntry {
+ range: Point::new(1, 8)..Point::new(1, 9),
+ related_information: expected_related_information(&error_1_related_information),
+ diagnostic: Diagnostic {
+ severity: DiagnosticSeverity::WARNING,
+ message: "error 1".into(),
+ group_id: 1,
+ is_primary: true,
+ source_kind: DiagnosticSourceKind::Pushed,
+ ..Diagnostic::default()
+ },
+ },
+ DiagnosticEntry {
+ range: Point::new(1, 8)..Point::new(1, 9),
+ related_information: expected_related_information(
+ &error_1_hint_related_information
+ ),
+ diagnostic: Diagnostic {
+ severity: DiagnosticSeverity::HINT,
+ message: "error 1 hint 1".into(),
+ group_id: 1,
+ is_primary: false,
+ source_kind: DiagnosticSourceKind::Pushed,
+ ..Diagnostic::default()
+ },
+ },
+ ]
+ );
+}
+
+#[gpui::test]
+async fn test_lsp_rename_notifications(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/dir"),
+ json!({
+ "one.rs": "const ONE: usize = 1;",
+ "two": {
+ "two.rs": "const TWO: usize = one::ONE + one::ONE;"
+ }
+
+ }),
+ )
+ .await;
+ let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
+
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+ let watched_paths = lsp::FileOperationRegistrationOptions {
+ filters: vec![
+ FileOperationFilter {
+ scheme: Some("file".to_owned()),
+ pattern: lsp::FileOperationPattern {
+ glob: "**/*.rs".to_owned(),
+ matches: Some(lsp::FileOperationPatternKind::File),
+ options: None,
+ },
+ },
+ FileOperationFilter {
+ scheme: Some("file".to_owned()),
+ pattern: lsp::FileOperationPattern {
+ glob: "**/**".to_owned(),
+ matches: Some(lsp::FileOperationPatternKind::Folder),
+ options: None,
+ },
+ },
+ ],
+ };
+ let mut fake_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities {
+ workspace: Some(lsp::WorkspaceServerCapabilities {
+ workspace_folders: None,
+ file_operations: Some(lsp::WorkspaceFileOperationsServerCapabilities {
+ did_rename: Some(watched_paths.clone()),
+ will_rename: Some(watched_paths),
+ ..lsp::WorkspaceFileOperationsServerCapabilities::default()
+ }),
+ }),
+ ..lsp::ServerCapabilities::default()
+ },
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ let _ = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/one.rs"), cx)
+ })
+ .await
+ .unwrap();
+
+ let fake_server = fake_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+ let response = project.update(cx, |project, cx| {
+ let worktree = project.worktrees(cx).next().unwrap();
+ let entry = worktree
+ .read(cx)
+ .entry_for_path(rel_path("one.rs"))
+ .unwrap();
+ project.rename_entry(
+ entry.id,
+ (worktree.read(cx).id(), rel_path("three.rs")).into(),
+ cx,
+ )
+ });
+ let expected_edit = lsp::WorkspaceEdit {
+ changes: None,
+ document_changes: Some(DocumentChanges::Edits({
+ vec![TextDocumentEdit {
+ edits: vec![lsp::Edit::Plain(lsp::TextEdit {
+ range: lsp::Range {
+ start: lsp::Position {
+ line: 0,
+ character: 1,
+ },
+ end: lsp::Position {
+ line: 0,
+ character: 3,
+ },
+ },
+ new_text: "This is not a drill".to_owned(),
+ })],
+ text_document: lsp::OptionalVersionedTextDocumentIdentifier {
+ uri: Uri::from_str(uri!("file:///dir/two/two.rs")).unwrap(),
+ version: Some(1337),
+ },
+ }]
+ })),
+ change_annotations: None,
+ };
+ let resolved_workspace_edit = Arc::new(OnceLock::new());
+ fake_server
+ .set_request_handler::<WillRenameFiles, _, _>({
+ let resolved_workspace_edit = resolved_workspace_edit.clone();
+ let expected_edit = expected_edit.clone();
+ move |params, _| {
+ let resolved_workspace_edit = resolved_workspace_edit.clone();
+ let expected_edit = expected_edit.clone();
+ async move {
+ assert_eq!(params.files.len(), 1);
+ assert_eq!(params.files[0].old_uri, uri!("file:///dir/one.rs"));
+ assert_eq!(params.files[0].new_uri, uri!("file:///dir/three.rs"));
+ resolved_workspace_edit.set(expected_edit.clone()).unwrap();
+ Ok(Some(expected_edit))
+ }
+ }
+ })
+ .next()
+ .await
+ .unwrap();
+ let _ = response.await.unwrap();
+ fake_server
+ .handle_notification::<DidRenameFiles, _>(|params, _| {
+ assert_eq!(params.files.len(), 1);
+ assert_eq!(params.files[0].old_uri, uri!("file:///dir/one.rs"));
+ assert_eq!(params.files[0].new_uri, uri!("file:///dir/three.rs"));
+ })
+ .next()
+ .await
+ .unwrap();
+ assert_eq!(resolved_workspace_edit.get(), Some(&expected_edit));
+}
+
+#[gpui::test]
+async fn test_dynamic_call_hierarchy_followups_use_prepared_server(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/dir"),
+ json!({
+ "one.rs": "fn one() {}",
+ }),
+ )
+ .await;
+
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+ let mut fake_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities::default(),
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ let (buffer, _handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/one.rs"), cx)
+ })
+ .await
+ .unwrap();
+ let fake_server = fake_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "file-call-hierarchy".to_string(),
+ method: "textDocument/prepareCallHierarchy".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "file" }],
+ })),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ let item = lsp::CallHierarchyItem {
+ name: "one".to_string(),
+ kind: lsp::SymbolKind::FUNCTION,
+ tags: None,
+ detail: None,
+ uri: Uri::from_file_path(path!("/dir/one.rs")).unwrap(),
+ range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 11)),
+ selection_range: lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(0, 6)),
+ data: None,
+ };
+ let _prepare_requests = fake_server
+ .set_request_handler::<lsp::request::CallHierarchyPrepare, _, _>({
+ let item = item.clone();
+ move |_, _| {
+ let item = item.clone();
+ async move { Ok(Some(vec![item])) }
+ }
+ });
+ let incoming_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _incoming_requests = fake_server
+ .set_request_handler::<lsp::request::CallHierarchyIncomingCalls, _, _>({
+ let incoming_request_count = incoming_request_count.clone();
+ move |_, _| {
+ incoming_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+ let outgoing_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _outgoing_requests = fake_server
+ .set_request_handler::<lsp::request::CallHierarchyOutgoingCalls, _, _>({
+ let outgoing_request_count = outgoing_request_count.clone();
+ move |_, _| {
+ outgoing_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+
+ let items = project
+ .update(cx, |project, cx| {
+ project.prepare_call_hierarchy(&buffer, 0, cx)
+ })
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(items.len(), 1);
+ let item = items.into_iter().next().unwrap();
+
+ project
+ .update(cx, |project, cx| project.incoming_calls(item.clone(), cx))
+ .await
+ .unwrap()
+ .unwrap();
+ project
+ .update(cx, |project, cx| project.outgoing_calls(item, cx))
+ .await
+ .unwrap()
+ .unwrap();
+
+ assert_eq!(incoming_request_count.load(atomic::Ordering::SeqCst), 1);
+ assert_eq!(outgoing_request_count.load(atomic::Ordering::SeqCst), 1);
+}
+
+#[gpui::test]
+async fn test_dynamic_rename_registration_routes_prepare_rename(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/dir"),
+ json!({
+ "one.rs": "const ONE: usize = 1;",
+ }),
+ )
+ .await;
+
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+ let mut fake_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities::default(),
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ let (buffer, _handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/one.rs"), cx)
+ })
+ .await
+ .unwrap();
+
+ let fake_server = fake_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![
+ lsp::Registration {
+ id: "file-rename".to_string(),
+ method: "textDocument/rename".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "file" }],
+ "prepareProvider": true,
+ })),
+ },
+ lsp::Registration {
+ id: "untitled-rename".to_string(),
+ method: "textDocument/rename".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "untitled" }],
+ "prepareProvider": false,
+ })),
+ },
+ ],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ let _prepare_rename_requests = fake_server
+ .set_request_handler::<lsp::request::PrepareRenameRequest, _, _>(|_, _| async move {
+ Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
+ lsp::Position::new(0, 6),
+ lsp::Position::new(0, 9),
+ ))))
+ });
+
+ let response = project
+ .update(cx, |project, cx| {
+ project.prepare_rename(buffer.clone(), 7, cx)
+ })
+ .await
+ .unwrap();
+ let PrepareRenameResponse::Success { range, .. } = response else {
+ panic!("expected prepare rename request, got {response:?}");
+ };
+ let range = buffer.update(cx, |buffer, _| range.to_offset(buffer));
+ assert_eq!(range, 6..9);
+}
+
+#[gpui::test]
+async fn test_dynamic_rename_registration_without_prepare_provider_skips_prepare_rename(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/dir"),
+ json!({
+ "one.rs": "const ONE: usize = 1;",
+ }),
+ )
+ .await;
+
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+ let mut fake_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities::default(),
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ let (buffer, _handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/one.rs"), cx)
+ })
+ .await
+ .unwrap();
+
+ let fake_server = fake_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![
+ lsp::Registration {
+ id: "file-rename".to_string(),
+ method: "textDocument/rename".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "file" }],
+ "prepareProvider": false,
+ })),
+ },
+ lsp::Registration {
+ id: "untitled-rename".to_string(),
+ method: "textDocument/rename".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "untitled" }],
+ "prepareProvider": true,
+ })),
+ },
+ ],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ let prepare_rename_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _prepare_rename_requests = fake_server
+ .set_request_handler::<lsp::request::PrepareRenameRequest, _, _>({
+ let prepare_rename_request_count = prepare_rename_request_count.clone();
+ move |_, _| {
+ prepare_rename_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move {
+ Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
+ lsp::Position::new(0, 6),
+ lsp::Position::new(0, 9),
+ ))))
+ }
+ }
+ });
+
+ let response = project
+ .update(cx, |project, cx| {
+ project.prepare_rename(buffer.clone(), 7, cx)
+ })
+ .await
+ .unwrap();
+
+ assert_matches!(
+ response,
+ PrepareRenameResponse::OnlyUnpreparedRenameSupported
+ );
+ assert_eq!(
+ prepare_rename_request_count.load(atomic::Ordering::SeqCst),
+ 0
+ );
+}
+
+#[gpui::test]
+async fn test_prepare_rename_prefers_server_with_prepare_support(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/dir"),
+ json!({
+ "one.rs": "const ONE: usize = 1;",
+ }),
+ )
+ .await;
+
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+ let mut unprepared_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ name: "unprepared-rename-server",
+ capabilities: lsp::ServerCapabilities {
+ rename_provider: Some(lsp::OneOf::Right(lsp::RenameOptions {
+ prepare_provider: Some(false),
+ work_done_progress_options: lsp::WorkDoneProgressOptions::default(),
+ })),
+ ..lsp::ServerCapabilities::default()
+ },
+ ..FakeLspAdapter::default()
+ },
+ );
+ let mut prepared_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ name: "prepared-rename-server",
+ capabilities: lsp::ServerCapabilities {
+ rename_provider: Some(lsp::OneOf::Right(lsp::RenameOptions {
+ prepare_provider: Some(true),
+ work_done_progress_options: lsp::WorkDoneProgressOptions::default(),
+ })),
+ ..lsp::ServerCapabilities::default()
+ },
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ let (buffer, _handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/one.rs"), cx)
+ })
+ .await
+ .unwrap();
+ let unprepared_server = unprepared_servers.next().await.unwrap();
+ let prepared_server = prepared_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+
+ let unprepared_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _unprepared_requests = unprepared_server
+ .set_request_handler::<lsp::request::PrepareRenameRequest, _, _>({
+ let unprepared_request_count = unprepared_request_count.clone();
+ move |_, _| {
+ unprepared_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+ let _prepared_requests = prepared_server
+ .set_request_handler::<lsp::request::PrepareRenameRequest, _, _>(|_, _| async move {
+ Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
+ lsp::Position::new(0, 6),
+ lsp::Position::new(0, 9),
+ ))))
+ });
+ let unprepared_rename_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _unprepared_rename_requests = unprepared_server
+ .set_request_handler::<lsp::request::Rename, _, _>({
+ let unprepared_rename_request_count = unprepared_rename_request_count.clone();
+ move |_, _| {
+ unprepared_rename_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+ let prepared_rename_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _prepared_rename_requests = prepared_server
+ .set_request_handler::<lsp::request::Rename, _, _>({
+ let prepared_rename_request_count = prepared_rename_request_count.clone();
+ move |_, _| {
+ prepared_rename_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+
+ let response = project
+ .update(cx, |project, cx| {
+ project.prepare_rename(buffer.clone(), 7, cx)
+ })
+ .await
+ .unwrap();
+
+ let PrepareRenameResponse::Success {
+ range,
+ language_server_id,
+ } = response
+ else {
+ panic!("expected the prepare-capable server to serve the request, got {response:?}");
+ };
+ let range = buffer.update(cx, |buffer, _| range.to_offset(buffer));
+ assert_eq!(range, 6..9);
+ assert_eq!(language_server_id, Some(prepared_server.server.server_id()),);
+ assert_eq!(unprepared_request_count.load(atomic::Ordering::SeqCst), 0);
+
+ project
+ .update(cx, |project, cx| {
+ project.perform_rename(buffer, 7, "TWO".to_string(), language_server_id, cx)
+ })
+ .await
+ .unwrap();
+ assert_eq!(
+ unprepared_rename_request_count.load(atomic::Ordering::SeqCst),
+ 0,
+ "expected rename not to switch back to the first rename-capable server",
+ );
+ assert_eq!(
+ prepared_rename_request_count.load(atomic::Ordering::SeqCst),
+ 1,
+ "expected rename to use the server that prepared it",
+ );
+}
+
+#[gpui::test]
+async fn test_perform_rename_falls_back_when_prepared_server_is_gone(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/dir"),
+ json!({
+ "one.rs": "const ONE: usize = 1;",
+ }),
+ )
+ .await;
+
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+ let mut fake_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities {
+ rename_provider: Some(lsp::OneOf::Left(true)),
+ ..lsp::ServerCapabilities::default()
+ },
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ let (buffer, _handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/one.rs"), cx)
+ })
+ .await
+ .unwrap();
+ let fake_server = fake_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+
+ let rename_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _rename_requests = fake_server.set_request_handler::<lsp::request::Rename, _, _>({
+ let rename_request_count = rename_request_count.clone();
+ move |params, _| {
+ rename_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move {
+ assert_eq!(params.new_name, "TWO");
+ Ok(Some(lsp::WorkspaceEdit {
+ changes: Some(
+ [(
+ lsp::Uri::from_file_path(path!("/dir/one.rs")).unwrap(),
+ vec![lsp::TextEdit::new(
+ lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
+ "TWO".to_string(),
+ )],
+ )]
+ .into_iter()
+ .collect(),
+ ),
+ ..lsp::WorkspaceEdit::default()
+ }))
+ }
+ }
+ });
+
+ let transaction = project
+ .update(cx, |project, cx| {
+ project.perform_rename(
+ buffer.clone(),
+ 7,
+ "TWO".to_string(),
+ Some(LanguageServerId(4242)),
+ cx,
+ )
+ })
+ .await
+ .unwrap()
+ .0;
+
+ assert_eq!(
+ rename_request_count.load(atomic::Ordering::SeqCst),
+ 1,
+ "expected the rename to fall back to the live rename-capable server",
+ );
+ assert_eq!(
+ transaction.len(),
+ 1,
+ "expected a transaction for the renamed buffer",
+ );
+ assert_eq!(
+ buffer.read_with(cx, |buffer, _| buffer.text()),
+ "const TWO: usize = 1;"
+ );
+}
+
+#[gpui::test]
+async fn test_perform_rename_falls_back_when_server_unregisters_rename(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/dir"),
+ json!({
+ "one.rs": "const ONE: usize = 1;",
+ }),
+ )
+ .await;
+
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+ let mut dynamic_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ name: "dynamic-rename-server",
+ capabilities: lsp::ServerCapabilities::default(),
+ ..FakeLspAdapter::default()
+ },
+ );
+ let mut static_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ name: "static-rename-server",
+ capabilities: lsp::ServerCapabilities {
+ rename_provider: Some(lsp::OneOf::Left(true)),
+ ..lsp::ServerCapabilities::default()
+ },
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ let (buffer, _handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/one.rs"), cx)
+ })
+ .await
+ .unwrap();
+ let dynamic_server = dynamic_servers.next().await.unwrap();
+ let static_server = static_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+
+ dynamic_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "file-rename".to_string(),
+ method: "textDocument/rename".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "file" }],
+ "prepareProvider": false,
+ })),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ let dynamic_rename_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _dynamic_rename_requests = dynamic_server
+ .set_request_handler::<lsp::request::Rename, _, _>({
+ let dynamic_rename_request_count = dynamic_rename_request_count.clone();
+ move |_, _| {
+ dynamic_rename_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+ let static_rename_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _static_rename_requests =
+ static_server.set_request_handler::<lsp::request::Rename, _, _>({
+ let static_rename_request_count = static_rename_request_count.clone();
+ move |params, _| {
+ static_rename_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move {
+ assert_eq!(params.new_name, "TWO");
+ Ok(None)
+ }
+ }
+ });
+
+ dynamic_server
+ .request::<lsp::request::UnregisterCapability>(
+ lsp::UnregistrationParams {
+ unregisterations: vec![lsp::Unregistration {
+ id: "file-rename".to_string(),
+ method: "textDocument/rename".to_string(),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ let dynamic_server_id = dynamic_server.server.server_id();
+ project
+ .update(cx, |project, cx| {
+ project.perform_rename(
+ buffer.clone(),
+ 7,
+ "TWO".to_string(),
+ Some(dynamic_server_id),
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(
+ dynamic_rename_request_count.load(atomic::Ordering::SeqCst),
+ 0,
+ "expected no rename request for the server that unregistered its rename capability",
+ );
+ assert_eq!(
+ static_rename_request_count.load(atomic::Ordering::SeqCst),
+ 1,
+ "expected the rename to fall back to the rename-capable server",
+ );
+}
+
+#[gpui::test]
+async fn test_dynamic_formatting_registrations_honor_document_selectors(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx);
+ cx.update(|cx| {
+ SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, |settings| {
+ settings.project.all_languages.defaults.formatter = Some(FormatterList::Single(
+ Formatter::LanguageServer(settings::LanguageServerFormatterSpecifier::Current),
+ ));
+ });
+ });
+ });
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(path!("/dir"), json!({ "a.rs": "let value = 1;" }))
+ .await;
+
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+ let mut fake_language_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities::default(),
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ let (buffer, _handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/a.rs"), cx)
+ })
+ .await
+ .unwrap();
+ let fake_server = fake_language_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+
+ let format_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _format_requests = fake_server.set_request_handler::<lsp::request::Formatting, _, _>({
+ let format_request_count = format_request_count.clone();
+ move |_, _| {
+ format_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+ let format_buffer = |cx: &mut gpui::TestAppContext| {
+ project.update(cx, |project, cx| {
+ project.format(
+ HashSet::from_iter([buffer.clone()]),
+ project::lsp_store::LspFormatTarget::Buffers,
+ false,
+ project::lsp_store::FormatTrigger::Manual,
+ cx,
+ )
+ })
+ };
+
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "untitled-formatting".to_string(),
+ method: "textDocument/formatting".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "untitled" }],
+ })),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ format_buffer(cx).await.unwrap();
+ assert_eq!(
+ format_request_count.load(atomic::Ordering::SeqCst),
+ 0,
+ "expected no formatting request for a buffer outside the registration's selector",
+ );
+
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "file-formatting".to_string(),
+ method: "textDocument/formatting".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "file" }],
+ })),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ format_buffer(cx).await.unwrap();
+ assert_eq!(
+ format_request_count.load(atomic::Ordering::SeqCst),
+ 1,
+ "expected a formatting request once a matching registration exists",
+ );
+}
+
+#[gpui::test]
+async fn test_dynamic_formatting_registration_with_pattern_only_selector_fails_open(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx);
+ cx.update(|cx| {
+ SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, |settings| {
+ settings.project.all_languages.defaults.formatter = Some(FormatterList::Single(
+ Formatter::LanguageServer(settings::LanguageServerFormatterSpecifier::Current),
+ ));
+ });
+ });
+ });
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(path!("/dir"), json!({ "a.rs": "let value = 1;" }))
+ .await;
+
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+ let mut fake_language_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities::default(),
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ let (buffer, _handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/a.rs"), cx)
+ })
.await
.unwrap();
+ let fake_server = fake_language_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
- let buffer_uri = Uri::from_file_path(path!("/dir/a.rs")).unwrap();
- let error_1_related_information: Arc<[lsp::DiagnosticRelatedInformation]> =
- Arc::from([lsp::DiagnosticRelatedInformation {
- location: lsp::Location {
- uri: buffer_uri.clone(),
- range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
- },
- message: "error 1 hint 1".to_string(),
- }]);
- let error_2_related_information: Arc<[lsp::DiagnosticRelatedInformation]> = Arc::from([
- lsp::DiagnosticRelatedInformation {
- location: lsp::Location {
- uri: buffer_uri.clone(),
- range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
+ let format_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _format_requests = fake_server.set_request_handler::<lsp::request::Formatting, _, _>({
+ let format_request_count = format_request_count.clone();
+ move |_, _| {
+ format_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "pattern-only-formatting".to_string(),
+ method: "textDocument/formatting".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "pattern": "**/*.nomatch" }],
+ })),
+ }],
},
- message: "error 2 hint 1".to_string(),
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ project
+ .update(cx, |project, cx| {
+ project.format(
+ HashSet::from_iter([buffer.clone()]),
+ project::lsp_store::LspFormatTarget::Buffers,
+ false,
+ project::lsp_store::FormatTrigger::Manual,
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+ assert_eq!(
+ format_request_count.load(atomic::Ordering::SeqCst),
+ 1,
+ "expected a pattern-only filter to fail open and route the formatting request",
+ );
+}
+
+#[gpui::test]
+async fn test_dynamic_formatting_registration_with_empty_selector_matches_nothing(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx);
+ cx.update(|cx| {
+ SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, |settings| {
+ settings.project.all_languages.defaults.formatter = Some(FormatterList::Single(
+ Formatter::LanguageServer(settings::LanguageServerFormatterSpecifier::Current),
+ ));
+ });
+ });
+ });
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(path!("/dir"), json!({ "a.rs": "let value = 1;" }))
+ .await;
+
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+ let mut fake_language_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities::default(),
+ ..FakeLspAdapter::default()
},
- lsp::DiagnosticRelatedInformation {
- location: lsp::Location {
- uri: buffer_uri.clone(),
- range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
+ );
+
+ let (buffer, _handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/a.rs"), cx)
+ })
+ .await
+ .unwrap();
+ let fake_server = fake_language_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+
+ let format_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _format_requests = fake_server.set_request_handler::<lsp::request::Formatting, _, _>({
+ let format_request_count = format_request_count.clone();
+ move |_, _| {
+ format_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "empty-selector-formatting".to_string(),
+ method: "textDocument/formatting".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [],
+ })),
+ }],
},
- message: "error 2 hint 2".to_string(),
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ project
+ .update(cx, |project, cx| {
+ project.format(
+ HashSet::from_iter([buffer.clone()]),
+ project::lsp_store::LspFormatTarget::Buffers,
+ false,
+ project::lsp_store::FormatTrigger::Manual,
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+ assert_eq!(
+ format_request_count.load(atomic::Ordering::SeqCst),
+ 0,
+ "expected an empty document selector to match no buffers",
+ );
+}
+
+#[gpui::test]
+async fn test_dynamic_formatting_registration_honors_language_selector(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx);
+ cx.update(|cx| {
+ SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, |settings| {
+ settings.project.all_languages.defaults.formatter = Some(FormatterList::Single(
+ Formatter::LanguageServer(settings::LanguageServerFormatterSpecifier::Current),
+ ));
+ });
+ });
+ });
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(path!("/dir"), json!({ "a.rs": "let value = 1;" }))
+ .await;
+
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+ let mut fake_language_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities::default(),
+ ..FakeLspAdapter::default()
},
- ]);
- let error_1_hint_related_information: Arc<[lsp::DiagnosticRelatedInformation]> =
- Arc::from([lsp::DiagnosticRelatedInformation {
- location: lsp::Location {
- uri: buffer_uri.clone(),
- range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
- },
- message: "original diagnostic".to_string(),
- }]);
- let error_2_hint_related_information: Arc<[lsp::DiagnosticRelatedInformation]> =
- Arc::from([lsp::DiagnosticRelatedInformation {
- location: lsp::Location {
- uri: buffer_uri.clone(),
- range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
- },
- message: "original diagnostic".to_string(),
- }]);
- let message = lsp::PublishDiagnosticsParams {
- uri: buffer_uri,
- diagnostics: vec![
- lsp::Diagnostic {
- range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
- severity: Some(DiagnosticSeverity::WARNING),
- message: lsp::DiagnosticMessage::from("error 1"),
- related_information: Some(error_1_related_information.to_vec()),
- ..Default::default()
- },
- lsp::Diagnostic {
- range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
- severity: Some(DiagnosticSeverity::HINT),
- message: lsp::DiagnosticMessage::from("error 1 hint 1"),
- related_information: Some(error_1_hint_related_information.to_vec()),
- ..Default::default()
- },
- lsp::Diagnostic {
- range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
- severity: Some(DiagnosticSeverity::ERROR),
- message: lsp::DiagnosticMessage::from("error 2"),
- related_information: Some(error_2_related_information.to_vec()),
- ..Default::default()
- },
- lsp::Diagnostic {
- range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
- severity: Some(DiagnosticSeverity::HINT),
- message: lsp::DiagnosticMessage::from("error 2 hint 1"),
- related_information: Some(error_2_hint_related_information.to_vec()),
- ..Default::default()
+ );
+
+ let (buffer, _handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/a.rs"), cx)
+ })
+ .await
+ .unwrap();
+ let fake_server = fake_language_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+
+ let format_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _format_requests = fake_server.set_request_handler::<lsp::request::Formatting, _, _>({
+ let format_request_count = format_request_count.clone();
+ move |_, _| {
+ format_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+ let format_buffer = |cx: &mut gpui::TestAppContext| {
+ project.update(cx, |project, cx| {
+ project.format(
+ HashSet::from_iter([buffer.clone()]),
+ project::lsp_store::LspFormatTarget::Buffers,
+ false,
+ project::lsp_store::FormatTrigger::Manual,
+ cx,
+ )
+ })
+ };
+
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "plaintext-formatting".to_string(),
+ method: "textDocument/formatting".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "plaintext" }],
+ })),
+ }],
},
- lsp::Diagnostic {
- range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
- severity: Some(DiagnosticSeverity::HINT),
- message: lsp::DiagnosticMessage::from("error 2 hint 2"),
- related_information: Some(error_2_hint_related_information.to_vec()),
- ..Default::default()
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ format_buffer(cx).await.unwrap();
+ assert_eq!(
+ format_request_count.load(atomic::Ordering::SeqCst),
+ 0,
+ "expected no formatting request for a registration with a different language filter",
+ );
+
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "rust-formatting".to_string(),
+ method: "textDocument/formatting".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "rust" }],
+ })),
+ }],
},
- ],
- version: None,
- };
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ format_buffer(cx).await.unwrap();
+ assert_eq!(
+ format_request_count.load(atomic::Ordering::SeqCst),
+ 1,
+ "expected a formatting request once a registration with the buffer's language id exists",
+ );
+}
+
+#[gpui::test]
+async fn test_dynamic_range_formatting_registrations_honor_document_selectors(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx);
+ cx.update(|cx| {
+ SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, |settings| {
+ settings.project.all_languages.defaults.formatter = Some(FormatterList::Single(
+ Formatter::LanguageServer(settings::LanguageServerFormatterSpecifier::Current),
+ ));
+ });
+ });
+ });
- lsp_store
- .update(cx, |lsp_store, cx| {
- lsp_store.update_diagnostics(
- LanguageServerId(0),
- message,
- None,
- DiagnosticSourceKind::Pushed,
- &[],
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(path!("/dir"), json!({ "a.rs": "let value = 1;" }))
+ .await;
+
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+ let mut fake_language_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities::default(),
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ let (buffer, _handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/a.rs"), cx)
+ })
+ .await
+ .unwrap();
+ let fake_server = fake_language_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+
+ let range_format_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _range_format_requests = fake_server
+ .set_request_handler::<lsp::request::RangeFormatting, _, _>({
+ let range_format_request_count = range_format_request_count.clone();
+ move |_, _| {
+ range_format_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(None) }
+ }
+ });
+ let (buffer_id, range) = buffer.read_with(cx, |buffer, _| {
+ (
+ buffer.remote_id(),
+ buffer.anchor_before(0)..buffer.anchor_after(buffer.len()),
+ )
+ });
+ let format_ranges = |cx: &mut gpui::TestAppContext| {
+ let ranges = std::collections::BTreeMap::from_iter([(buffer_id, vec![range.clone()])]);
+ project.update(cx, |project, cx| {
+ project.format(
+ HashSet::from_iter([buffer.clone()]),
+ project::lsp_store::LspFormatTarget::Ranges(ranges),
+ false,
+ project::lsp_store::FormatTrigger::Manual,
cx,
)
})
+ };
+
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "untitled-range-formatting".to_string(),
+ method: "textDocument/rangeFormatting".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "untitled" }],
+ })),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
.unwrap();
- let buffer = buffer.update(cx, |buffer, _| buffer.snapshot());
+ cx.executor().run_until_parked();
+ format_ranges(cx).await.unwrap();
assert_eq!(
- buffer
- .diagnostic_entries_in_range(0..buffer.len(), false)
- .map(|entry| entry.clone().map_coordinates(|range| {
- range.start.to_point(&buffer)..range.end.to_point(&buffer)
- }))
- .collect::<Vec<_>>(),
- &[
- DiagnosticEntry {
- range: Point::new(1, 8)..Point::new(1, 9),
- related_information: expected_related_information(&error_1_related_information),
- diagnostic: Diagnostic {
- severity: DiagnosticSeverity::WARNING,
- message: "error 1".into(),
- group_id: 1,
- is_primary: true,
- source_kind: DiagnosticSourceKind::Pushed,
- ..Diagnostic::default()
- },
- },
- DiagnosticEntry {
- range: Point::new(1, 8)..Point::new(1, 9),
- related_information: expected_related_information(
- &error_1_hint_related_information
- ),
- diagnostic: Diagnostic {
- severity: DiagnosticSeverity::HINT,
- message: "error 1 hint 1".into(),
- group_id: 1,
- is_primary: false,
- source_kind: DiagnosticSourceKind::Pushed,
- ..Diagnostic::default()
- },
- },
- DiagnosticEntry {
- range: Point::new(1, 13)..Point::new(1, 15),
- related_information: expected_related_information(
- &error_2_hint_related_information
- ),
- diagnostic: Diagnostic {
- severity: DiagnosticSeverity::HINT,
- message: "error 2 hint 1".into(),
- group_id: 0,
- is_primary: false,
- source_kind: DiagnosticSourceKind::Pushed,
- ..Diagnostic::default()
- },
- },
- DiagnosticEntry {
- range: Point::new(1, 13)..Point::new(1, 15),
- related_information: expected_related_information(
- &error_2_hint_related_information
- ),
- diagnostic: Diagnostic {
- severity: DiagnosticSeverity::HINT,
- message: "error 2 hint 2".into(),
- group_id: 0,
- is_primary: false,
- source_kind: DiagnosticSourceKind::Pushed,
- ..Diagnostic::default()
- },
- },
- DiagnosticEntry {
- range: Point::new(2, 8)..Point::new(2, 17),
- related_information: expected_related_information(&error_2_related_information),
- diagnostic: Diagnostic {
- severity: DiagnosticSeverity::ERROR,
- message: "error 2".into(),
- group_id: 0,
- is_primary: true,
- source_kind: DiagnosticSourceKind::Pushed,
- ..Diagnostic::default()
- },
- }
- ]
+ range_format_request_count.load(atomic::Ordering::SeqCst),
+ 0,
+ "expected no range formatting request for a buffer outside the registration's selector",
);
- assert_eq!(
- buffer.diagnostic_group::<Point>(0).collect::<Vec<_>>(),
- &[
- DiagnosticEntry {
- range: Point::new(1, 13)..Point::new(1, 15),
- related_information: expected_related_information(
- &error_2_hint_related_information
- ),
- diagnostic: Diagnostic {
- severity: DiagnosticSeverity::HINT,
- message: "error 2 hint 1".into(),
- group_id: 0,
- is_primary: false,
- source_kind: DiagnosticSourceKind::Pushed,
- ..Diagnostic::default()
- },
- },
- DiagnosticEntry {
- range: Point::new(1, 13)..Point::new(1, 15),
- related_information: expected_related_information(
- &error_2_hint_related_information
- ),
- diagnostic: Diagnostic {
- severity: DiagnosticSeverity::HINT,
- message: "error 2 hint 2".into(),
- group_id: 0,
- is_primary: false,
- source_kind: DiagnosticSourceKind::Pushed,
- ..Diagnostic::default()
- },
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "file-range-formatting".to_string(),
+ method: "textDocument/rangeFormatting".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "file" }],
+ })),
+ }],
},
- DiagnosticEntry {
- range: Point::new(2, 8)..Point::new(2, 17),
- related_information: expected_related_information(&error_2_related_information),
- diagnostic: Diagnostic {
- severity: DiagnosticSeverity::ERROR,
- message: "error 2".into(),
- group_id: 0,
- is_primary: true,
- source_kind: DiagnosticSourceKind::Pushed,
- ..Diagnostic::default()
- },
- }
- ]
- );
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+ format_ranges(cx).await.unwrap();
assert_eq!(
- buffer.diagnostic_group::<Point>(1).collect::<Vec<_>>(),
- &[
- DiagnosticEntry {
- range: Point::new(1, 8)..Point::new(1, 9),
- related_information: expected_related_information(&error_1_related_information),
- diagnostic: Diagnostic {
- severity: DiagnosticSeverity::WARNING,
- message: "error 1".into(),
- group_id: 1,
- is_primary: true,
- source_kind: DiagnosticSourceKind::Pushed,
- ..Diagnostic::default()
- },
- },
- DiagnosticEntry {
- range: Point::new(1, 8)..Point::new(1, 9),
- related_information: expected_related_information(
- &error_1_hint_related_information
- ),
- diagnostic: Diagnostic {
- severity: DiagnosticSeverity::HINT,
- message: "error 1 hint 1".into(),
- group_id: 1,
- is_primary: false,
- source_kind: DiagnosticSourceKind::Pushed,
- ..Diagnostic::default()
- },
- },
- ]
+ range_format_request_count.load(atomic::Ordering::SeqCst),
+ 1,
+ "expected a range formatting request once a matching registration exists",
);
}
#[gpui::test]
-async fn test_lsp_rename_notifications(cx: &mut gpui::TestAppContext) {
+async fn test_dynamic_on_type_formatting_registration_routes_matching_trigger(
+ cx: &mut gpui::TestAppContext,
+) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
@@ -9292,56 +11204,22 @@ async fn test_lsp_rename_notifications(cx: &mut gpui::TestAppContext) {
path!("/dir"),
json!({
"one.rs": "const ONE: usize = 1;",
- "two": {
- "two.rs": "const TWO: usize = one::ONE + one::ONE;"
- }
-
}),
)
.await;
- let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
- let language_registry = project.read_with(cx, |project, _| project.languages().clone());
- language_registry.add(rust_lang());
- let watched_paths = lsp::FileOperationRegistrationOptions {
- filters: vec![
- FileOperationFilter {
- scheme: Some("file".to_owned()),
- pattern: lsp::FileOperationPattern {
- glob: "**/*.rs".to_owned(),
- matches: Some(lsp::FileOperationPatternKind::File),
- options: None,
- },
- },
- FileOperationFilter {
- scheme: Some("file".to_owned()),
- pattern: lsp::FileOperationPattern {
- glob: "**/**".to_owned(),
- matches: Some(lsp::FileOperationPatternKind::Folder),
- options: None,
- },
- },
- ],
- };
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
let mut fake_servers = language_registry.register_fake_lsp(
"Rust",
FakeLspAdapter {
- capabilities: lsp::ServerCapabilities {
- workspace: Some(lsp::WorkspaceServerCapabilities {
- workspace_folders: None,
- file_operations: Some(lsp::WorkspaceFileOperationsServerCapabilities {
- did_rename: Some(watched_paths.clone()),
- will_rename: Some(watched_paths),
- ..Default::default()
- }),
- }),
- ..Default::default()
- },
+ capabilities: lsp::ServerCapabilities::default(),
..Default::default()
},
);
- let _ = project
+ let (buffer, _handle) = project
.update(cx, |project, cx| {
project.open_local_buffer_with_lsp(path!("/dir/one.rs"), cx)
})
@@ -9350,74 +11228,59 @@ async fn test_lsp_rename_notifications(cx: &mut gpui::TestAppContext) {
let fake_server = fake_servers.next().await.unwrap();
cx.executor().run_until_parked();
- let response = project.update(cx, |project, cx| {
- let worktree = project.worktrees(cx).next().unwrap();
- let entry = worktree
- .read(cx)
- .entry_for_path(rel_path("one.rs"))
- .unwrap();
- project.rename_entry(
- entry.id,
- (worktree.read(cx).id(), rel_path("three.rs")).into(),
- cx,
- )
- });
- let expected_edit = lsp::WorkspaceEdit {
- changes: None,
- document_changes: Some(DocumentChanges::Edits({
- vec![TextDocumentEdit {
- edits: vec![lsp::Edit::Plain(lsp::TextEdit {
- range: lsp::Range {
- start: lsp::Position {
- line: 0,
- character: 1,
- },
- end: lsp::Position {
- line: 0,
- character: 3,
- },
- },
- new_text: "This is not a drill".to_owned(),
- })],
- text_document: lsp::OptionalVersionedTextDocumentIdentifier {
- uri: Uri::from_str(uri!("file:///dir/two/two.rs")).unwrap(),
- version: Some(1337),
- },
- }]
- })),
- change_annotations: None,
- };
- let resolved_workspace_edit = Arc::new(OnceLock::new());
+
fake_server
- .set_request_handler::<WillRenameFiles, _, _>({
- let resolved_workspace_edit = resolved_workspace_edit.clone();
- let expected_edit = expected_edit.clone();
- move |params, _| {
- let resolved_workspace_edit = resolved_workspace_edit.clone();
- let expected_edit = expected_edit.clone();
- async move {
- assert_eq!(params.files.len(), 1);
- assert_eq!(params.files[0].old_uri, uri!("file:///dir/one.rs"));
- assert_eq!(params.files[0].new_uri, uri!("file:///dir/three.rs"));
- resolved_workspace_edit.set(expected_edit.clone()).unwrap();
- Ok(Some(expected_edit))
- }
- }
- })
- .next()
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![
+ lsp::Registration {
+ id: "file-on-type-formatting".to_string(),
+ method: "textDocument/onTypeFormatting".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "file" }],
+ "firstTriggerCharacter": ";",
+ })),
+ },
+ lsp::Registration {
+ id: "untitled-on-type-formatting".to_string(),
+ method: "textDocument/onTypeFormatting".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "rust", "scheme": "untitled" }],
+ "firstTriggerCharacter": ":",
+ })),
+ },
+ ],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
.await
+ .into_response()
.unwrap();
- let _ = response.await.unwrap();
- fake_server
- .handle_notification::<DidRenameFiles, _>(|params, _| {
- assert_eq!(params.files.len(), 1);
- assert_eq!(params.files[0].old_uri, uri!("file:///dir/one.rs"));
- assert_eq!(params.files[0].new_uri, uri!("file:///dir/three.rs"));
+ cx.executor().run_until_parked();
+
+ let on_type_format_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _on_type_format_requests = fake_server
+ .set_request_handler::<lsp::request::OnTypeFormatting, _, _>({
+ let on_type_format_request_count = on_type_format_request_count.clone();
+ move |params, _| {
+ on_type_format_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ assert_eq!(params.ch, ";");
+ async move { Ok(None) }
+ }
+ });
+
+ let on_type_format = project
+ .update(cx, |project, cx| {
+ project.on_type_format(buffer.clone(), 7, ";".to_string(), false, cx)
})
- .next()
- .await
- .unwrap();
- assert_eq!(resolved_workspace_edit.get(), Some(&expected_edit));
+ .expect("matching dynamic registration should support on-type formatting");
+ let response = on_type_format.await.unwrap();
+
+ assert!(response.is_none());
+ assert_eq!(
+ on_type_format_request_count.load(atomic::Ordering::SeqCst),
+ 1
+ );
}
#[gpui::test]
@@ -9482,14 +11345,24 @@ async fn test_rename(cx: &mut gpui::TestAppContext) {
.await
.unwrap();
let response = response.await.unwrap();
- let PrepareRenameResponse::Success(range) = response else {
+ let PrepareRenameResponse::Success {
+ range,
+ language_server_id,
+ } = response
+ else {
panic!("{:?}", response);
};
let range = buffer.update(cx, |buffer, _| range.to_offset(buffer));
assert_eq!(range, 6..9);
let response = project.update(cx, |project, cx| {
- project.perform_rename(buffer.clone(), 7, "THREE".to_string(), cx)
+ project.perform_rename(
+ buffer.clone(),
+ 7,
+ "THREE".to_string(),
+ language_server_id,
+ cx,
+ )
});
fake_server
.set_request_handler::<lsp::request::Rename, _, _>(|params, _| async move {
@@ -9607,7 +11480,7 @@ async fn test_rename_that_also_renames_file(cx: &mut gpui::TestAppContext) {
cx.executor().run_until_parked();
let response = project.update(cx, |project, cx| {
- project.perform_rename(buffer.clone(), 7, "THREE".to_string(), cx)
+ project.perform_rename(buffer.clone(), 7, "THREE".to_string(), None, cx)
});
fake_server
.set_request_handler::<lsp::request::Rename, _, _>(|_params, _| async move {
@@ -11878,6 +13751,232 @@ async fn test_code_actions_with_related_information_from_multiple_servers(
assert!(code_actions_task.await.unwrap().unwrap().is_empty());
}
+#[gpui::test]
+async fn test_dynamic_code_action_registrations_use_matching_options(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(path!("/dir"), json!({ "a.ts": "a" })).await;
+
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(typescript_lang());
+ let mut fake_language_servers = language_registry.register_fake_lsp(
+ "TypeScript",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities {
+ text_document_sync: Some(lsp::TextDocumentSyncCapability::Options(
+ lsp::TextDocumentSyncOptions {
+ open_close: Some(true),
+ change: Some(lsp::TextDocumentSyncKind::FULL),
+ ..lsp::TextDocumentSyncOptions::default()
+ },
+ )),
+ ..lsp::ServerCapabilities::default()
+ },
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ let (buffer, _handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/a.ts"), cx)
+ })
+ .await
+ .unwrap();
+ let fake_server = fake_language_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![
+ lsp::Registration {
+ id: "file-code-actions".to_string(),
+ method: "textDocument/codeAction".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "typescript", "scheme": "file" }],
+ "codeActionKinds": [CodeActionKind::SOURCE_ORGANIZE_IMPORTS.as_str()],
+ })),
+ },
+ lsp::Registration {
+ id: "untitled-code-actions".to_string(),
+ method: "textDocument/codeAction".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "typescript", "scheme": "untitled" }],
+ "codeActionKinds": [CodeActionKind::SOURCE_FIX_ALL.as_str()],
+ })),
+ },
+ ],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ let code_action_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let mut code_action_requests = fake_server
+ .set_request_handler::<lsp::request::CodeActionRequest, _, _>({
+ let code_action_request_count = code_action_request_count.clone();
+ move |params, _| {
+ code_action_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ assert_eq!(
+ params.context.only,
+ Some(vec![CodeActionKind::SOURCE_ORGANIZE_IMPORTS])
+ );
+ async {
+ Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(
+ lsp::CodeAction {
+ title: "organize imports".to_string(),
+ kind: Some(CodeActionKind::SOURCE_ORGANIZE_IMPORTS),
+ ..lsp::CodeAction::default()
+ },
+ )]))
+ }
+ }
+ });
+
+ let code_actions = project.update(cx, |project, cx| {
+ project.code_actions(
+ &buffer,
+ 0..buffer.read(cx).len(),
+ Some(vec![CodeActionKind::SOURCE_ORGANIZE_IMPORTS]),
+ cx,
+ )
+ });
+ code_action_requests
+ .next()
+ .await
+ .expect("The matching code action registration should receive the request");
+ let code_actions = code_actions.await.unwrap().unwrap();
+
+ assert_eq!(code_action_request_count.load(atomic::Ordering::SeqCst), 1);
+ assert_eq!(code_actions.len(), 1);
+}
+
+#[gpui::test]
+async fn test_format_code_actions_skip_resolve_from_non_matching_registration(
+ cx: &mut gpui::TestAppContext,
+) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/dir"),
+ json!({
+ "a.ts": "a",
+ }),
+ )
+ .await;
+
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(typescript_lang());
+ let mut fake_language_servers = language_registry.register_fake_lsp(
+ "TypeScript",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities {
+ code_action_provider: Some(lsp::CodeActionProviderCapability::Simple(true)),
+ ..lsp::ServerCapabilities::default()
+ },
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ let (buffer, _handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/a.ts"), cx)
+ })
+ .await
+ .unwrap();
+ let fake_server = fake_language_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+
+ fake_server
+ .request::<lsp::request::RegisterCapability>(
+ lsp::RegistrationParams {
+ registrations: vec![lsp::Registration {
+ id: "untitled-code-actions".to_string(),
+ method: "textDocument/codeAction".to_string(),
+ register_options: Some(json!({
+ "documentSelector": [{ "language": "typescript", "scheme": "untitled" }],
+ "codeActionKinds": [CodeActionKind::SOURCE_ORGANIZE_IMPORTS.as_str()],
+ "resolveProvider": true,
+ })),
+ }],
+ },
+ DEFAULT_LSP_REQUEST_TIMEOUT,
+ )
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().run_until_parked();
+
+ let _code_action_requests = fake_server
+ .set_request_handler::<lsp::request::CodeActionRequest, _, _>(|params, _| async move {
+ Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(
+ lsp::CodeAction {
+ title: "organize imports".to_string(),
+ kind: Some(CodeActionKind::SOURCE_ORGANIZE_IMPORTS),
+ data: Some(json!({ "marker": true })),
+ edit: Some(lsp::WorkspaceEdit {
+ changes: Some(
+ [(
+ params.text_document.uri,
+ vec![lsp::TextEdit::new(
+ lsp::Range::new(
+ lsp::Position::new(0, 0),
+ lsp::Position::new(0, 0),
+ ),
+ "organized ".to_string(),
+ )],
+ )]
+ .into_iter()
+ .collect(),
+ ),
+ ..lsp::WorkspaceEdit::default()
+ }),
+ ..lsp::CodeAction::default()
+ },
+ )]))
+ });
+ let resolve_request_count = Arc::new(atomic::AtomicUsize::new(0));
+ let _resolve_requests = fake_server
+ .set_request_handler::<lsp::request::CodeActionResolveRequest, _, _>({
+ let resolve_request_count = resolve_request_count.clone();
+ move |action, _| {
+ resolve_request_count.fetch_add(1, atomic::Ordering::SeqCst);
+ async move { Ok(action) }
+ }
+ });
+
+ project
+ .update(cx, |project, cx| {
+ project.apply_code_action_kind(
+ HashSet::from_iter([buffer.clone()]),
+ CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
+ true,
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(
+ resolve_request_count.load(atomic::Ordering::SeqCst),
+ 0,
+ "expected no resolve request when the resolve capability comes from a non-matching registration",
+ );
+ buffer.read_with(cx, |buffer, _| {
+ assert_eq!(buffer.text(), "organized a");
+ });
+}
+
#[gpui::test]
async fn test_code_actions_without_requested_kinds_do_not_send_only_filter(
cx: &mut gpui::TestAppContext,
diff --git a/crates/proto/proto/lsp.proto b/crates/proto/proto/lsp.proto
index cf7080a7191..e28726aba33 100644
--- a/crates/proto/proto/lsp.proto
+++ b/crates/proto/proto/lsp.proto
@@ -507,6 +507,7 @@ message PrepareRenameResponse {
Anchor end = 3;
repeated VectorClockEntry version = 4;
bool only_unprepared_rename_supported = 5;
+ optional uint64 language_server_id = 6;
}
message PerformRename {
@@ -515,6 +516,7 @@ message PerformRename {
Anchor position = 3;
string new_name = 4;
repeated VectorClockEntry version = 5;
+ optional uint64 language_server_id = 6;
}
message OnTypeFormatting {
diff --git a/crates/remote_server/src/remote_editing_tests.rs b/crates/remote_server/src/remote_editing_tests.rs
index 2aaf99b9b4a..ca690686504 100644
--- a/crates/remote_server/src/remote_editing_tests.rs
+++ b/crates/remote_server/src/remote_editing_tests.rs
@@ -1111,7 +1111,7 @@ async fn test_remote_lsp(cx: &mut TestAppContext, server_cx: &mut TestAppContext
project
.update(cx, |project, cx| {
- project.perform_rename(buffer.clone(), 3, "two".to_string(), cx)
+ project.perform_rename(buffer.clone(), 3, "two".to_string(), None, cx)
})
.await
.unwrap();