project: Match document filter patterns in dynamic registrations (#65252)

## Summary

Follow-up to #59243, which made dynamically registered capabilities
honor the `language` and `scheme` of their document selectors, but left
`pattern` matching fail-open. A registration such as `{ "language":
"toml", "pattern": "**/Project.toml" }` therefore still applied to every
TOML document the server had opened, and a pattern-only filter applied
to every document.

This matches `pattern` against the document's path:

- String patterns are matched against the absolute path. As in the LSP
glob syntax, `*` and `?` do not match path separators.
- Relative patterns are matched against the path relative to their base
URI, and Zed now advertises the
`textDocument.filters.relativePatternSupport` client capability.
- Documents without a file system path never match a `pattern` filter.
Contexts that stand for a whole language, like the semantic token legend
lookup, and guest buffers whose path is unknown keep not evaluating
patterns.
- Registrations whose patterns are not valid globs are rejected when
they are registered.

LSP 3.18 changed `TextDocumentFilter.pattern` from a string to a
`GlobPattern`, so that it can also be a relative pattern. ~~This PR
depends on zed-industries/lsp-types#16, which updates the type and adds
the client capability. I'd like to merge this together with that
upstream change: `Cargo.toml` currently points at the commit of
zed-industries/lsp-types#16 on my fork, and I will switch it to the
`zed-industries/lsp-types` revision once that PR is merged.~~

**Update:** zed-industries/lsp-types#16 has been merged, and
`Cargo.toml` now points at its `zed-industries/lsp-types` revision
(zed-industries/lsp-types@82d7fc66eb).

## Testing

- Added unit tests for matching string patterns, wildcards across path
separators, and relative patterns.
- Added an integration test that a pattern-scoped completion
registration only applies to matching buffers, and that a registration
with an invalid pattern is rejected.
- Updated
`test_dynamic_formatting_registration_with_pattern_only_selector`, which
asserted the fail-open behavior left by #59243.

## Self-review

- [x] I've reviewed my diff for quality, security, reliability, and
performance.
- [x] UI changes follow the
[checklist](https://zed.dev/docs/development/ui-checklist).
- [x] Tests cover the new or changed behavior.

Release Notes:

- Fixed language servers' dynamically registered capabilities applying
to files outside of the `pattern` of their document selector.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shuhei Kadowaki
2026-10-21 17:41:09 +00:00
committed by GitHub
parent 59dd60d4dd
commit cb593458e1
9 changed files with 1778 additions and 130 deletions
Generated
+1 -1
View File
@@ -10480,7 +10480,7 @@ dependencies = [
[[package]]
name = "lsp-types"
version = "0.95.1"
source = "git+https://github.com/zed-industries/lsp-types?rev=f1783e63a7f4eb4397bf51d4148b4895a1f7ab16#f1783e63a7f4eb4397bf51d4148b4895a1f7ab16"
source = "git+https://github.com/zed-industries/lsp-types?rev=82d7fc66ebdfabcfeb26ba16bbed9f3d26211fc3#82d7fc66ebdfabcfeb26ba16bbed9f3d26211fc3"
dependencies = [
"bitflags 1.3.2",
"serde",
+1 -1
View File
@@ -688,7 +688,7 @@ linkify = "0.10.0"
livekit = { version = "0.7.32", features = ["tokio", "rustls-tls-native-roots"] }
log = { version = "0.4", default-features = false, features = ["std"] }
lru = "0.16"
lsp-types = { git = "https://github.com/zed-industries/lsp-types", rev = "f1783e63a7f4eb4397bf51d4148b4895a1f7ab16" }
lsp-types = { git = "https://github.com/zed-industries/lsp-types", rev = "82d7fc66ebdfabcfeb26ba16bbed9f3d26211fc3" }
mach2 = "0.6"
markup5ever_rcdom = "0.39"
mdbook = { version = "=0.4.40", default-features = false, features = ["search"] }
@@ -2126,7 +2126,12 @@ async fn test_collaborating_with_code_lens_resolve(
.unwrap()
.downcast::<Editor>()
.unwrap();
let fake_language_server = fake_language_servers.next().await.unwrap();
let mut fake_language_server = fake_language_servers.next().await.unwrap();
// Fake servers are handed out before they are initialized, while registrations need a
// running server, which the buffer being opened in it ensures.
fake_language_server
.receive_notification::<lsp::notification::DidOpenTextDocument>()
.await;
fake_language_server
.request::<lsp::request::RegisterCapability>(
lsp::RegistrationParams {
+3
View File
@@ -1134,6 +1134,9 @@ impl LanguageServer {
]),
}),
}),
filters: Some(TextDocumentFilterClientCapabilities {
relative_pattern_support: Some(true),
}),
..TextDocumentClientCapabilities::default()
}),
experimental: Some(json!({
File diff suppressed because it is too large Load Diff
@@ -15,7 +15,7 @@ use lsp::{
};
use crate::lsp_store::{
LanguageServerState, LspStore, RenamePathsWatchedForServer,
CompiledDocumentSelector, LanguageServerState, LspStore, RenamePathsWatchedForServer,
completion_trigger_characters_for_buffer, lsp_workspace_diagnostics_refresh,
};
@@ -55,7 +55,7 @@ impl CapabilityRegistrationChange {
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub(super) struct DynamicTextDocumentRegistration {
pub(super) document_selector: Option<lsp::DocumentSelector>,
pub(super) document_selector: Option<CompiledDocumentSelector>,
pub(super) server_capabilities: lsp::ServerCapabilities,
}
@@ -83,6 +83,9 @@ impl LspStore {
cx: &mut Context<Self>,
capability_of: impl Fn(&mut lsp::ServerCapabilities) -> &mut Option<T>,
) -> anyhow::Result<CapabilityRegistrationChange> {
let document_selector = document_selector
.map(CompiledDocumentSelector::new)
.transpose()?;
let server_id = server.server_id();
let local = self
.as_local_mut()
@@ -230,6 +233,9 @@ impl LspStore {
sync_options: lsp::TextDocumentSyncOptions,
cx: &mut Context<Self>,
) -> anyhow::Result<()> {
let document_selector = document_selector
.map(CompiledDocumentSelector::new)
.transpose()?;
let local = self
.as_local_mut()
.context("Expected LSP Store to be local")?;
@@ -476,7 +482,7 @@ impl LspStore {
for handle in buffers_with_language_server {
handle.update(cx, |buffer, cx| {
let triggers =
completion_trigger_characters_for_buffer(local, server_id, adapter, buffer);
completion_trigger_characters_for_buffer(local, server_id, adapter, buffer, cx);
buffer.set_completion_triggers(server_id, triggers, cx);
});
}
@@ -491,7 +497,7 @@ impl LspStore {
let server = self
.language_server_for_id(server_id)
.with_context(|| format!("no server {server_id} found"))?;
for reg in params.registrations {
let mut register_capability = |reg: lsp::Registration| -> Result<()> {
match reg.method.as_str() {
"workspace/didChangeWatchedFiles" => {
if let Some(options) = reg.register_options {
@@ -1035,6 +1041,26 @@ impl LspStore {
}
_ => log::warn!("unhandled capability registration: {reg:?}"),
}
Ok(())
};
// Keep valid siblings even when a batch is partially invalid, but report its failures
// to the server rather than acknowledging the whole batch as successful.
let mut registration_errors = Vec::new();
for registration in params.registrations {
let method = registration.method.clone();
let registration_id = registration.id.clone();
if let Err(error) = register_capability(registration) {
registration_errors.push(format!(
"server {server_id}, method {method}, registration {registration_id:?}: {error:#}"
));
}
}
if !registration_errors.is_empty() {
anyhow::bail!(
"Failed to register server capabilities:\n{}",
registration_errors.join("\n")
);
}
Ok(())
@@ -27,8 +27,8 @@ use crate::{
SemanticTokensResponse,
},
lsp_store::{
LanguageServerState, document_selector_context_for_language, document_selector_matches,
missing_servers_to_query,
DocumentSelectorPath, LanguageServerState, document_selector_context_for_language,
document_selector_matches, missing_servers_to_query,
},
project_settings::ProjectSettings,
};
@@ -576,7 +576,11 @@ impl LspStore {
}
if let Some(initial_capabilities) = self.lsp_server_initial_capabilities.get(&server_id) {
let context = self.remote_document_selector_context(server_id, language);
let context = self.remote_document_selector_context(
server_id,
language,
DocumentSelectorPath::Unknown,
);
if let Some(registrations) = self
.lsp_server_text_document_registrations
.get(&server_id)
@@ -3040,6 +3040,431 @@ async fn edit_and_receive_change(
(params.text_document.uri, change.range.is_some())
}
#[gpui::test]
async fn test_registration_pattern_scopes_capability_to_matching_documents(
cx: &mut gpui::TestAppContext,
) {
init_test(cx);
let (project, fake_server) =
setup_dynamic_registration_test(cx, lsp::ServerCapabilities::default()).await;
let fs = project.read_with(cx, |project, _| project.fs().as_fake());
fs.insert_tree(path!("/the-root"), json!({ "b.rs": "" }))
.await;
let method = "textDocument/completion";
let (buffer_a, _lsp_handle_a) = project
.update(cx, |project, cx| {
project.open_local_buffer_with_lsp(path!("/the-root/a.rs"), cx)
})
.await
.unwrap();
let (buffer_b, _lsp_handle_b) = project
.update(cx, |project, cx| {
project.open_local_buffer_with_lsp(path!("/the-root/b.rs"), cx)
})
.await
.unwrap();
let buffer_triggers = |buffer: &Entity<Buffer>, cx: &mut gpui::TestAppContext| {
buffer.read_with(cx, |buffer, _| buffer.completion_triggers().clone())
};
let error = register_capabilities(
&fake_server,
vec![lsp::Registration {
id: "completion-invalid-pattern".to_string(),
method: method.to_string(),
register_options: Some(json!({
"documentSelector": [{ "language": "rust", "pattern": "**/[a.rs" }],
"triggerCharacters": [":"],
})),
}],
)
.await
.expect_err("an invalid selector pattern should produce an error response");
assert!(
error
.to_string()
.contains("invalid document filter pattern")
);
cx.executor().run_until_parked();
assert_eq!(
server_capabilities(&project, fake_server.server.server_id(), cx).completion_provider,
None,
"expected a registration with an invalid pattern to be rejected",
);
register_capability(
&fake_server,
method,
"completion-a",
Some(json!({
"documentSelector": [{ "language": "rust", "pattern": "**/a.rs" }],
"triggerCharacters": ["."],
})),
)
.await;
cx.executor().run_until_parked();
assert_eq!(
buffer_triggers(&buffer_a, cx),
BTreeSet::from([".".to_string()]),
"expected the registration to apply to the document matching its pattern",
);
assert_eq!(
buffer_triggers(&buffer_b, cx),
BTreeSet::new(),
"expected the registration not to apply to a document outside its pattern",
);
}
#[gpui::test]
async fn test_registration_batch_applies_valid_siblings_and_reports_errors(
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 (buffer, _lsp_handle) = project
.update(cx, |project, cx| {
project.open_local_buffer_with_lsp(path!("/the-root/a.rs"), cx)
})
.await
.unwrap();
let (events, _subscription) = observe_refresh_events(&project, cx);
let mut registrations = vec![
lsp::Registration {
id: "hover-valid".to_string(),
method: "textDocument/hover".to_string(),
register_options: None,
},
lsp::Registration {
id: "completion-invalid".to_string(),
method: "textDocument/completion".to_string(),
register_options: Some(json!({
"documentSelector": [{ "language": "rust", "pattern": "**/[a.rs" }],
"triggerCharacters": ["."],
})),
},
lsp::Registration {
id: "formatting-valid".to_string(),
method: "textDocument/formatting".to_string(),
register_options: None,
},
lsp::Registration {
id: "code-lens-invalid".to_string(),
method: "textDocument/codeLens".to_string(),
register_options: Some(json!({
"documentSelector": [{ "language": "rust", "pattern": "**/[b.rs" }],
"resolveProvider": true,
})),
},
];
let error = register_capabilities(&fake_server, registrations.clone())
.await
.expect_err("a mixed registration batch should produce an error response")
.to_string();
for (method, registration_id, pattern) in [
("textDocument/completion", "completion-invalid", "**/[a.rs"),
("textDocument/codeLens", "code-lens-invalid", "**/[b.rs"),
] {
assert!(
error.contains(&format!(
"server {server_id}, method {method}, registration {registration_id:?}"
)),
"expected the failed registration's context in {error}",
);
assert!(
error.contains(pattern),
"expected the failed registration's pattern in {error}",
);
}
cx.executor().run_until_parked();
let capabilities = server_capabilities(&project, server_id, cx);
assert_eq!(
capabilities.hover_provider,
Some(lsp::HoverProviderCapability::Simple(true)),
);
assert_eq!(capabilities.completion_provider, None);
assert_eq!(
capabilities.document_formatting_provider,
Some(lsp::OneOf::Left(true)),
);
assert_eq!(capabilities.code_lens_provider, None);
buffer.read_with(cx, |buffer, _| {
assert!(buffer.completion_triggers().is_empty());
});
assert!(
events.lock().is_empty(),
"a failed registration must not trigger its refresh followup",
);
for registration in &mut registrations {
if let Some(options) = registration.register_options.as_mut() {
options["documentSelector"] = json!([{ "language": "rust", "pattern": "**/a.rs" }]);
}
}
register_capabilities(&fake_server, registrations)
.await
.expect("an all-valid registration batch should produce a success response");
cx.executor().run_until_parked();
let capabilities = server_capabilities(&project, server_id, cx);
assert_eq!(
capabilities.completion_provider,
Some(lsp::CompletionOptions {
trigger_characters: Some(vec![".".to_string()]),
..lsp::CompletionOptions::default()
}),
);
assert_eq!(
capabilities.code_lens_provider,
Some(lsp::CodeLensOptions {
resolve_provider: Some(true),
}),
);
buffer.read_with(cx, |buffer, _| {
assert_eq!(
buffer.completion_triggers(),
&BTreeSet::from([".".to_string()]),
);
});
assert_eq!(*events.lock(), vec![format!("code_lens({server_id})")]);
}
#[gpui::test]
async fn test_invalid_registration_pattern_preserves_previous_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 (buffer, _lsp_handle) = project
.update(cx, |project, cx| {
project.open_local_buffer_with_lsp(path!("/the-root/a.rs"), cx)
})
.await
.unwrap();
let method = "textDocument/completion";
let registration_id = "completion-a";
register_capability(
&fake_server,
method,
registration_id,
Some(json!({
"documentSelector": [{ "language": "rust", "pattern": "**/a.rs" }],
"triggerCharacters": ["."],
})),
)
.await;
cx.executor().run_until_parked();
let previous_capabilities = server_capabilities(&project, server_id, cx);
let error = register_capabilities(
&fake_server,
vec![lsp::Registration {
id: registration_id.to_string(),
method: method.to_string(),
register_options: Some(json!({
"documentSelector": [{ "language": "rust", "pattern": "**/[a.rs" }],
"triggerCharacters": [":"],
})),
}],
)
.await
.expect_err("an invalid replacement should produce an error response");
assert!(
error
.to_string()
.contains("invalid document filter pattern")
);
cx.executor().run_until_parked();
assert_eq!(
server_capabilities(&project, server_id, cx),
previous_capabilities,
);
buffer.read_with(cx, |buffer, _| {
assert_eq!(
buffer.completion_triggers(),
&BTreeSet::from([".".to_string()]),
);
});
let fs = project.read_with(cx, |project, _| project.fs().as_fake());
fs.insert_tree(
path!("/the-root"),
json!({ "nested": { "a.rs": "", "b.rs": "" } }),
)
.await;
for (path, expected_triggers) in [
(
path!("/the-root/nested/a.rs"),
BTreeSet::from([".".to_string()]),
),
(path!("/the-root/nested/b.rs"), BTreeSet::new()),
] {
let (new_buffer, _lsp_handle) = project
.update(cx, |project, cx| {
project.open_local_buffer_with_lsp(path, cx)
})
.await
.unwrap();
new_buffer.read_with(cx, |buffer, _| {
assert_eq!(buffer.completion_triggers(), &expected_triggers);
});
}
}
#[gpui::test]
async fn test_invalid_sync_registration_pattern_preserves_previous_registration(
cx: &mut gpui::TestAppContext,
) {
init_test(cx);
let (project, mut fake_server) =
setup_dynamic_registration_test(cx, lsp::ServerCapabilities::default()).await;
let (buffer, _lsp_handle) = project
.update(cx, |project, cx| {
project.open_local_buffer_with_lsp(path!("/the-root/a.rs"), cx)
})
.await
.unwrap();
let uri = lsp::Uri::from_file_path(path!("/the-root/a.rs")).unwrap();
// Test builds send incremental changes without a sync kind, so the registered `FULL` sync
// tells whether the registration still applies.
for (method, registration_id, options) in [
(
"textDocument/didChange",
"change-a",
json!({ "syncKind": 1 }),
),
(
"textDocument/didSave",
"save-a",
json!({ "includeText": false }),
),
] {
let register_options = |pattern: &str| {
let mut register_options = options.clone();
register_options["documentSelector"] = json!([{ "pattern": pattern }]);
register_options
};
register_capability(
&fake_server,
method,
registration_id,
Some(register_options("**/a.rs")),
)
.await;
let error = register_capabilities(
&fake_server,
vec![lsp::Registration {
id: registration_id.to_string(),
method: method.to_string(),
register_options: Some(register_options("**/[a.rs")),
}],
)
.await
.expect_err("an invalid replacement should produce an error response");
assert!(
error
.to_string()
.contains("invalid document filter pattern"),
"unexpected error for an invalid {method} replacement: {error:#}",
);
}
cx.executor().run_until_parked();
assert_eq!(
edit_and_receive_change(&buffer, &mut fake_server, cx).await,
(uri.clone(), false),
"expected the previous didChange registration to remain in effect",
);
project
.update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
.await
.unwrap();
assert_eq!(
fake_server
.receive_notification::<lsp::notification::DidSaveTextDocument>()
.await
.text_document
.uri,
uri,
"expected the previous didSave registration to remain in effect",
);
}
#[gpui::test]
async fn test_registration_patterns_respect_globstar_and_character_class_separators(
cx: &mut gpui::TestAppContext,
) {
init_test(cx);
let (project, fake_server) =
setup_dynamic_registration_test(cx, lsp::ServerCapabilities::default()).await;
let fs = project.read_with(cx, |project, _| project.fs().as_fake());
fs.insert_tree(
path!("/the-root"),
json!({ "a0b.rs": "", "a": { "b.rs": "" } }),
)
.await;
let (flat_buffer, _flat_lsp_handle) = project
.update(cx, |project, cx| {
project.open_local_buffer_with_lsp(path!("/the-root/a0b.rs"), cx)
})
.await
.unwrap();
let (nested_buffer, _nested_lsp_handle) = project
.update(cx, |project, cx| {
project.open_local_buffer_with_lsp(path!("/the-root/a/b.rs"), cx)
})
.await
.unwrap();
let buffer_triggers = |buffer: &Entity<Buffer>, cx: &mut gpui::TestAppContext| {
buffer.read_with(cx, |buffer, _| buffer.completion_triggers().clone())
};
let mut expected_flat_triggers = BTreeSet::new();
for (id, pattern, trigger) in [
("completion-globstars", "**/the-root/**/**", "."),
("completion-negated-class", "**/a[!x]b.rs", ":"),
("completion-range-class", "**/a[.-0]b.rs", "!"),
(
"completion-braced-globstar",
"**/the-root/{**,src}/a0b.rs",
";",
),
("completion-literal-brace", "**/{[}],a0b}.rs", "?"),
] {
register_capability(
&fake_server,
"textDocument/completion",
id,
Some(json!({
"documentSelector": [{ "language": "rust", "pattern": pattern }],
"triggerCharacters": [trigger],
})),
)
.await;
cx.executor().run_until_parked();
expected_flat_triggers.insert(trigger.to_string());
assert_eq!(
buffer_triggers(&flat_buffer, cx),
expected_flat_triggers,
"expected {pattern} to enable its trigger for the flat filename",
);
assert_eq!(
buffer_triggers(&nested_buffer, cx),
BTreeSet::from([".".to_string()]),
"expected only the globstar trigger for the nested path after registering {pattern}",
);
}
}
async fn setup_dynamic_registration_test(
cx: &mut gpui::TestAppContext,
capabilities: lsp::ServerCapabilities,
@@ -3080,20 +3505,29 @@ async fn register_capability(
id: &str,
register_options: Option<serde_json::Value>,
) {
register_capabilities(
fake_server,
vec![lsp::Registration {
id: id.to_string(),
method: method.to_string(),
register_options,
}],
)
.await
.unwrap();
}
async fn register_capabilities(
fake_server: &lsp::FakeLanguageServer,
registrations: Vec<lsp::Registration>,
) -> anyhow::Result<()> {
fake_server
.request::<lsp::request::RegisterCapability>(
lsp::RegistrationParams {
registrations: vec![lsp::Registration {
id: id.to_string(),
method: method.to_string(),
register_options,
}],
},
lsp::RegistrationParams { registrations },
DEFAULT_LSP_REQUEST_TIMEOUT,
)
.await
.into_response()
.unwrap();
}
async fn unregister_capabilities(
@@ -11419,7 +11419,7 @@ async fn test_dynamic_formatting_registrations_honor_document_selectors(
}
#[gpui::test]
async fn test_dynamic_formatting_registration_with_pattern_only_selector_fails_open(
async fn test_dynamic_formatting_registration_with_pattern_only_selector(
cx: &mut gpui::TestAppContext,
) {
init_test(cx);
@@ -11466,40 +11466,55 @@ async fn test_dynamic_formatting_registration_with_pattern_only_selector_fails_o
}
});
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" }],
})),
}],
},
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,
let register_formatting = async |id: &str, pattern: &str| {
fake_server
.request::<lsp::request::RegisterCapability>(
lsp::RegistrationParams {
registrations: vec![lsp::Registration {
id: id.to_string(),
method: "textDocument/formatting".to_string(),
register_options: Some(json!({
"documentSelector": [{ "pattern": pattern }],
})),
}],
},
DEFAULT_LSP_REQUEST_TIMEOUT,
)
})
.await
.unwrap();
.await
.into_response()
.unwrap();
};
let format = async |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,
)
})
.await
.unwrap();
};
register_formatting("pattern-only-formatting", "**/*.nomatch").await;
cx.executor().run_until_parked();
format(cx).await;
assert_eq!(
format_request_count.load(atomic::Ordering::SeqCst),
0,
"expected a pattern-only filter not matching the buffer's path not to route the formatting request",
);
register_formatting("matching-pattern-formatting", "**/*.rs").await;
cx.executor().run_until_parked();
format(cx).await;
assert_eq!(
format_request_count.load(atomic::Ordering::SeqCst),
1,
"expected a pattern-only filter to fail open and route the formatting request",
"expected a pattern-only filter matching the buffer's path to route the formatting request",
);
}