Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
project: Match document filter patterns in dynamic registrations (#65252)
Shuhei Kadowakicb593458e1d6
diff --git a/Cargo.lock b/Cargo.lockindex 2456c21c85b..5b2eeb56d4e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -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",diff --git a/Cargo.toml b/Cargo.tomlindex 1b224fec377..055fb7f0f8f 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -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"] }diff --git a/crates/collab/tests/integration/editor_tests.rs b/crates/collab/tests/integration/editor_tests.rsindex c2e8779b153..0dfc147a5b0 100644--- a/crates/collab/tests/integration/editor_tests.rs+++ b/crates/collab/tests/integration/editor_tests.rs@@ -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 {diff --git a/crates/lsp/src/lsp.rs b/crates/lsp/src/lsp.rsindex ce68fa25eac..b3307419c66 100644--- a/crates/lsp/src/lsp.rs+++ b/crates/lsp/src/lsp.rs@@ -1134,6 +1134,9 @@ impl LanguageServer {]),}),}),+ filters: Some(TextDocumentFilterClientCapabilities {+ relative_pattern_support: Some(true),+ }),..TextDocumentClientCapabilities::default()}),experimental: Some(json!({diff --git a/crates/project/src/lsp_store.rs b/crates/project/src/lsp_store.rsindex 06e71a9d44d..9f364e79108 100644--- a/crates/project/src/lsp_store.rs+++ b/crates/project/src/lsp_store.rs@@ -308,6 +308,42 @@ struct DocumentSelectorContext {/// `None` for documents without a language, which no `language` filter matches.language_id: Option<String>,scheme: &'static str,+ path: DocumentSelectorPath,+}++#[derive(Clone, Debug)]+enum DocumentSelectorPath {+ /// The context stands for every document of a language (e.g. for per-language caches),+ /// so `pattern` filters cannot be evaluated and are not considered.+ Unknown,+ /// The document has no file system path, so no `pattern` filter matches it.+ Absent,+ /// The absolute path of the document with `/` separators, in the path style of the host it+ /// belongs to, which differs from this machine's for remote projects.+ Present { path: String, path_style: PathStyle },+}++impl DocumentSelectorPath {+ fn for_file(file: &File, cx: &App) -> Self {+ Self::present(+ &file.abs_path(cx).to_string_lossy(),+ file.worktree.read(cx).path_style(),+ )+ }++ fn present(path: &str, path_style: PathStyle) -> Self {+ Self::Present {+ path: path_with_slashes(path, path_style),+ path_style,+ }+ }+}++fn path_with_slashes(path: &str, path_style: PathStyle) -> String {+ match path_style {+ PathStyle::Windows => path.replace('\\', "/"),+ PathStyle::Unix => path.to_string(),+ }}pub struct LocalLspStore {@@ -1086,23 +1122,15 @@ impl LocalLspStore {let lsp_store = lsp_store.clone();let mut cx = cx.clone();async move {- lsp_store- .update(&mut cx, |lsp_store, cx| {- if lsp_store.as_local().is_some() {- match lsp_store- .register_server_capabilities(server_id, params, cx)- {- Ok(()) => {}- Err(e) => {- log::error!(- "Failed to register server capabilities: {e:#}"- );- }- };- }- })- .ok();- Ok(())+ lsp_store.update(&mut cx, |lsp_store, cx| {+ if lsp_store.as_local().is_some() {+ lsp_store+ .register_server_capabilities(server_id, params, cx)+ .inspect_err(|error| log::error!("{error:#}"))+ } else {+ Ok(())+ }+ })?}}})@@ -1501,9 +1529,9 @@ impl LocalLspStore {fn language_servers_for_buffer<'a>(&'a self,- buffer: &'a Buffer,- cx: &'a mut App,- ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {+ buffer: &Buffer,+ cx: &mut App,+ ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> + use<'a> {self.language_server_ids_for_buffer(buffer, cx).into_iter().filter_map(|server_id| match self.language_servers.get(&server_id)? {@@ -2027,6 +2055,7 @@ impl LocalLspStore {buffer_snapshot,adapter,server,+ cx,)});if range_formatter.is_some() {@@ -2041,6 +2070,7 @@ impl LocalLspStore {buffer_snapshot,adapter,server,+ cx,)})} else {@@ -2053,11 +2083,13 @@ impl LocalLspStore {buffer_snapshot,adapter,server,+ cx,) || buffer_supports_lsp_range_formatting(local,buffer_snapshot,adapter,server,+ cx,)})};@@ -2548,6 +2580,7 @@ impl LocalLspStore {buffer_handle.read(cx),adapter,language_server,+ cx,)})})?;@@ -2695,12 +2728,13 @@ impl LocalLspStore {Some(local) => {let buffer = buffer.read(cx);(- buffer_supports_lsp_formatting(local, buffer, adapter, language_server),+ buffer_supports_lsp_formatting(local, buffer, adapter, language_server, cx),buffer_supports_lsp_range_formatting(local,buffer,adapter,language_server,+ cx,),)}@@ -2988,6 +3022,7 @@ impl LocalLspStore {server.server_id(),&adapter,buffer,+ cx,),cx,);@@ -3290,6 +3325,7 @@ impl LocalLspStore {server.server_id(),&adapter,buffer,+ cx,),cx,);@@ -6007,6 +6043,7 @@ impl LspStore {&self,server_id: LanguageServerId,language: Option<&LanguageName>,+ path: DocumentSelectorPath,) -> Option<DocumentSelectorContext> {let language = language?;let server_name = &self.language_server_statuses.get(&server_id)?.name;@@ -6021,6 +6058,7 @@ impl LspStore {Some(DocumentSelectorContext {language_id: Some(language_id),scheme: "file",+ path,})}@@ -6033,8 +6071,12 @@ impl LspStore {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());+ let buffer = buffer.read(cx);+ let language = buffer.language().map(|language| language.name());+ let path = File::from_dyn(buffer.file()).map_or(DocumentSelectorPath::Unknown, |file| {+ DocumentSelectorPath::for_file(file, cx)+ });+ let context = self.remote_document_selector_context(server_id, language.as_ref(), path);remote_text_document_capabilities_match(self.lsp_server_initial_capabilities.get(&server_id),self.lsp_server_capabilities.get(&server_id),@@ -6062,7 +6104,7 @@ impl LspStore {else {return false;};- text_document_capabilities_for_buffer(local, method, buffer, adapter, server)+ text_document_capabilities_for_buffer(local, method, buffer, adapter, server, cx).any(&mut check)});}@@ -6095,8 +6137,10 @@ impl LspStore {}).any(|(adapter, server)| {let server_name = server.name();- text_document_capabilities_for_buffer(local, method, buffer, adapter, server)- .any(|capabilities| check(&server_name, capabilities))+ text_document_capabilities_for_buffer(+ local, method, buffer, adapter, server, cx,+ )+ .any(|capabilities| check(&server_name, capabilities))});}@@ -6241,6 +6285,7 @@ impl LspStore {buffer,adapter,language_server,+ cx,).peekable();if applicable_capabilities.peek().is_some() {@@ -7978,7 +8023,7 @@ impl LspStore {local.language_servers_for_buffer(buffer, cx).filter(|(adapter, server)| {- lsp_command_allowed_for_buffer(local, &request, buffer, adapter, server)+ lsp_command_allowed_for_buffer(local, &request, buffer, adapter, server, cx)}).filter(|(adapter, _)| {scope@@ -8677,6 +8722,7 @@ impl LspStore {registration,buffer.read(cx),&adapter,+ cx,) {continue;}@@ -9622,7 +9668,7 @@ impl LspStore {.language_servers_for_buffer(buffer, cx).map(|(adapter, server)| {let sync_kind =- text_document_sync_kind_for_buffer(local, buffer, adapter, server);+ text_document_sync_kind_for_buffer(local, buffer, adapter, server, cx);(server.clone(), sync_kind)}).collect(),@@ -9754,7 +9800,7 @@ impl LspStore {return None;};let include_text =- did_save_include_text_for_buffer(local, buffer.read(cx), adapter, server)?;+ did_save_include_text_for_buffer(local, buffer.read(cx), adapter, server, cx)?;Some((server.clone(), include_text))}).collect::<Vec<_>>();@@ -10642,7 +10688,7 @@ impl LspStore {local.language_servers_for_buffer(buffer, cx).filter(|(adapter, server)| {- lsp_command_allowed_for_buffer(local, request, buffer, adapter, server)+ lsp_command_allowed_for_buffer(local, request, buffer, adapter, server, cx)}).map(|(_, server)| server.server_id()).filter(|server_id| {@@ -10696,7 +10742,7 @@ impl LspStore {local.language_servers_for_buffer(buffer, cx).filter(|(adapter, server)| {- lsp_command_allowed_for_buffer(local, &request, buffer, adapter, server)+ lsp_command_allowed_for_buffer(local, &request, buffer, adapter, server, cx)}).filter(|(adapter, _)| {scope@@ -14959,13 +15005,17 @@ impl LspStore {fn document_selector_context_for_buffer(buffer: &Buffer,adapter: &CachedLspAdapter,+ cx: &App,) -> DocumentSelectorContext {- match buffer.language() {- Some(language) => document_selector_context_for_language(&language.name(), adapter),- None => DocumentSelectorContext {- language_id: None,- scheme: "file",- },+ let path = File::from_dyn(buffer.file()).map_or(DocumentSelectorPath::Absent, |file| {+ DocumentSelectorPath::for_file(file, cx)+ });+ DocumentSelectorContext {+ language_id: buffer+ .language()+ .map(|language| adapter.language_id(&language.name())),+ scheme: "file",+ path,}}@@ -14976,32 +15026,450 @@ fn document_selector_context_for_language(DocumentSelectorContext {language_id: Some(adapter.language_id(language)),scheme: "file",+ path: DocumentSelectorPath::Unknown,+ }+}++/// A document selector with the patterns of its filters compiled when it is registered, as+/// documents are matched against it as often as on every edit.+#[derive(Clone, Debug)]+pub(super) struct CompiledDocumentSelector {+ filters: Vec<CompiledDocumentFilter>,+}++#[derive(Clone, Debug)]+struct CompiledDocumentFilter {+ filter: lsp::DocumentFilter,+ pattern: Option<DocumentFilterPattern>,+}++impl CompiledDocumentSelector {+ /// Rejects unusable patterns up front, so that matching never has to decide what they mean.+ pub(super) fn new(document_selector: lsp::DocumentSelector) -> Result<Self> {+ let filters = document_selector+ .into_iter()+ .map(CompiledDocumentFilter::new)+ .collect::<Result<_>>()?;+ Ok(Self { filters })+ }+}++impl CompiledDocumentFilter {+ fn new(filter: lsp::DocumentFilter) -> Result<Self> {+ let pattern = filter+ .pattern+ .as_ref()+ .map(|pattern| {+ DocumentFilterPattern::new(pattern)+ .with_context(|| format!("invalid document filter pattern {pattern:?}"))+ })+ .transpose()?;+ Ok(Self { filter, pattern })+ }+}++impl PartialEq for CompiledDocumentSelector {+ fn eq(&self, other: &Self) -> bool {+ self.filters+ .iter()+ .map(|filter| &filter.filter)+ .eq(other.filters.iter().map(|filter| &filter.filter))+ }+}++impl Serialize for CompiledDocumentSelector {+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {+ serializer.collect_seq(self.filters.iter().map(|filter| &filter.filter))+ }+}++impl<'de> serde::Deserialize<'de> for CompiledDocumentSelector {+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ let document_selector = lsp::DocumentSelector::deserialize(deserializer)?;+ // Hosts only share selectors they compiled. Should a guest still fail to compile a+ // pattern, dropping its filter leaves it matching no document, while failing here would+ // discard the server's other capabilities.+ let filters = document_selector+ .into_iter()+ .filter_map(|filter| CompiledDocumentFilter::new(filter).log_err())+ .collect();+ Ok(Self { filters })}}fn document_selector_matches(- document_selector: Option<&lsp::DocumentSelector>,+ document_selector: Option<&CompiledDocumentSelector>,context: &DocumentSelectorContext,) -> bool {let Some(document_selector) = document_selector else {return true;};- document_selector.iter().any(|filter| {- if let Some(language) = &filter.language- && context.language_id.as_ref() != Some(language)- {- return false;+ document_selector+ .filters+ .iter()+ .any(|CompiledDocumentFilter { filter, pattern }| {+ if let Some(language) = &filter.language+ && context.language_id.as_ref() != Some(language)+ {+ return false;+ }++ if let Some(scheme) = &filter.scheme+ && !scheme.eq_ignore_ascii_case(context.scheme)+ {+ return false;+ }++ // Checked last, since it runs the glob.+ if let Some(pattern) = pattern {+ match &context.path {+ DocumentSelectorPath::Unknown => {}+ DocumentSelectorPath::Absent => return false,+ DocumentSelectorPath::Present { path, path_style } => {+ if !pattern.matches(path, *path_style) {+ return false;+ }+ }+ }+ }++ true+ })+}++fn document_filter_glob(pattern: &lsp::GlobPattern) -> (Option<&lsp::Uri>, &str) {+ match pattern {+ lsp::GlobPattern::String(pattern) => (None, pattern),+ lsp::GlobPattern::Relative(relative_pattern) => {+ let base_uri = match &relative_pattern.base_uri {+ OneOf::Left(workspace_folder) => &workspace_folder.uri,+ OneOf::Right(base_uri) => base_uri,+ };+ (Some(base_uri), &relative_pattern.pattern)}+ }+}++// Bound work on server-supplied patterns before the regex compiler's own limits apply.+const DOCUMENT_FILTER_GLOB_MAX_ALTERNATIVES: usize = 256;+const DOCUMENT_FILTER_GLOB_MAX_BYTES: usize = 1024 * 1024;- if let Some(scheme) = &filter.scheme- && !scheme.eq_ignore_ascii_case(context.scheme)+/// Compiles an LSP glob pattern into a regular expression matching paths with `/` separators.+///+/// Uses LSP glob semantics: `*` and `?` match characters (not bytes) within a path segment,+/// a `**` segment matches any number of segments, `{a,b}` matches either sub-pattern, and+/// `[a-z]` or `[!a-z]` matches a character in or out of a range within a path segment.+/// Unlike VS Code's parser, consecutive `**` segments are equivalent to one, and character+/// classes cannot consume `/`, even when a negation or range would otherwise include it.+///+/// With `normalize_drive_letters`, the drive letters of absolute Windows paths are lowercased+/// in each alternative after brace expansion, as braces can enclose or even produce them.+fn compile_document_filter_glob(glob: &str, normalize_drive_letters: bool) -> Result<regex::Regex> {+ let mut regex = String::from("^(?:");+ // Expand complete paths so `**` inside an alternative can absorb adjacent separators.+ for (index, alternative) in expand_glob_braces(glob)?.iter().enumerate() {+ let alternative = if normalize_drive_letters {+ normalize_document_filter_drive_letter(alternative)+ } else {+ Cow::Borrowed(alternative.as_str())+ };+ let branch = glob_regex(&alternative)?;+ anyhow::ensure!(+ regex.len() + branch.len() + 3 <= DOCUMENT_FILTER_GLOB_MAX_BYTES,+ "document filter glob exceeds the compiled pattern size limit"+ );+ if index > 0 {+ regex.push('|');+ }+ regex.push_str(&branch);+ }+ regex.push_str(")$");+ Ok(regex::Regex::new(®ex)?)+}++fn expand_glob_braces(glob: &str) -> Result<Vec<String>> {+ let mut remaining_bytes = DOCUMENT_FILTER_GLOB_MAX_BYTES+ .checked_sub(glob.len())+ .context("document filter glob exceeds the expansion size limit")?;+ let mut pending = vec![glob.to_string()];+ let mut expanded = Vec::new();+ while let Some(pattern) = pending.pop() {+ let Some((group, alternatives)) = glob_brace_alternatives(&pattern)? else {+ expanded.push(pattern);+ continue;+ };+ anyhow::ensure!(+ expanded.len() + pending.len() + alternatives.len()+ <= DOCUMENT_FILTER_GLOB_MAX_ALTERNATIVES,+ "document filter glob exceeds the alternative count limit"+ );+ let prefix = &pattern[..group.start];+ let suffix = &pattern[group.end..];+ for alternative in alternatives.into_iter().rev() {+ // Charge intermediate expansions too, so deeply nested single-choice groups+ // cannot cause unbounded rescanning and copying even with few final alternatives.+ remaining_bytes = remaining_bytes+ .checked_sub(prefix.len() + alternative.len() + suffix.len())+ .context("document filter glob exceeds the expansion size limit")?;+ pending.push(format!("{prefix}{alternative}{suffix}"));+ }+ }+ Ok(expanded)+}++fn glob_brace_alternatives(glob: &str) -> Result<Option<(Range<usize>, Vec<&str>)>> {+ let mut chars = glob.char_indices();+ let mut depth = 0;+ let mut group_start = 0;+ let mut alternative_start = 0;+ let mut alternatives = Vec::new();+ while let Some((index, character)) = chars.next() {+ match character {+ '[' => {+ glob_character_class_end(glob, &mut chars)?;+ }+ '{' => {+ if depth == 0 {+ group_start = index;+ alternative_start = index + 1;+ }+ depth += 1;+ }+ ',' if depth == 1 => {+ anyhow::ensure!(+ alternatives.len() + 1 < DOCUMENT_FILTER_GLOB_MAX_ALTERNATIVES,+ "document filter glob exceeds the alternative count limit"+ );+ alternatives.push(&glob[alternative_start..index]);+ alternative_start = index + 1;+ }+ '}' if depth > 0 => {+ depth -= 1;+ if depth == 0 {+ alternatives.push(&glob[alternative_start..index]);+ return Ok(Some((group_start..index + 1, alternatives)));+ }+ }+ _ => {}+ }+ }+ anyhow::ensure!(depth == 0, "unclosed `{{` in glob pattern {glob:?}");+ Ok(None)+}++fn glob_character_class_end(glob: &str, chars: &mut std::str::CharIndices<'_>) -> Result<usize> {+ let mut first = true;+ let mut has_member = false;+ for (index, character) in chars.by_ref() {+ if character == ']' && has_member {+ return Ok(index + 1);+ }+ // A leading `]`, also after negation, is a literal member rather than the delimiter.+ if !first || !matches!(character, '!' | '^') {+ has_member = true;+ }+ first = false;+ }+ anyhow::bail!("unclosed `[` in glob pattern {glob:?}")+}++fn glob_regex(glob: &str) -> Result<String> {+ const GLOBSTAR: &str = "**";+ let mut segments = split_glob(glob, '/')?;+ segments.dedup_by(|segment, previous| *segment == GLOBSTAR && *previous == GLOBSTAR);+ if segments.is_empty() {+ return Ok(String::new());+ }+ if segments.iter().all(|segment| *segment == GLOBSTAR) {+ return Ok("(?s:.*)".to_string());+ }+ if segments.as_slice() == ["", GLOBSTAR] {+ return Ok("/(?s:.*)".to_string());+ }++ let mut regex = String::new();+ for (index, segment) in segments.iter().enumerate() {+ let is_last_segment = index + 1 == segments.len();+ if *segment == GLOBSTAR {+ // A terminal globstar owns its separator, but cannot extend the preceding+ // segment (e.g. `/root/**` must not match `/rooted/`).+ regex.push_str(if is_last_segment {+ "(?:/(?s:.*))?"+ } else {+ "(?:/|[^/]+/)*?"+ });+ continue;+ }++ let mut chars = segment.char_indices();+ while let Some((index, char)) = chars.next() {+ match char {+ '[' => {+ let end = glob_character_class_end(segment, &mut chars)?;+ regex.push_str(&glob_character_class_regex(&segment[index + 1..end - 1]));+ }+ '?' => regex.push_str("[^/]"),+ '*' => regex.push_str("[^/]*?"),+ char => regex.push_str(®ex::escape(char.encode_utf8(&mut [0; 4]))),+ }+ }++ // A following `**` that ends the pattern brings its own separator.+ let next_segment_is_last_globstar = segments+ .get(index + 1)+ .is_some_and(|next| *next == GLOBSTAR)+ && index + 2 == segments.len();+ if !is_last_segment && !next_segment_is_last_globstar {+ regex.push('/');+ }+ }+ Ok(regex)+}++/// Members are escaped and only a `-` between two members forms a range, as in the JavaScript+/// regular expressions VS Code compiles classes into, so a `-` endpoint (e.g. `[--0]`) keeps+/// its meaning instead of being reinterpreted by the regex parser.+fn glob_character_class_regex(members: &str) -> String {+ let push_member = |class: &mut String, member: char| {+ class.push_str(®ex::escape(member.encode_utf8(&mut [0; 4])));+ };+ let mut class = String::new();+ let mut members = match members.strip_prefix(['!', '^']) {+ Some(members) => {+ class.push('^');+ members.chars()+ }+ None => members.chars(),+ };+ while let Some(member) = members.next() {+ push_member(&mut class, member);+ let mut lookahead = members.clone();+ if lookahead.next() == Some('-')+ && let Some(range_end) = lookahead.next(){- return false;+ class.push('-');+ push_member(&mut class, range_end);+ members = lookahead;}+ }+ format!("[[{class}]&&[^/]]")+}- true- })+/// Splits a brace-expanded glob without interpreting separators inside character classes.+fn split_glob(glob: &str, separator: char) -> Result<Vec<&str>> {+ let mut parts = Vec::new();+ if glob.is_empty() {+ return Ok(parts);+ }+ let mut start = 0;+ let mut chars = glob.char_indices();+ while let Some((index, character)) = chars.next() {+ if character == '[' {+ glob_character_class_end(glob, &mut chars)?;+ } else if character == separator {+ parts.push(&glob[start..index]);+ start = index + character.len_utf8();+ }+ }+ parts.push(&glob[start..]);+ Ok(parts)+}++fn normalize_document_filter_drive_letter(path: &str) -> Cow<'_, str> {+ match path.as_bytes() {+ [drive_letter, b':', b'/', ..] if drive_letter.is_ascii_uppercase() => {+ let mut path = path.to_string();+ path.replace_range(+ ..1,+ &char::from(drive_letter.to_ascii_lowercase()).to_string(),+ );+ Cow::Owned(path)+ }+ _ => Cow::Borrowed(path),+ }+}++#[derive(Clone, Debug)]+struct DocumentFilterPattern {+ base: Option<RelativePatternBase>,+ matcher: regex::Regex,+}++/// The base of a relative pattern, read in either path style, as the one of the host is only+/// known when matching, with `/` separators and without a trailing one.+#[derive(Clone, Debug)]+struct RelativePatternBase {+ unix_path: Option<String>,+ windows_path: Option<String>,+}++impl DocumentFilterPattern {+ fn new(pattern: &lsp::GlobPattern) -> Result<Self> {+ let (base_uri, glob) = document_filter_glob(pattern);+ let base = base_uri+ .map(|base_uri| {+ anyhow::ensure!(+ base_uri.scheme() == "file",+ "relative pattern base URI {base_uri} is not a file URI"+ );+ let base_path = |path_style| {+ let path = base_uri.to_file_path_ext(path_style).ok()?;+ let path = path_with_slashes(&path.to_string_lossy(), path_style);+ Some(path.trim_end_matches('/').to_string())+ };+ Ok(RelativePatternBase {+ unix_path: base_path(PathStyle::Unix),+ windows_path: base_path(PathStyle::Windows),+ })+ })+ .transpose()?;+ // VS Code's fsPath lowercases the drive letter, so drive prefixes of absolute patterns+ // are canonicalized like those of Windows paths when matching. This leaves the matches+ // of Unix paths unchanged, as they start with `/` rather than a drive letter.+ let matcher = compile_document_filter_glob(glob, base.is_none())?;+ Ok(Self { base, matcher })+ }++ fn matches(&self, path: &str, path_style: PathStyle) -> bool {+ let Some(base) = &self.base else {+ let path = match path_style {+ PathStyle::Windows => normalize_document_filter_drive_letter(path),+ PathStyle::Unix => Cow::Borrowed(path),+ };+ return self.matcher.is_match(&path);+ };++ // The base URI is on the same host as the document, so it is read in the same path style.+ let base_path = match path_style {+ PathStyle::Windows => base.windows_path.as_deref(),+ PathStyle::Unix => base.unix_path.as_deref(),+ };+ let Some(base_path) = base_path else {+ return false;+ };+ let mut relative_path = path;+ // Case-equivalent components can have different UTF-8 lengths (e.g. K and k), so+ // consume the candidate's components rather than slicing at the base's byte length.+ for base_component in base_path.split('/') {+ // The base may be the document itself, leaving an empty path for the pattern, which+ // `**` matches. A path running out before the base does fails to match its components.+ let (component, remainder) =+ relative_path.split_once('/').unwrap_or((relative_path, ""));+ let matches = match path_style {+ PathStyle::Windows => {+ component == base_component+ || component.to_lowercase() == base_component.to_lowercase()+ }+ PathStyle::Unix => component == base_component,+ };+ if !matches {+ return false;+ }+ relative_path = remainder;+ }+ self.matcher.is_match(relative_path)+ }}fn remote_text_document_capabilities_match(@@ -15046,8 +15514,9 @@ fn dynamic_text_document_registration_allows_buffer(registration: &dynamic_registration::DynamicTextDocumentRegistration,buffer: &Buffer,adapter: &CachedLspAdapter,+ cx: &App,) -> bool {- let context = document_selector_context_for_buffer(buffer, adapter);+ let context = document_selector_context_for_buffer(buffer, adapter, cx);document_selector_matches(registration.document_selector.as_ref(), &context)}@@ -15065,10 +15534,11 @@ fn text_document_registration_method(method: &str) -> &str {fn text_document_capabilities_for_buffer<'a>(local: &'a LocalLspStore,method: &str,- buffer: &'a Buffer,- adapter: &'a CachedLspAdapter,+ buffer: &Buffer,+ adapter: &CachedLspAdapter,server: &'a LanguageServer,-) -> impl Iterator<Item = AdapterServerCapabilities<'a>> {+ cx: &App,+) -> impl DoubleEndedIterator<Item = AdapterServerCapabilities<'a>> + use<'a> {let code_action_kinds = server.code_action_kinds();let static_capabilities = local.initial_server_capabilities@@ -15079,6 +15549,7 @@ fn text_document_capabilities_for_buffer<'a>(});let registration_method = text_document_registration_method(method);+ let context = document_selector_context_for_buffer(buffer, adapter, cx);let dynamic_capabilities = local.language_server_dynamic_registrations.get(&server.server_id())@@ -15086,7 +15557,7 @@ fn text_document_capabilities_for_buffer<'a>(.into_iter().flat_map(|registrations| registrations.values()).filter(move |registration| {- dynamic_text_document_registration_allows_buffer(registration, buffer, adapter)+ document_selector_matches(registration.document_selector.as_ref(), &context)}).map(move |registration| AdapterServerCapabilities {server_capabilities: ®istration.server_capabilities,@@ -15099,10 +15570,11 @@ fn text_document_capabilities_for_buffer<'a>(fn applicable_lsp_command_capabilities_for_buffer<'a, R>(local: &'a LocalLspStore,request: &'a R,- buffer: &'a Buffer,- adapter: &'a CachedLspAdapter,+ buffer: &Buffer,+ adapter: &CachedLspAdapter,server: &'a LanguageServer,-) -> impl Iterator<Item = AdapterServerCapabilities<'a>>+ cx: &App,+) -> impl Iterator<Item = AdapterServerCapabilities<'a>> + use<'a, R>whereR: LspCommand,{@@ -15112,6 +15584,7 @@ wherebuffer,adapter,server,+ cx,).filter(move |capabilities| request.check_capabilities(*capabilities))}@@ -15122,11 +15595,12 @@ fn lsp_command_allowed_for_buffer<R>(buffer: &Buffer,adapter: &CachedLspAdapter,server: &LanguageServer,+ cx: &App,) -> boolwhereR: LspCommand,{- applicable_lsp_command_capabilities_for_buffer(local, request, buffer, adapter, server)+ applicable_lsp_command_capabilities_for_buffer(local, request, buffer, adapter, server, cx).next().is_some()}@@ -15136,11 +15610,17 @@ fn buffer_supports_lsp_formatting(buffer: &Buffer,adapter: &CachedLspAdapter,server: &LanguageServer,+ cx: &App,) -> bool {- text_document_capabilities_for_buffer(local, "textDocument/formatting", buffer, adapter, server)- .any(|capabilities| {- server_capabilities_support_formatting(capabilities.server_capabilities)- })+ text_document_capabilities_for_buffer(+ local,+ "textDocument/formatting",+ buffer,+ adapter,+ server,+ cx,+ )+ .any(|capabilities| server_capabilities_support_formatting(capabilities.server_capabilities))}fn buffer_supports_lsp_range_formatting(@@ -15148,6 +15628,7 @@ fn buffer_supports_lsp_range_formatting(buffer: &Buffer,adapter: &CachedLspAdapter,server: &LanguageServer,+ cx: &App,) -> bool {text_document_capabilities_for_buffer(local,@@ -15155,6 +15636,7 @@ fn buffer_supports_lsp_range_formatting(buffer,adapter,server,+ cx,).any(|capabilities| {server_capabilities_support_range_formatting(capabilities.server_capabilities)@@ -15166,6 +15648,7 @@ fn completion_trigger_characters_for_buffer(server_id: LanguageServerId,adapter: &CachedLspAdapter,buffer: &Buffer,+ cx: &App,) -> BTreeSet<String> {fn extend_triggers(triggers: &mut BTreeSet<String>, options: &lsp::CompletionOptions) {if let Some(characters) = &options.trigger_characters {@@ -15187,7 +15670,7 @@ fn completion_trigger_characters_for_buffer(.and_then(|registrations| registrations.text_documents.get("textDocument/completion")){for registration in registrations.values() {- if dynamic_text_document_registration_allows_buffer(registration, buffer, adapter)+ if dynamic_text_document_registration_allows_buffer(registration, buffer, adapter, cx)&& let Some(options) = registration.server_capabilities.completion_provider@@ -16841,6 +17324,7 @@ fn did_save_include_text_for_buffer(buffer: &Buffer,adapter: &CachedLspAdapter,server: &LanguageServer,+ cx: &App,) -> Option<bool> {fn save_options(capabilities: &lsp::ServerCapabilities,@@ -16857,7 +17341,7 @@ fn did_save_include_text_for_buffer(.buffers_opened_in_servers.get(&buffer.remote_id()).is_some_and(|servers| servers.contains(&server_id));- let context = document_selector_context_for_buffer(buffer, adapter);+ let context = document_selector_context_for_buffer(buffer, adapter, cx);// Later registrations take precedence over earlier ones. Registrations without a selector// stand for the documents the client selects for the server, like the static options.let registered_save_options = local@@ -16898,20 +17382,29 @@ fn text_document_sync_kind_for_buffer(buffer: &Buffer,adapter: &CachedLspAdapter,server: &LanguageServer,+ cx: &App,) -> Option<lsp::TextDocumentSyncKind> {- // Later registrations take precedence over earlier ones and the static options.- text_document_capabilities_for_buffer(local, "textDocument/didChange", buffer, adapter, server)- .filter_map(|capabilities| {- match capabilities- .server_capabilities- .text_document_sync- .as_ref()?- {- lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),- lsp::TextDocumentSyncCapability::Options(options) => options.change,- }- })- .last()+ // Later registrations take precedence over earlier ones and the static options, so+ // searching from the latest one stops at the first registration selecting the buffer.+ text_document_capabilities_for_buffer(+ local,+ "textDocument/didChange",+ buffer,+ adapter,+ server,+ cx,+ )+ .rev()+ .find_map(|capabilities| {+ match capabilities+ .server_capabilities+ .text_document_sync+ .as_ref()?+ {+ lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),+ lsp::TextDocumentSyncCapability::Options(options) => options.change,+ }+ })}/// Completion items are displayed in a `UniformList`.@@ -17415,6 +17908,34 @@ mod tests {));assert!(should_log_lsp_request_failure("something else entirely"));}++ #[test]+ fn synced_document_selector_drops_filters_that_fail_to_compile() {+ let context =+ |path: &str| toml_file_context(DocumentSelectorPath::present(path, PathStyle::Unix));+ let selector: CompiledDocumentSelector = serde_json::from_value(serde_json::json!([+ { "pattern": "**/[a.rs" },+ { "pattern": "**/b.rs" },+ ]))+ .expect("a synced selector with an invalid pattern should deserialize");+ assert!(!document_selector_matches(+ Some(&selector),+ &context("/root/a.rs")+ ));+ assert!(document_selector_matches(+ Some(&selector),+ &context("/root/b.rs")+ ));++ let selector: CompiledDocumentSelector =+ serde_json::from_value(serde_json::json!([{ "pattern": "**/[a.rs" }]))+ .expect("a synced selector with an invalid pattern should deserialize");+ assert!(+ !document_selector_matches(Some(&selector), &context("/root/a.rs")),+ "a selector without any usable filter should match no document",+ );+ }+#[test]fn synced_server_capabilities_wire_format_is_compatible_with_plain_capabilities() {let registrations: dynamic_registration::TextDocumentRegistrations =@@ -17423,11 +17944,11 @@ mod tests {collections::IndexMap::from_iter([("file-completion".to_string(),dynamic_registration::DynamicTextDocumentRegistration {- document_selector: Some(vec![lsp::DocumentFilter {+ document_selector: Some(compiled_selector(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()]),@@ -17562,6 +18083,646 @@ mod tests {DocumentSelectorContext {language_id: Some("rust".to_string()),scheme: "file",+ path: DocumentSelectorPath::Unknown,+ }+ }++ fn toml_file_context(path: DocumentSelectorPath) -> DocumentSelectorContext {+ DocumentSelectorContext {+ language_id: Some("toml".to_string()),+ scheme: "file",+ path,+ }+ }++ fn compiled_selector(document_selector: lsp::DocumentSelector) -> CompiledDocumentSelector {+ CompiledDocumentSelector::new(document_selector).expect("valid document selector")+ }++ fn pattern_selector(+ language: Option<&str>,+ pattern: lsp::GlobPattern,+ ) -> Option<CompiledDocumentSelector> {+ Some(compiled_selector(vec![lsp::DocumentFilter {+ language: language.map(str::to_string),+ scheme: None,+ pattern: Some(pattern),+ }]))+ }++ #[test]+ fn document_selector_pattern_matches_document_path() {+ let selector = pattern_selector(+ Some("toml"),+ lsp::GlobPattern::String("**/Project.toml".to_string()),+ );+ let present = |path: &str| DocumentSelectorPath::present(path, PathStyle::local());++ assert!(document_selector_matches(+ selector.as_ref(),+ &toml_file_context(present(util::path!("/root/Project.toml"))),+ ));+ assert!(!document_selector_matches(+ selector.as_ref(),+ &toml_file_context(present(util::path!("/root/Manifest.toml"))),+ ));+ assert!(+ !document_selector_matches(+ selector.as_ref(),+ &toml_file_context(DocumentSelectorPath::Absent),+ ),+ "a document without a path cannot match a pattern filter",+ );+ assert!(+ document_selector_matches(+ selector.as_ref(),+ &toml_file_context(DocumentSelectorPath::Unknown),+ ),+ "per-language contexts do not evaluate pattern filters",+ );++ let mut context = toml_file_context(present(util::path!("/root/Project.toml")));+ context.language_id = Some("julia".to_string());+ assert!(+ !document_selector_matches(selector.as_ref(), &context),+ "the pattern must not override a mismatching language",+ );+ }++ #[test]+ fn document_selector_pattern_wildcard_does_not_cross_separators() {+ let selector =+ pattern_selector(None, lsp::GlobPattern::String("**/root/*.toml".to_string()));+ let context =+ |path: &str| toml_file_context(DocumentSelectorPath::present(path, PathStyle::local()));++ assert!(document_selector_matches(+ selector.as_ref(),+ &context(util::path!("/root/Project.toml")),+ ));+ assert!(!document_selector_matches(+ selector.as_ref(),+ &context(util::path!("/root/sub/Project.toml")),+ ));+ }++ #[test]+ fn document_selector_relative_pattern_matches_below_base() {+ let selector = pattern_selector(+ None,+ lsp::GlobPattern::Relative(lsp::RelativePattern {+ base_uri: OneOf::Right(lsp::Uri::from_file_path(util::path!("/root")).unwrap()),+ pattern: "sub/*.toml".to_string(),+ }),+ );+ let context =+ |path: &str| toml_file_context(DocumentSelectorPath::present(path, PathStyle::local()));++ assert!(document_selector_matches(+ selector.as_ref(),+ &context(util::path!("/root/sub/Project.toml")),+ ));+ assert!(!document_selector_matches(+ selector.as_ref(),+ &context(util::path!("/other/sub/Project.toml")),+ ));+ assert!(!document_selector_matches(+ selector.as_ref(),+ &context(util::path!("/root/Project.toml")),+ ));+ }++ #[test]+ fn document_selector_relative_pattern_matches_base_document() -> Result<()> {+ for (base_uri, pattern, path, path_style, expected) in [+ (+ "file:///root/a.rs",+ "**",+ "/root/a.rs",+ PathStyle::Unix,+ true,+ ),+ (+ "file:///root/a.rs",+ "**",+ "/root/a.rsx",+ PathStyle::Unix,+ false,+ ),+ ("file:///root/a.rs", "**", "/root", PathStyle::Unix, false),+ (+ "file:///root/a.rs",+ "*.rs",+ "/root/a.rs",+ PathStyle::Unix,+ false,+ ),+ (+ "file:///C:/repo/a.rs",+ "**",+ r"c:\repo\A.rs",+ PathStyle::Windows,+ true,+ ),+ (+ "file:///C:/repo/a.rs",+ "**",+ r"C:\repo\a.rsx",+ PathStyle::Windows,+ false,+ ),+ ] {+ let selector = pattern_selector(+ None,+ lsp::GlobPattern::Relative(lsp::RelativePattern {+ base_uri: OneOf::Right(base_uri.parse()?),+ pattern: pattern.to_string(),+ }),+ );+ let context = toml_file_context(DocumentSelectorPath::present(path, path_style));+ assert_eq!(+ document_selector_matches(selector.as_ref(), &context),+ expected,+ "base {base_uri:?}, pattern {pattern:?}, path {path:?}",+ );+ }+ Ok(())+ }++ #[cfg(unix)]+ #[gpui::test]+ fn document_selector_pattern_matches_windows_remote_worktree(cx: &mut TestAppContext) {+ assert_eq!(PathStyle::local(), PathStyle::Unix);+ let worktree = cx.update(|cx| {+ let settings_store = SettingsStore::test(cx);+ cx.set_global(settings_store);+ Worktree::remote(+ 1,+ clock::ReplicaId::new(1),+ proto::WorktreeMetadata {+ id: 1,+ root_name: "repo".to_string(),+ visible: true,+ abs_path: r"C:\repo".to_string(),+ ..Default::default()+ },+ AnyProtoClient::new(rpc::NoopProtoClient::new()),+ PathStyle::Windows,+ cx,+ )+ });+ cx.read(|cx| {+ let file = File::from_proto(+ proto::File {+ worktree_id: 1,+ path: "sub/Project.toml".to_string(),+ ..Default::default()+ },+ worktree.clone(),+ cx,+ )+ .expect("valid remote file");+ assert!(worktree.read(cx).as_remote().is_some());+ assert!(!file.is_local);+ assert_eq!(+ file.abs_path(cx),+ PathBuf::from(r"C:\repo\sub\Project.toml")+ );+ let context = toml_file_context(DocumentSelectorPath::for_file(&file, cx));+ match &context.path {+ DocumentSelectorPath::Present { path, path_style } => {+ assert_eq!(path, "C:/repo/sub/Project.toml");+ assert_eq!(*path_style, PathStyle::Windows);+ }+ path => panic!("expected the remote file's absolute path, got {path:?}"),+ }+ for (pattern, expected) in [+ ("c:/repo/**/Project.toml", true),+ ("c:/repo/**/Manifest.toml", false),+ ("d:/repo/**/Project.toml", false),+ ] {+ let selector =+ pattern_selector(Some("toml"), lsp::GlobPattern::String(pattern.to_string()));+ assert_eq!(+ document_selector_matches(selector.as_ref(), &context),+ expected,+ "string pattern {pattern:?}",+ );+ }+ for (base_uri, expected) in [+ ("file:///c%3A/repo", true),+ ("file:///d%3A/repo", false),+ ("file:///c%3A/rep", false),+ ] {+ let selector = pattern_selector(+ Some("toml"),+ lsp::GlobPattern::Relative(lsp::RelativePattern {+ base_uri: OneOf::Right(base_uri.parse().expect("valid Windows file URI")),+ pattern: "sub/*.toml".to_string(),+ }),+ );+ assert_eq!(+ document_selector_matches(selector.as_ref(), &context),+ expected,+ "relative pattern base {base_uri:?}",+ );+ }+ });+ }++ #[test]+ fn document_selector_pattern_matches_paths_in_the_host_path_style() {+ // Remote clients match the paths of hosts with another path style than their own.+ let windows_context =+ |path: &str| toml_file_context(DocumentSelectorPath::present(path, PathStyle::Windows));+ let absolute_selector = pattern_selector(+ None,+ lsp::GlobPattern::String("C:/repo/**/Project.toml".to_string()),+ );+ assert!(document_selector_matches(+ absolute_selector.as_ref(),+ &windows_context(r"C:\repo\sub\Project.toml"),+ ));+ assert!(!document_selector_matches(+ absolute_selector.as_ref(),+ &windows_context(r"D:\repo\sub\Project.toml"),+ ));++ let relative_selector = pattern_selector(+ None,+ lsp::GlobPattern::Relative(lsp::RelativePattern {+ base_uri: OneOf::Right("file:///c%3A/repo".parse().unwrap()),+ pattern: "sub/*.toml".to_string(),+ }),+ );+ assert!(+ document_selector_matches(+ relative_selector.as_ref(),+ &windows_context(r"C:\repo\sub\Project.toml"),+ ),+ "the base URI must be read in the host path style, ignoring the drive letter case",+ );+ assert!(!document_selector_matches(+ relative_selector.as_ref(),+ &windows_context(r"C:\repository\sub\Project.toml"),+ ));++ let unix_context = toml_file_context(DocumentSelectorPath::present(+ r"/repo/sub\Project.toml",+ PathStyle::Unix,+ ));+ assert!(+ !document_selector_matches(+ pattern_selector(None, lsp::GlobPattern::String("**/sub/*.toml".to_string()))+ .as_ref(),+ &unix_context,+ ),+ "backslashes are not separators in Unix paths",+ );+ }++ #[test]+ fn document_selector_absolute_pattern_normalizes_windows_drive_letter() {+ for (pattern, path, expected) in [+ ("c:/repo/a.rs", r"C:\repo\a.rs", true),+ ("C:/repo/a.rs", r"c:\repo\a.rs", true),+ ("C:/repo/a.rs", r"C:\repo\a.rs", true),+ ("c:/repo/a.rs", r"c:\repo\a.rs", true),+ ("c:/repo/**/a.rs", r"C:\repo\sub\a.rs", true),+ // Braces can enclose or produce drive prefixes.+ ("{C:/repo,D:/repo}/a.rs", r"C:\repo\a.rs", true),+ ("{c:/repo,d:/repo}/a.rs", r"C:\repo\a.rs", true),+ ("{C,D}:/repo/a.rs", r"c:\repo\a.rs", true),+ ("{D:/repo,E:/repo}/a.rs", r"C:\repo\a.rs", false),+ ("{C:/Repo,D:/repo}/a.rs", r"C:\repo\a.rs", false),+ ("c:/repo/a.rs", r"D:\repo\a.rs", false),+ ("c:/Repo/a.rs", r"C:\repo\a.rs", false),+ ("c:/repo/A.rs", r"C:\repo\a.rs", false),+ ("c:/Équipe/a.rs", r"C:\équipe\a.rs", false),+ ("//server/Share/a.rs", r"\\server\share\a.rs", false),+ ] {+ let selector = pattern_selector(None, lsp::GlobPattern::String(pattern.to_string()));+ let context =+ toml_file_context(DocumentSelectorPath::present(path, PathStyle::Windows));+ assert_eq!(+ document_selector_matches(selector.as_ref(), &context),+ expected,+ "pattern {pattern:?}, path {path:?}",+ );+ }+ }++ #[test]+ fn document_selector_relative_pattern_matches_unicode_windows_base() -> Result<()> {+ for (base_uri, pattern, path, expected) in [+ ("file:///C:/%C3%89quipe", "a.rs", r"C:\équipe\a.rs", true),+ ("file:///c:/%C3%A9quipe", "a.rs", r"C:\Équipe\a.rs", true),+ ("file:///C:/%E2%84%AA", "a.rs", r"c:\k\a.rs", true),+ ("file:///c:/k", "a.rs", r"C:\K\a.rs", true),+ ("file:///C:/%C3%89quipe/", "a.rs", r"c:\équipe\a.rs", true),+ (+ "file://server/%C3%89quipe",+ "a.rs",+ r"\\SERVER\équipe\a.rs",+ true,+ ),+ ("file:///C:/", "Équipe/a.rs", r"c:\Équipe\a.rs", true),+ ("file:///C:/%C3%89quipe", "a.rs", r"C:\équipe\A.rs", false),+ (+ "file:///C:/%C3%89quipe",+ "Sub/a.rs",+ r"C:\équipe\sub\a.rs",+ false,+ ),+ (+ "file:///C:/%C3%89quipe",+ "a.rs",+ r"C:\équipement\a.rs",+ false,+ ),+ ("file:///C:/%E2%84%AA", "a.rs", r"C:\kelvin\a.rs", false),+ ("file:///C:/%C3%89quipe", "a.rs", r"D:\équipe\a.rs", false),+ ] {+ let selector = pattern_selector(+ None,+ lsp::GlobPattern::Relative(lsp::RelativePattern {+ base_uri: OneOf::Right(base_uri.parse()?),+ pattern: pattern.to_string(),+ }),+ );+ let context =+ toml_file_context(DocumentSelectorPath::present(path, PathStyle::Windows));+ assert_eq!(+ document_selector_matches(selector.as_ref(), &context),+ expected,+ "base {base_uri:?}, pattern {pattern:?}, path {path:?}",+ );+ }+ Ok(())+ }++ #[test]+ fn document_selector_patterns_preserve_unix_case() -> Result<()> {+ for pattern in ["/C:/repo/a.rs", "/Équipe/a.rs"] {+ let selector = pattern_selector(None, lsp::GlobPattern::String(pattern.to_string()));+ let context = toml_file_context(DocumentSelectorPath::present(+ &pattern.to_lowercase(),+ PathStyle::Unix,+ ));+ assert!(!document_selector_matches(selector.as_ref(), &context));+ }++ for (base_uri, path, expected) in [+ ("file:///%C3%89quipe", "/équipe/a.rs", false),+ ("file:///%E2%84%AA", "/k/a.rs", false),+ ("file:///%C3%89quipe", "/Équipe/a.rs", true),+ ("file:///", "/a.rs", true),+ ] {+ let selector = pattern_selector(+ None,+ lsp::GlobPattern::Relative(lsp::RelativePattern {+ base_uri: OneOf::Right(base_uri.parse()?),+ pattern: "a.rs".to_string(),+ }),+ );+ let context = toml_file_context(DocumentSelectorPath::present(path, PathStyle::Unix));+ assert_eq!(+ document_selector_matches(selector.as_ref(), &context),+ expected,+ "base {base_uri:?}, path {path:?}",+ );+ }+ Ok(())+ }++ #[test]+ fn document_filter_brace_alternatives_preserve_path_segments() -> Result<()> {+ for (pattern, path, expected) in [+ ("/root/{**,src}/a.rs", "/root/a.rs", true),+ ("/root/{**,src}/a.rs", "/root/sub/a.rs", true),+ ("/root/{**,src}/a.rs", "/root/src/a.rs", true),+ ("/root/{**,src}/a.rs", "/root/b.rs", false),+ ("/root/{**,src}/a.rs", "/rooted/a.rs", false),+ ("/root/{**,src}", "/root", true),+ ("/root/{**,src}/**", "/root", true),+ ("/root/{*,src}*/a.rs", "/root/a.rs", true),+ ("/{root/**,other}/a.rs", "/root/a.rs", true),+ ("/root/{src/,}a.rs", "/root/a.rs", true),+ ("/root/{,src/}a.rs", "/root/src/a.rs", true),+ ("/root/{,src}/a.rs", "/root/a.rs", false),+ ("/root/{,src}/a.rs", "/root//a.rs", true),+ ("/root/{src,{lib,tests}}/a.rs", "/root/lib/a.rs", true),+ ("/root/{src,lib}/{a,b}.rs", "/root/lib/b.rs", true),+ ("/root/{}a.rs", "/root/a.rs", true),+ ] {+ let matcher = compile_document_filter_glob(pattern, false)?;+ assert_eq!(+ matcher.is_match(path),+ expected,+ "pattern {pattern:?}, path {path:?}",+ );+ }+ Ok(())+ }++ #[test]+ fn document_filter_braces_in_character_classes_are_literal() -> Result<()> {+ for (pattern, path, expected) in [+ ("**/{[}],a}.rs", "/root/}.rs", true),+ ("**/{[}],a}.rs", "/root/a.rs", true),+ ("**/{[}],a}.rs", "/root/b.rs", false),+ ("**/[{]/**/a.rs", "/root/{/a.rs", true),+ ("**/[{]/**/a.rs", "/root/{/sub/a.rs", true),+ ("**/[{]/**/a.rs", "/root/other/a.rs", false),+ ("**/{[{],[}]}.rs", "/root/{.rs", true),+ ("**/{[{],[}]}.rs", "/root/}.rs", true),+ ("**/{[]}],a}.rs", "/root/].rs", true),+ ("**/{[]}],a}.rs", "/root/}.rs", true),+ ("**/{[,],a}.rs", "/root/,.rs", true),+ ("**/{[!]],a}.rs", "/root/b.rs", true),+ ("**/{[!]],a}.rs", "/root/].rs", false),+ ] {+ let matcher = compile_document_filter_glob(pattern, false)?;+ assert_eq!(+ matcher.is_match(path),+ expected,+ "pattern {pattern:?}, path {path:?}",+ );+ }+ Ok(())+ }++ #[test]+ fn document_filter_brace_expansion_is_bounded() -> Result<()> {+ assert_eq!(+ expand_glob_braces(&"{a,b}".repeat(8))?.len(),+ DOCUMENT_FILTER_GLOB_MAX_ALTERNATIVES,+ );+ assert!(expand_glob_braces(&"{a,b}".repeat(9)).is_err());++ let empty_alternatives = format!(+ "{{{}}}",+ ",".repeat(DOCUMENT_FILTER_GLOB_MAX_ALTERNATIVES - 1)+ );+ assert_eq!(+ expand_glob_braces(&empty_alternatives)?.len(),+ DOCUMENT_FILTER_GLOB_MAX_ALTERNATIVES,+ );+ let too_many_empty_alternatives =+ format!("{{{}}}", ",".repeat(DOCUMENT_FILTER_GLOB_MAX_ALTERNATIVES));+ assert!(expand_glob_braces(&too_many_empty_alternatives).is_err());++ let at_size_limit = "a".repeat(DOCUMENT_FILTER_GLOB_MAX_BYTES);+ assert_eq!(expand_glob_braces(&at_size_limit)?, vec![at_size_limit]);+ assert!(expand_glob_braces(&"a".repeat(DOCUMENT_FILTER_GLOB_MAX_BYTES + 1)).is_err());+ let deeply_nested = format!("{}a{}", "{".repeat(2048), "}".repeat(2048));+ assert!(expand_glob_braces(&deeply_nested).is_err());+ let large_regex = "*a".repeat(DOCUMENT_FILTER_GLOB_MAX_BYTES / 4);+ assert!(+ compile_document_filter_glob(&large_regex, false)+ .expect_err("the generated regex must also have a bounded size")+ .to_string()+ .contains("compiled pattern size limit")+ );+ Ok(())+ }++ #[test]+ fn document_filter_globstar_runs_match_path_segments() -> Result<()> {+ for (pattern, path, expected) in [+ ("/root/**/**", "/root/a.rs", true),+ ("/root/**/**", "/root/sub/a.rs", true),+ ("/root/**/**", "/root", true),+ ("/root/**/**", "/root/", true),+ ("/root/**/**", "/rooted/a.rs", false),+ ("/root/**", "/rooted/", false),+ ("/root/**/**", "/rooted//a.rs", false),+ ("/root/**", "/root//a.rs", true),+ ("/root/**", "/root/a\nb.rs", true),+ ("/root/**/a.rs", "/root/sub\ndir/a.rs", true),+ ("**", "/root/a\nb.rs", true),+ ("**/**", "/root/a\nb.rs", true),+ ("/**", "", false),+ ("/**", "a.rs", false),+ ("/**", "/", true),+ ("/**", "/a.rs", true),+ ("/", "/", true),+ ("a/", "a", false),+ ("a/", "a/", true),+ ("/root/**/", "/root/sub", false),+ ("/root/**/", "/root/sub/", true),+ ("/root/**/**/**", "/root/a.rs", true),+ ("/root/**/**/a.rs", "/root/a.rs", true),+ ("/root/**/**/a.rs", "/root/sub/a.rs", true),+ ("/root/**/**/a.rs", "/root/sub/b.rs", false),+ ("**/**/a.rs", "a.rs", true),+ ("**/**/a.rs", "/root/sub/a.rs", true),+ ("**/**", "", true),+ ("**/**", "a.rs", true),+ ("**/**", "/root/a.rs", true),+ ("/root/root/**/**", "/root/a.rs", false),+ ("/root/root/**/**", "/root/root/a.rs", true),+ ("/root/**/**/{a.rs,b.rs}", "/root/b.rs", true),+ ] {+ let matcher = compile_document_filter_glob(pattern, false)?;+ assert_eq!(+ matcher.is_match(path),+ expected,+ "pattern {pattern:?}, path {path:?}",+ );+ }+ Ok(())+ }++ #[test]+ fn document_filter_character_classes_do_not_match_separators() -> Result<()> {+ for (pattern, path, expected) in [+ ("**/a[!x]b.rs", "/root/a/b.rs", false),+ ("**/a[!x]b.rs", "/root/axb.rs", false),+ ("**/a[!x]b.rs", "/root/a0b.rs", true),+ ("**/a[!x]b.rs", "/root/aéb.rs", true),+ ("**/a[.-0]b.rs", "/root/a/b.rs", false),+ ("**/a[.-0]b.rs", "/root/a.b.rs", true),+ ("**/a[.-0]b.rs", "/root/a0b.rs", true),+ ("**/a[.-0]b.rs", "/root/a-b.rs", false),+ ("**/a[/]b.rs", "/root/a/b.rs", false),+ ("**/a[!/]b.rs", "/root/a/b.rs", false),+ ("**/a[!/]b.rs", "/root/aéb.rs", true),+ ("**/a[.-/]b.rs", "/root/a/b.rs", false),+ ("**/a[.-/]b.rs", "/root/a.b.rs", true),+ ("**/a[.-/]b.rs", "/root/a-b.rs", false),+ ("**/a[/-0]b.rs", "/root/a/b.rs", false),+ ("**/a[/-0]b.rs", "/root/a0b.rs", true),+ ("**/a[/-0]b.rs", "/root/a-b.rs", false),+ ("**/a[é]b.rs", "/root/aéb.rs", true),+ ("**/a[!é]b.rs", "/root/aéb.rs", false),+ ("**/a[!é]b.rs", "/root/a/b.rs", false),+ ("**/a[[]b.rs", "/root/a[b.rs", true),+ ("**/a[]]b.rs", "/root/a]b.rs", true),+ ("**/a[x-]b.rs", "/root/a-b.rs", true),+ ] {+ let matcher = compile_document_filter_glob(pattern, false)?;+ assert_eq!(+ matcher.is_match(path),+ expected,+ "pattern {pattern:?}, path {path:?}",+ );+ }+ Ok(())+ }++ #[test]+ fn document_filter_pattern_matches_characters() {+ let matches = |pattern: &str, path: &str| {+ DocumentFilterPattern::new(&lsp::GlobPattern::String(pattern.to_string()))+ .expect("valid pattern")+ .matches(path, PathStyle::Unix)+ };++ // `?` and character classes match characters, not bytes.+ assert!(matches("**/?.rs", "/root/a.rs"));+ assert!(matches("**/?.rs", "/root/é.rs"));+ assert!(matches("**/[é].rs", "/root/é.rs"));+ assert!(!matches("**/?.rs", "/root/ab.rs"));++ assert!(matches("**/*.{rs,toml}", "/root/Project.toml"));+ assert!(!matches("**/*.{rs,toml}", "/root/Project.json"));+ assert!(matches("**/[!a].rs", "/root/b.rs"));+ assert!(!matches("**/[!a].rs", "/root/a.rs"));+ assert!(matches("**/[a-c].rs", "/root/b.rs"));+ assert!(!matches("**/[a-c].rs", "/root/d.rs"));++ // A `-` is a range operator only between two members; elsewhere it is literal.+ assert!(matches("**/[--0].rs", "/root/..rs"));+ assert!(!matches("**/[!--0].rs", "/root/..rs"));+ assert!(matches("**/[!--0].rs", "/root/a.rs"));+ assert!(matches("**/[-a].rs", "/root/-.rs"));+ assert!(!matches("**/[-a].rs", "/root/b.rs"));+ assert!(matches("**/[a-].rs", "/root/-.rs"));+ assert!(matches("**/[!-a].rs", "/root/b.rs"));+ assert!(!matches("**/[!-a].rs", "/root/-.rs"));+ assert!(matches("**/[a-c-e].rs", "/root/-.rs"));+ assert!(matches("**/[a-c-e].rs", "/root/e.rs"));+ assert!(!matches("**/[a-c-e].rs", "/root/d.rs"));++ assert!(matches("/root/**", "/root/sub/a.rs"));+ assert!(matches("/root/**/a.rs", "/root/a.rs"));+ assert!(matches("/root/**/a.rs", "/root/sub/a.rs"));+ assert!(!matches("/root/**/a.rs", "/rooted/a.rs"));+ assert!(!matches("/root/*.rs", "/root/sub/a.rs"));++ for invalid_pattern in [+ "**/[a.rs",+ "**/{a,b.rs",+ "**/{[}],a.rs",+ "**/{a,{b,c}",+ "**/[0--].rs",+ ] {+ assert!(+ DocumentFilterPattern::new(&lsp::GlobPattern::String(invalid_pattern.to_string()))+ .is_err(),+ "expected {invalid_pattern:?} to be rejected",+ );}}@@ -17571,11 +18732,11 @@ mod tests {collections::IndexMap::from_iter([("rename-registration".to_string(),dynamic_registration::DynamicTextDocumentRegistration {- document_selector: Some(vec![lsp::DocumentFilter {+ document_selector: Some(compiled_selector(vec![lsp::DocumentFilter {language: Some(language.to_string()),scheme: Some("file".to_string()),pattern: None,- }]),+ }])),server_capabilities: rename_capabilities(),},)])diff --git a/crates/project/src/lsp_store/dynamic_registration.rs b/crates/project/src/lsp_store/dynamic_registration.rsindex 7572f4a5ef8..1ae77ca44d4 100644--- a/crates/project/src/lsp_store/dynamic_registration.rs+++ b/crates/project/src/lsp_store/dynamic_registration.rs@@ -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(())diff --git a/crates/project/src/lsp_store/semantic_tokens.rs b/crates/project/src/lsp_store/semantic_tokens.rsindex 06d3b65fd48..2bb3b00540b 100644--- a/crates/project/src/lsp_store/semantic_tokens.rs+++ b/crates/project/src/lsp_store/semantic_tokens.rs@@ -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)diff --git a/crates/project/tests/integration/dynamic_registration.rs b/crates/project/tests/integration/dynamic_registration.rsindex fdc8f37f409..8b1e0300720 100644--- a/crates/project/tests/integration/dynamic_registration.rs+++ b/crates/project/tests/integration/dynamic_registration.rs@@ -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(diff --git a/crates/project/tests/integration/project_tests.rs b/crates/project/tests/integration/project_tests.rsindex 2887f32b1c0..f1cbd4ce336 100644--- a/crates/project/tests/integration/project_tests.rs+++ b/crates/project/tests/integration/project_tests.rs@@ -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();+ 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+ .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",+ );- 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("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",);}