From da44dd024bddfab97fe33d7f487968f96e966af7 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Mon, 16 Nov 2026 18:40:47 +0800 Subject: [PATCH] =?UTF-8?q?refactor(lsp-engine):=20=E7=B4=A2=E5=BC=95?= =?UTF-8?q?=E6=8E=92=E9=99=A4=E6=94=B9=E7=94=B1=E8=AF=AD=E8=A8=80=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E5=99=A8=E5=A3=B0=E6=98=8E=20indexingExclusions?= =?UTF-8?q?=EF=BC=8CCore=20=E4=B8=8D=E5=86=8D=E8=AF=86=E5=88=AB=20rust-ana?= =?UTF-8?q?lyzer=20=E5=92=8C=20gopls?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LSP 引擎原来按 provider 是 rust 还是 go 决定把排除目录写进 rust-analyzer.files.exclude 还是 gopls.directoryFilters,以及怎样写。 现在语言服务器在清单里声明 indexingExclusions(section、entry、rootEntry、 default、pathSyntax),启动计划的 sessionPolicy 带上它,引擎只按声明把 排除目录追加进服务器读到的配置;没有声明的服务器配置不变。 - plugin-language-servers:新增 IndexingExclusions 及校验,挂在会话字段上 - plugin-server-policy:SessionPolicy 接受并复核 indexingExclusions - lsp-engine:scan_settings 去掉按语言的分支,改为按声明填充 - 契约:README、schema、fixture、invalid-manifests、languages 参考页、 能力对照和协议更新记录 Refs 1lck/Lithe-IDEA#1856 --- rust/crates/lsp-engine/src/configuration.rs | 8 +- rust/crates/lsp-engine/src/engine.rs | 5 + rust/crates/lsp-engine/src/scan_settings.rs | 108 +++++---- rust/crates/lsp-engine/src/state.rs | 4 + rust/crates/lsp-engine/src/tests.rs | 56 +++-- .../src/indexing_exclusions.rs | 216 ++++++++++++++++++ .../crates/plugin-language-servers/src/lib.rs | 18 +- rust/crates/plugin-manifest/src/manifest.rs | 5 +- rust/crates/plugin-server-policy/src/lib.rs | 15 +- shared/plugins/contract/v1/README.md | 53 ++++- .../v1/fixtures/languages/command-plans.json | 9 +- .../language-system-command.plugin.json | 9 +- .../fixtures/manifest/invalid-manifests.json | 4 + .../contract/v1/plugin-manifest.schema.json | 41 ++++ .../reference/capabilities-and-versions.md | 4 +- shared/plugins/reference/domains/languages.md | 46 +++- .../plugins/reference/protocol-changelog.md | 1 + 17 files changed, 522 insertions(+), 80 deletions(-) create mode 100644 rust/crates/plugin-language-servers/src/indexing_exclusions.rs diff --git a/rust/crates/lsp-engine/src/configuration.rs b/rust/crates/lsp-engine/src/configuration.rs index 9628d278..eb3d637b 100644 --- a/rust/crates/lsp-engine/src/configuration.rs +++ b/rust/crates/lsp-engine/src/configuration.rs @@ -155,8 +155,12 @@ impl RuntimeSession { .lock() .map(|configuration| configuration.clone()) .unwrap_or_else(|poisoned| poisoned.into_inner().clone()); - crate::scan_settings::configuration(&self.provider_id, &self.root_uri, base.as_deref()) - .map(Arc::new) + crate::scan_settings::configuration( + self.indexing_exclusions.as_ref(), + &self.root_uri, + base.as_deref(), + ) + .map(Arc::new) } pub(crate) fn update_plugin_configuration( diff --git a/rust/crates/lsp-engine/src/engine.rs b/rust/crates/lsp-engine/src/engine.rs index e166ecb7..d0cd599c 100644 --- a/rust/crates/lsp-engine/src/engine.rs +++ b/rust/crates/lsp-engine/src/engine.rs @@ -177,6 +177,10 @@ impl LspEngine { let request_id = (initialize.state.next_request_id - 1).to_string(); let now = Instant::now(); let process_id = process.handle.process_id(); + let indexing_exclusions = request + .session_policy + .as_ref() + .and_then(|policy| policy.indexing_exclusions.clone()); let plugin_server = request.session_policy.map(PluginServerState::new); let session = Arc::new(RuntimeSession { startup_attempt: Arc::clone(attempt), @@ -191,6 +195,7 @@ impl LspEngine { plugin_id: request.plugin_id, workspace_host: lithe_workspace::current(), plugin_configuration: Mutex::new(workspace_configuration.map(Arc::new)), + indexing_exclusions, root_uri: request.root_uri, indexing_roots: Mutex::default(), indexing_revision: std::sync::atomic::AtomicU64::new(0), diff --git a/rust/crates/lsp-engine/src/scan_settings.rs b/rust/crates/lsp-engine/src/scan_settings.rs index 5625a47b..5cf58b7c 100644 --- a/rust/crates/lsp-engine/src/scan_settings.rs +++ b/rust/crates/lsp-engine/src/scan_settings.rs @@ -1,12 +1,20 @@ -//! Provider-owned native scan settings. These are not build-system exclusions. +//! A server's declared indexing exclusions, written into the workspace +//! configuration it reads. These are not build-system exclusions. +use lithe_plugin_language_servers::IndexingExclusions; use serde_json::{json, Value}; /// Overlay the current policy without mutating the user's stored configuration. -/// Removing exclusions therefore restores the original settings exactly. -pub(crate) fn configuration(provider: &str, root_uri: &str, base: Option<&Value>) -> Option { - if !matches!(provider, "rust" | "go") { +/// Removing exclusions therefore restores the original settings exactly. A +/// server that declares no `indexingExclusions` sees its configuration +/// unchanged; Core never guesses the setting from the server or language. +pub(crate) fn configuration( + exclusions: Option<&IndexingExclusions>, + root_uri: &str, + base: Option<&Value>, +) -> Option { + let Some(exclusions) = exclusions else { return base.cloned(); - } + }; let Some(root) = url::Url::parse(root_uri) .ok() .and_then(|uri| uri.to_file_path().ok()) @@ -18,48 +26,25 @@ pub(crate) fn configuration(provider: &str, root_uri: &str, base: Option<&Value> return base.cloned(); } Some(with_roots( - provider, + exclusions, base, &lithe_project::indexing::excluded_roots(&root), )) } -fn with_roots(provider: &str, base: Option<&Value>, roots: &[String]) -> Value { +fn with_roots(exclusions: &IndexingExclusions, base: Option<&Value>, roots: &[String]) -> Value { let mut configuration = base.cloned().unwrap_or_else(|| json!({})); - match provider { - // rust-analyzer.files.exclude takes literal workspace-relative paths, not globs. - // https://rust-analyzer.github.io/book/configuration#rust-analyzerfilesexclude - "rust" => append_array( - &mut configuration, - &["rust-analyzer", "files", "exclude"], - roots.to_vec(), - &[], - ), - // https://go.dev/gopls/settings#directoryFilters: ordered filters, last match wins. - // Preserve its documented default when the user did not configure this array. - "go" => append_array( - &mut configuration, - &["gopls", "directoryFilters"], - roots - .iter() - .filter(|path| !path.contains(['*', '?', '[', ']', '{', '}'])) - .map(|path| { - if path == "." { - "-".into() - } else { - format!("-{path}") - } - }) - .collect(), - &["-**/node_modules"], - ), - _ => {} - } + append_array( + &mut configuration, + &exclusions.section_keys(), + exclusions.entries(roots), + exclusions.default_entries(), + ); configuration } /// Normalize owned dotted prefixes, so a request for the provider section sees them too. -fn append_array(value: &mut Value, path: &[&str], additions: Vec, defaults: &[&str]) { +fn append_array(value: &mut Value, path: &[&str], additions: Vec, defaults: &[String]) { for length in 2..=path.len() { let dotted = path[..length].join("."); let previous = value @@ -80,8 +65,9 @@ fn append_array(value: &mut Value, path: &[&str], additions: Vec, defaul if let Some(array) = slot.as_array_mut() { for addition in additions { let value = Value::String(addition); - // Go filters are ordered: an existing exclusion before a later inclusion - // must move to the end rather than being treated as a harmless duplicate. + // Filters may be ordered with the last match winning: an existing + // exclusion before a later inclusion must move to the end rather + // than being treated as a harmless duplicate. array.retain(|item| item != &value); array.push(value); } @@ -124,7 +110,7 @@ mod tests { "rust-analyzer.files.exclude":["leaf"] }); let original = base.clone(); - let configured = with_roots("rust", Some(&base), &["vendor".into()]); + let configured = with_roots(&literal(), Some(&base), &["vendor".into()]); assert_eq!( configured["rust-analyzer"]["files"], json!({ @@ -143,7 +129,11 @@ mod tests { #[test] fn native_exclusions_preserve_settings_and_restore_them_on_undo() { let base = json!({"rust-analyzer":{"files":{"exclude":["existing"]},"cargo":{"allFeatures":true}}}); - let excluded = with_roots("rust", Some(&base), &["vendor".into(), "带 空格".into()]); + let excluded = with_roots( + &literal(), + Some(&base), + &["vendor".into(), "带 空格".into()], + ); assert_eq!( excluded["rust-analyzer"]["files"]["exclude"], json!(["existing", "vendor", "带 空格"]) @@ -152,34 +142,56 @@ mod tests { excluded["rust-analyzer"]["cargo"], base["rust-analyzer"]["cargo"] ); - assert_eq!(with_roots("rust", Some(&base), &[]), base); + assert_eq!(with_roots(&literal(), Some(&base), &[]), base); let go = json!({"gopls.directoryFilters":["+vendor","-cache"]}); assert_eq!( - with_roots("go", Some(&go), &["vendor".into()])["gopls"]["directoryFilters"], + with_roots(&glob(), Some(&go), &["vendor".into()])["gopls"]["directoryFilters"], json!(["+vendor", "-cache", "-vendor"]) ); assert_eq!( with_roots( - "go", + &glob(), Some(&json!({"gopls":{"directoryFilters":["-vendor","+vendor"]}})), &["vendor".into()] )["gopls"]["directoryFilters"], json!(["+vendor", "-vendor"]) ); assert_eq!( - with_roots("go", None, &["vendor".into()])["gopls"]["directoryFilters"], - json!(["-**/node_modules", "-vendor"]) + with_roots(&glob(), None, &[".".into(), "vendor".into()])["gopls"]["directoryFilters"], + json!(["-**/node_modules", "-", "-vendor"]) ); } #[test] fn native_patterns_do_not_accidentally_exclude_literal_metacharacter_siblings() { assert_eq!( - with_roots("go", None, &["literal*".into()])["gopls"]["directoryFilters"], + with_roots(&glob(), None, &["literal*".into()])["gopls"]["directoryFilters"], json!(["-**/node_modules"]) ); assert_eq!( - with_roots("rust", None, &["literal*".into()])["rust-analyzer"]["files"]["exclude"], + with_roots(&literal(), None, &["literal*".into()])["rust-analyzer"]["files"]["exclude"], json!(["literal*"]) ); } + + /// A server whose setting takes literal paths, as rust-analyzer's + /// `files.exclude` does. + fn literal() -> IndexingExclusions { + serde_json::from_value( + json!({"section": "rust-analyzer.files.exclude", "entry": "${path}"}), + ) + .unwrap() + } + + /// A server whose setting takes ordered glob filters with a default, as + /// gopls's `directoryFilters` does. + fn glob() -> IndexingExclusions { + serde_json::from_value(json!({ + "section": "gopls.directoryFilters", + "entry": "-${path}", + "rootEntry": "-", + "default": ["-**/node_modules"], + "pathSyntax": "glob" + })) + .unwrap() + } } diff --git a/rust/crates/lsp-engine/src/state.rs b/rust/crates/lsp-engine/src/state.rs index deb226f0..610d8647 100644 --- a/rust/crates/lsp-engine/src/state.rs +++ b/rust/crates/lsp-engine/src/state.rs @@ -118,6 +118,10 @@ pub(crate) struct RuntimeSession { /// Replaced as a whole by `lsp.updateWorkspaceConfiguration`; never held /// across another lock. pub(crate) plugin_configuration: Mutex>>, + /// The setting of `plugin_configuration` that lists the workspace's + /// excluded directories, as the session policy declares it. Without one + /// the configuration is answered unchanged. + pub(crate) indexing_exclusions: Option, /// Workspace URI the server was initialized with; scopes indexing /// exclusions and other workspace-wide checks to this session's root. pub(crate) root_uri: String, diff --git a/rust/crates/lsp-engine/src/tests.rs b/rust/crates/lsp-engine/src/tests.rs index a1541b65..320492f6 100644 --- a/rust/crates/lsp-engine/src/tests.rs +++ b/rust/crates/lsp-engine/src/tests.rs @@ -1759,31 +1759,53 @@ fn indexing_cold_start_resolves_git_before_provider_initialization() { let status = lithe_project::indexing::configure(serde_json::from_value(json!({ "root": root, "manualExcludedDirectories": [], "includedDirectories": [], "gitIgnoreEnabled": true })).unwrap(), crate::indexing_changed).unwrap(); - let harness = Harness::start(|request| { - workspace.configure(request); - request.root_uri = url::Url::from_directory_path(&root).unwrap().to_string(); - }); - assert!(notifications(&harness, "initialize").pop().is_some()); - for (provider, pointer) in [ - ("go", "/gopls/directoryFilters"), - ("rust", "/rust-analyzer/files/exclude"), + let start = |exclusions: Option| { + Harness::start(|request| { + workspace.configure(request); + request.root_uri = url::Url::from_directory_path(&root).unwrap().to_string(); + request.plugin_id = Some("io.example.server".into()); + request.workspace_configuration = Some(json!({"server": {"mode": "full"}})); + request.session_policy = Some( + serde_json::from_value( + json!({"serverID": "server", "indexingExclusions": exclusions}), + ) + .unwrap(), + ); + }) + }; + // The server's declaration alone decides where the exclusions go and how + // one is written; its provider ID plays no part. + for (declaration, pointer, entry) in [ + ( + json!({"section": "server.filters", "entry": "-${path}", "pathSyntax": "glob"}), + "/server/filters", + "-ignored", + ), + ( + json!({"section": "server.files.exclude", "entry": "${path}"}), + "/server/files/exclude", + "ignored", + ), ] { - let value = - crate::scan_settings::configuration(provider, &harness.session().root_uri, None) - .unwrap(); + let harness = start(Some(declaration)); + assert!(notifications(&harness, "initialize").pop().is_some()); + let value = harness.session().plugin_configuration().unwrap(); + assert_eq!(value["server"]["mode"], "full"); assert!(value .pointer(pointer) .unwrap() .as_array() .unwrap() .iter() - .any(|item| item - == if provider == "go" { - "-ignored" - } else { - "ignored" - })); + .any(|item| item == entry)); } + let undeclared = start(None); + assert_eq!( + *undeclared.session().plugin_configuration().unwrap(), + json!({"server": {"mode": "full"}}), + "a server without indexingExclusions keeps its configuration" + ); + drop(undeclared); lithe_project::indexing::release(lithe_project::indexing::ReleaseIndexingRequest { root: root.to_string_lossy().into_owned(), revision: status.revision, diff --git a/rust/crates/plugin-language-servers/src/indexing_exclusions.rs b/rust/crates/plugin-language-servers/src/indexing_exclusions.rs new file mode 100644 index 00000000..41e89e99 --- /dev/null +++ b/rust/crates/plugin-language-servers/src/indexing_exclusions.rs @@ -0,0 +1,216 @@ +//! Indexing exclusions a language server reads from its own settings. +//! +//! Some servers index every directory of the workspace unless one of their +//! own settings lists the directories to skip, and each server names that +//! setting and writes a directory differently. A server therefore declares +//! `indexingExclusions`: the array in its workspace configuration and the +//! form of one entry. The LSP engine fills that array with the workspace's +//! excluded directories, so Core never matches on a language, a server or a +//! tool name to find it. + +use lithe_plugin_model::{invalid, Validation}; +use serde::{Deserialize, Serialize}; + +/// The placeholder `entry` must contain exactly once. +const PATH_PLACEHOLDER: &str = "${path}"; +/// Characters a glob reads as a pattern rather than as part of a name. +const GLOB_METACHARACTERS: [char; 6] = ['*', '?', '[', ']', '{', '}']; +/// Most keys in `section`, and most entries in `default`. +const MAX_SECTION_KEYS: usize = 8; +const MAX_DEFAULT_ENTRIES: usize = 32; +/// Longest `section`, `entry`, `rootEntry` or `default` entry, in UTF-8 bytes. +const MAX_TEXT_BYTES: usize = 256; + +/// `indexingExclusions` of a language server: where its workspace +/// configuration lists excluded directories, and how it writes one. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct IndexingExclusions { + /// Dotted path of the array in the workspace configuration, such as + /// `gopls.directoryFilters`. + section: String, + /// One excluded directory, where `${path}` is its workspace-relative + /// path separated by `/`. + entry: String, + /// The entry for the workspace root itself. Without it the root is + /// `entry` with the path `.`. + #[serde(default, skip_serializing_if = "Option::is_none")] + root_entry: Option, + /// What the server uses when the configuration has no such array. The + /// excluded directories are added after it, so the server's own default + /// still applies. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + default: Vec, + /// How the server reads a path in an entry. + #[serde(default)] + path_syntax: PathSyntax, +} + +/// How a server reads the path in an exclusion entry. +#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub enum PathSyntax { + /// The path is a literal name. + #[default] + Literal, + /// The path is a glob. A directory whose name contains a glob + /// metacharacter cannot be written literally, so it is left out rather + /// than excluding the other directories the pattern would match. + Glob, +} + +impl IndexingExclusions { + /// Checks the declaration at `field`. The engine checks a session + /// policy again with the same rules, since `lsp.startServer` is public. + pub fn validate(&self, field: &str) -> Validation<()> { + let keys = self.section_keys(); + if self.section.len() > MAX_TEXT_BYTES + || keys.len() > MAX_SECTION_KEYS + || keys.iter().any(|key| key.is_empty() || !is_plain_text(key)) + || self.section.contains(char::is_whitespace) + { + return Err(invalid( + format!("{field}.section"), + "section is a dotted path of at most 8 non-empty keys without whitespace.", + )); + } + if !is_entry_text(&self.entry) + || self.entry.matches(PATH_PLACEHOLDER).count() != 1 + || self.entry.replacen(PATH_PLACEHOLDER, "", 1).contains("${") + { + return Err(invalid( + format!("{field}.entry"), + "entry must contain ${path} exactly once and no other template.", + )); + } + if self + .root_entry + .as_deref() + .is_some_and(|entry| !is_literal_entry(entry)) + { + return Err(invalid( + format!("{field}.rootEntry"), + "rootEntry is non-empty literal text without a template.", + )); + } + if self.default.len() > MAX_DEFAULT_ENTRIES + || !self.default.iter().all(|entry| is_literal_entry(entry)) + { + return Err(invalid( + format!("{field}.default"), + "default lists at most 32 non-empty literal entries without a template.", + )); + } + Ok(()) + } + + /// The keys of `section`, outermost first. + pub fn section_keys(&self) -> Vec<&str> { + self.section.split('.').collect() + } + + /// What the server uses when its configuration has no such array. + pub fn default_entries(&self) -> &[String] { + &self.default + } + + /// The entries for `roots`, the workspace-relative excluded directories + /// in order, where `.` is the workspace root. + pub fn entries(&self, roots: &[String]) -> Vec { + roots + .iter() + .filter(|path| { + self.path_syntax == PathSyntax::Literal || !path.contains(GLOB_METACHARACTERS) + }) + .map(|path| match (&self.root_entry, path.as_str()) { + (Some(root), ".") => root.clone(), + _ => self.entry.replacen(PATH_PLACEHOLDER, path, 1), + }) + .collect() + } +} + +/// Text without control characters, at most `MAX_TEXT_BYTES` long. +fn is_plain_text(text: &str) -> bool { + text.len() <= MAX_TEXT_BYTES && !text.contains(char::is_control) +} + +fn is_entry_text(text: &str) -> bool { + !text.is_empty() && is_plain_text(text) +} + +/// An entry used as written: `${` would read as a template that is never +/// expanded. +fn is_literal_entry(text: &str) -> bool { + is_entry_text(text) && !text.contains("${") +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn declaration(value: serde_json::Value) -> IndexingExclusions { + serde_json::from_value(value).unwrap() + } + + #[test] + fn literal_paths_fill_the_entry_template_in_order() { + let exclusions = + declaration(json!({"section": "server.files.exclude", "entry": "${path}"})); + assert_eq!(exclusions.section_keys(), ["server", "files", "exclude"]); + assert_eq!( + exclusions.entries(&[".".into(), "vendor".into(), "带 空格".into(), "a*".into()]), + [".", "vendor", "带 空格", "a*"] + ); + assert!(exclusions.default_entries().is_empty()); + } + + #[test] + fn glob_paths_leave_out_names_with_metacharacters_and_use_the_root_entry() { + let exclusions = declaration(json!({ + "section": "server.directoryFilters", + "entry": "-${path}", + "rootEntry": "-", + "default": ["-**/node_modules"], + "pathSyntax": "glob" + })); + let roots = [".", "vendor", "literal*", "x?", "a[b]", "c{d}", "out/gen"].map(String::from); + assert_eq!(exclusions.entries(&roots), ["-", "-vendor", "-out/gen"]); + assert_eq!(exclusions.default_entries(), ["-**/node_modules"]); + } + + #[test] + fn declarations_are_bounded_and_templates_are_exact() { + let valid = json!({"section": "a.b", "entry": "-${path}"}); + assert!(declaration(valid.clone()).validate("f").is_ok()); + let cases = [ + ("section", json!(""), "f.section"), + ("section", json!("a..b"), "f.section"), + ("section", json!("a b"), "f.section"), + ("section", json!("a.b.c.d.e.f.g.h.i"), "f.section"), + ("entry", json!("-path"), "f.entry"), + ("entry", json!("${path}/${path}"), "f.entry"), + ("entry", json!("${path}${setting:x}"), "f.entry"), + ("rootEntry", json!(""), "f.rootEntry"), + ("rootEntry", json!("${path}"), "f.rootEntry"), + ("default", json!([""]), "f.default"), + ("default", json!(["${path}"]), "f.default"), + ("default", json!(vec!["x"; 33]), "f.default"), + ]; + for (key, value, field) in cases { + let mut candidate = valid.clone(); + candidate[key] = value; + let rejection = declaration(candidate).validate("f").unwrap_err(); + assert_eq!(rejection.field.as_deref(), Some(field), "{key}"); + } + assert!(serde_json::from_value::( + json!({"section": "a", "entry": "${path}", "other": true}) + ) + .is_err()); + assert!(serde_json::from_value::( + json!({"section": "a", "entry": "${path}", "pathSyntax": "regex"}) + ) + .is_err()); + } +} diff --git a/rust/crates/plugin-language-servers/src/lib.rs b/rust/crates/plugin-language-servers/src/lib.rs index 4e1c0a0b..99f82f25 100644 --- a/rust/crates/plugin-language-servers/src/lib.rs +++ b/rust/crates/plugin-language-servers/src/lib.rs @@ -6,7 +6,9 @@ //! time, which server notifications reach the backend, how long per- //! workspace state is kept, and whether the server works on a remote //! workspace. The backend may also resolve the command line each time the -//! server starts (`launch.kind: "backend"`). +//! server starts (`launch.kind: "backend"`). Any server may declare which of +//! its settings lists the workspace's excluded directories +//! (`indexingExclusions`). //! //! Core validates those declarations, turns them into the session policy //! the LSP engine enforces, decodes the backend's launch answer, and selects @@ -21,6 +23,9 @@ use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; use std::collections::{BTreeMap, BTreeSet}; +mod indexing_exclusions; +pub use indexing_exclusions::IndexingExclusions; + /// How long a forwarded request may take when the backend names no timeout, /// in milliseconds. pub const DEFAULT_REQUEST_TIMEOUT_MILLISECONDS: u64 = 60_000; @@ -84,7 +89,7 @@ pub(crate) fn is_host_owned_method(method: &str) -> bool { /// The `languageServers` session fields, flattened into the server's /// declaration. Every field is optional: a server that its backend does not -/// drive declares none of them. +/// drive declares at most `indexingExclusions`. #[derive(Debug, Clone, Default, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct SessionDeclaration { @@ -107,6 +112,9 @@ pub struct SessionDeclaration { /// Whether the server works on a remote workspace; supported when absent. #[serde(default, skip_serializing_if = "Option::is_none")] remote: Option, + /// The setting the engine fills with the workspace's excluded directories. + #[serde(default, skip_serializing_if = "Option::is_none")] + indexing_exclusions: Option, } /// `state` of a language server: the host prunes its per-workspace state @@ -225,6 +233,9 @@ impl SessionDeclaration { .validate() .map_err(|message| invalid(format!("{field}.state.retention"), message))?; } + if let Some(exclusions) = &self.indexing_exclusions { + exclusions.validate(&format!("{field}.indexingExclusions"))?; + } Ok(()) } @@ -251,6 +262,9 @@ impl SessionDeclaration { if let Some(state) = &self.state { policy["state"] = json!(state); } + if let Some(exclusions) = &self.indexing_exclusions { + policy["indexingExclusions"] = json!(exclusions); + } policy } } diff --git a/rust/crates/plugin-manifest/src/manifest.rs b/rust/crates/plugin-manifest/src/manifest.rs index 68f3f5e6..5febe846 100644 --- a/rust/crates/plugin-manifest/src/manifest.rs +++ b/rust/crates/plugin-manifest/src/manifest.rs @@ -260,8 +260,9 @@ pub(crate) struct LanguageServerDeclaration { /// is `immediate`. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) workspace_configuration: Option, - /// Fields that govern what the plugin backend may send to its own server - /// and how the host keeps the server's state. + /// Fields that govern what the plugin backend may send to its own server, + /// how the host keeps the server's state, and which setting lists the + /// workspace's excluded directories. #[serde(flatten)] pub(crate) session: lithe_plugin_language_servers::SessionDeclaration, } diff --git a/rust/crates/plugin-server-policy/src/lib.rs b/rust/crates/plugin-server-policy/src/lib.rs index fb020bf1..c1203a8f 100644 --- a/rust/crates/plugin-server-policy/src/lib.rs +++ b/rust/crates/plugin-server-policy/src/lib.rs @@ -15,8 +15,8 @@ //! failing the session therefore only pick the operations to complete. use lithe_plugin_language_servers::{ - is_protocol_name, matches_pattern, Gate, RemoteSupport, DID_CHANGE_CONFIGURATION, - EXECUTE_COMMAND, + is_protocol_name, matches_pattern, Gate, IndexingExclusions, RemoteSupport, + DID_CHANGE_CONFIGURATION, EXECUTE_COMMAND, }; use lithe_plugin_rpc::{codes, MAX_HOST_NOTIFICATION_BYTES}; use lithe_protocol::{CoreError, ErrorCode}; @@ -69,6 +69,10 @@ pub struct SessionPolicy { /// prunes the directories, so the engine only accepts the field. #[serde(default, rename = "state")] _state: Option, + /// The setting the engine fills with the workspace's excluded + /// directories whenever it answers the server's configuration. + #[serde(default)] + pub indexing_exclusions: Option, } impl SessionPolicy { @@ -111,6 +115,13 @@ impl SessionPolicy { { return Err(invalid("gates")); } + if self + .indexing_exclusions + .as_ref() + .is_some_and(|exclusions| exclusions.validate("indexingExclusions").is_err()) + { + return Err(invalid("indexingExclusions")); + } Ok(()) } } diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index d5916cb3..dc9211cc 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -297,6 +297,7 @@ activation event, and a plugin may consist of grammars alone. | `validationArguments` | Probe that must exit with status 0 before a candidate is used; empty means the host trusts the candidate and lets the LSP handshake decide. | | `runtimeDependencies` | Tools the host must discover and pass to the server, each a tool-definition ID that `requiresTools` lists (see [Tool references](#tool-references)). The host exports each path as `LITHE__PATH` (`LITHE_NODE_PATH`, `LITHE_GO_PATH`; a user-set value takes precedence) and prepends its directory to the server's `PATH`, because servers such as gopls run the tool themselves and an app opened from the Dock does not inherit the shell `PATH`. A project-local copy is never chosen, since servers start automatically when a file opens. | | `initializationOptions` | A JSON object sent as the LSP `initializationOptions`. Every string value inside it is a launch template. | +| `indexingExclusions` | The array in the server's workspace configuration that the host fills with the workspace's excluded directories; see [Indexing exclusions](#indexing-exclusions). | | `hostIntegration` | Reserved. Core implements no host integration, so any ID is refused; see [Language server host integrations](#language-server-host-integrations). | | `requestMethods`, `commands`, `serializedCommands`, `forwardNotifications`, `state`, `remote` | What the plugin backend may ask of the running server and how the host keeps its state; see [Plugin-owned sessions](#plugin-owned-sessions). | @@ -360,6 +361,55 @@ requests by section path from it, and sends value with `lsp.updateWorkspaceConfiguration` when an `immediate` setting changes; the running server receives it without a restart. +#### Indexing exclusions + +The user can exclude workspace directories from indexing, and directories Git +ignores can be excluded too. Many servers index every directory unless one of +their own settings lists the ones to skip. A server whose setting does so +declares `indexingExclusions`, and the host keeps that setting filled; Core +never guesses the setting from the language, the server or the tool. + +| Field | Meaning | +| --- | --- | +| `section` | Dotted path of the array in the workspace configuration, such as `gopls.directoryFilters`; at most 8 non-empty keys without whitespace. | +| `entry` | One excluded directory. `${path}` appears exactly once and is the directory's workspace-relative path separated by `/`; no other template is allowed. | +| `rootEntry` | The entry for the workspace root itself. Without it the root is `entry` with the path `.`. | +| `default` | What the server uses when the configuration has no such array, at most 32 entries. | +| `pathSyntax` | `literal` (default) or `glob`: how the server reads the path. | + +- The host answers `workspace/configuration` and sends + `workspace/didChangeConfiguration` with the excluded directories appended, + in order, to the array at `section`. It never changes the stored + configuration, so removing an exclusion restores the user's array exactly. +- An array the configuration already has is kept and the entries are added + after it; an entry already present moves to the end, because filters such as + gopls's are read in order and the last match wins. Without an array the + host starts from `default`, so the server's own default still applies. +- A configuration written with dotted keys (`"gopls.directoryFilters"`, + `"gopls": {"directoryFilters": …}`) is normalized to nested objects along + `section` before the entries are added; unrelated settings are kept. +- With `glob`, a directory whose name contains `*`, `?`, `[`, `]`, `{` or `}` + is left out, since writing it would exclude every directory the pattern + matches. +- When the excluded directories change, a running server receives + `workspace/didChangeConfiguration` again. A server without + `indexingExclusions` sees its configuration unchanged; the host still stops + sending it the documents, diagnostics and file changes of excluded + directories. +- A text field is at most 256 bytes without control characters, and + `rootEntry` and `default` entries are literal. A violation is + `plugin.manifest.invalid` at `languageServers[].indexingExclusions.`. + +```json +"indexingExclusions": { + "section": "gopls.directoryFilters", + "entry": "-${path}", + "rootEntry": "-", + "default": ["-**/node_modules"], + "pathSyntax": "glob" +} +``` + #### Plugin-owned sessions A plugin backend drives its own server only through what the server @@ -384,7 +434,8 @@ declares. A server may declare: `languageServer.request` permission; declaring the permission without such a server is `plugin.manifest.invalid`. - The launch plan's `sessionPolicy` is these fields as sorted lists plus - `serverID` (the `languageID`) and `gates`. The host sends it unchanged as + `serverID` (the `languageID`), `gates` and, when declared, the server's + `indexingExclusions`. The host sends it unchanged as `lsp.startServer.sessionPolicy`; Core's LSP engine enforces it, so a host cannot widen it and a backend cannot step outside it. - A server with `remote: "unsupported"` is not started for a remote diff --git a/shared/plugins/contract/v1/fixtures/languages/command-plans.json b/shared/plugins/contract/v1/fixtures/languages/command-plans.json index 54cca62c..7cc2dad2 100644 --- a/shared/plugins/contract/v1/fixtures/languages/command-plans.json +++ b/shared/plugins/contract/v1/fixtures/languages/command-plans.json @@ -421,7 +421,14 @@ "serializedCommands": [], "forwardNotifications": [], "remote": "supported", - "gates": [] + "gates": [], + "indexingExclusions": { + "section": "gopls.directoryFilters", + "entry": "-${path}", + "rootEntry": "-", + "default": ["-**/node_modules"], + "pathSyntax": "glob" + } } } } diff --git a/shared/plugins/contract/v1/fixtures/languages/language-system-command.plugin.json b/shared/plugins/contract/v1/fixtures/languages/language-system-command.plugin.json index cb7f00d7..ccbf8466 100644 --- a/shared/plugins/contract/v1/fixtures/languages/language-system-command.plugin.json +++ b/shared/plugins/contract/v1/fixtures/languages/language-system-command.plugin.json @@ -64,7 +64,14 @@ "validationArguments": [ "version" ], - "runtimeDependencies": [{ "tool": "go" }] + "runtimeDependencies": [{ "tool": "go" }], + "indexingExclusions": { + "section": "gopls.directoryFilters", + "entry": "-${path}", + "rootEntry": "-", + "default": ["-**/node_modules"], + "pathSyntax": "glob" + } } ], "executionProviders": [ diff --git a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json index de08480f..a5d75152 100644 --- a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json +++ b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json @@ -885,6 +885,10 @@ {"name": "state retention keeps a workspace for a day at least", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/state/retention/maxAgeDays", "value": 0}], "expectedCode": "plugin.manifest.invalid"}, {"name": "state belongs to a known scope", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/state/scope", "value": "user"}], "expectedCode": "plugin.manifest.invalid"}, {"name": "remote support is supported or unsupported", "base": "language-server-backend-launch.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/remote", "value": "partial"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "an indexing exclusion entry places the path once", "base": "language-system-command.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/indexingExclusions/entry", "value": "-vendor"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "languageServers[0].indexingExclusions.entry"}, + {"name": "an indexing exclusion section names dotted keys", "base": "language-system-command.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/indexingExclusions/section", "value": "gopls..directoryFilters"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "languageServers[0].indexingExclusions.section"}, + {"name": "an indexing exclusion default is literal", "base": "language-system-command.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/indexingExclusions/default", "value": ["-${path}"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "languageServers[0].indexingExclusions.default"}, + {"name": "an indexing exclusion path syntax is literal or glob", "base": "language-system-command.plugin.json", "edits": [{"op": "set", "path": "/languageServers/0/indexingExclusions/pathSyntax", "value": "regex"}], "expectedCode": "plugin.manifest.invalid"}, {"name": "an export states its calling context", "base": "plugin-functions-exporter.plugin.json", "edits": [{"op": "remove", "path": "/pluginFunctions/exports/0/context"}], "expectedCode": "plugin.manifest.invalid"}, {"name": "an export names a context Lithe knows", "base": "plugin-functions-exporter.plugin.json", "edits": [{"op": "set", "path": "/pluginFunctions/exports/0/context", "value": "remote"}], "expectedCode": "plugin.manifest.invalid"}, {"name": "an export is an object, not a bare function ID", "base": "plugin-functions-exporter.plugin.json", "edits": [{"op": "set", "path": "/pluginFunctions/exports/0", "value": "document.format"}], "expectedCode": "plugin.manifest.invalid"}, diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 84a15dd0..124894c9 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -1482,6 +1482,13 @@ "maxItems": 2, "items": { "$ref": "#/$defs/editorDelimiter" } }, + "indexingExclusionLiteral": { + "description": "A literal indexing exclusion entry: non-empty text of at most 256 bytes without control characters or a ${ template.", + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^(?:(?!\\$\\{)[^\\u0000-\\u001f\\u007f-\\u009f])+(?![\\s\\S])" + }, "protocolName": { "description": "An LSP method or command name: non-empty text of at most 256 bytes without whitespace or control characters.", "type": "string", @@ -1553,6 +1560,40 @@ } } }, + "indexingExclusions": { + "description": "The array in workspaceConfiguration the host fills with the workspace's excluded directories, and how the server writes one entry. Without it the server's configuration does not change when directories are excluded.", + "type": "object", + "additionalProperties": false, + "required": ["section", "entry"], + "properties": { + "section": { + "description": "Dotted path of the array, at most 8 non-empty keys without whitespace.", + "type": "string", + "maxLength": 256, + "pattern": "^[^\\s.\\u0000-\\u001f\\u007f-\\u009f]+(\\.[^\\s.\\u0000-\\u001f\\u007f-\\u009f]+){0,7}(?![\\s\\S])" + }, + "entry": { + "description": "One excluded directory. ${path} appears exactly once and is the directory's workspace-relative path separated by /; no other template is allowed.", + "type": "string", + "maxLength": 256, + "pattern": "^(?:(?!\\$\\{)[^\\u0000-\\u001f\\u007f-\\u009f])*\\$\\{path\\}(?:(?!\\$\\{)[^\\u0000-\\u001f\\u007f-\\u009f])*(?![\\s\\S])" + }, + "rootEntry": { + "description": "The entry for the workspace root. Without it the root is entry with the path \".\".", + "$ref": "#/$defs/indexingExclusionLiteral" + }, + "default": { + "description": "What the server uses when the configuration has no such array. The excluded directories are added after it.", + "type": "array", + "maxItems": 32, + "items": { "$ref": "#/$defs/indexingExclusionLiteral" } + }, + "pathSyntax": { + "description": "How the server reads the path. With glob, a directory whose name contains * ? [ ] { or } is left out. literal when absent.", + "enum": ["literal", "glob"] + } + } + }, "remote": { "description": "Whether the server works on a remote workspace. Supported when absent.", "enum": ["supported", "unsupported"] diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index cda71248..bd5a3667 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -42,7 +42,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | --- | --- | --- | --- | --- | | `languages` `0` | `languages[]`:语言 ID、文件扩展名,以及包内 TextMate [`grammar` 与 `configuration`](../contract/v1/README.md#grammars-and-editor-configuration);宿主从包里读取并在编辑器里应用,不启动进程 | ✅ | ✅ | [语言](domains/languages.md) | | `packageTrust` `0` | `vendor.bundledSignatureRequirement`:随宿主发布的发布者签名插件副本按来源信任 | ✅ | 未声明 | [包信任](domains/package-trust.md)、[Trust](../contract/v1/README.md#trust) | -| `languageServers` `0` | `languageServers[]`(启动字段按[启动进程](../contract/v1/README.md#process-start)),包括[`workspaceConfiguration`](../contract/v1/README.md#workspace-configuration)和[插件自有服务器的会话字段](../contract/v1/README.md#plugin-owned-sessions) | ✅ | ✅¹ | [语言](domains/languages.md)、[Language servers](../contract/v1/README.md#language-servers) | +| `languageServers` `0` | `languageServers[]`(启动字段按[启动进程](../contract/v1/README.md#process-start)),包括[`workspaceConfiguration`](../contract/v1/README.md#workspace-configuration)、[`indexingExclusions`](../contract/v1/README.md#indexing-exclusions)和[插件自有服务器的会话字段](../contract/v1/README.md#plugin-owned-sessions) | ✅ | ✅¹ | [语言](domains/languages.md)、[Language servers](../contract/v1/README.md#language-servers) | | `executionProviders` `0` | `executionProviders[]`:用声明的命令运行和发现测试 | ✅ | 未声明 | [语言](domains/languages.md)、[Execution providers](../contract/v1/README.md#execution-providers) | | `settings` `0` | `settings[]` 与 `settingActions[]`,含[放置位置、作用域、生效方式、页面按钮](../contract/v1/README.md#placement-scope-effect-and-page-buttons) | ✅ | ✅ | [插件设置](domains/settings.md)、[Plugin settings](../contract/v1/README.md#plugin-settings) | | `sourceSettings` `0` | 真实配置来源表单、编译器页、私有暂存与显式保存 | ✅ | 待宿主接入 / Pending host integration | [Source-backed settings editors](../contract/v1/README.md#source-backed-settings-editors) | @@ -147,7 +147,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | --- | --- | --- | --- | --- | | `languages` `0` | `languages[]`: language IDs, file extensions, and packaged TextMate [`grammar` and `configuration`](../contract/v1/README.md#grammars-and-editor-configuration); the host reads them from the package and applies them in the editor without starting a process | ✅ | ✅ | [Languages](domains/languages.md) | | `packageTrust` `0` | `vendor.bundledSignatureRequirement`: origin-scoped trust for a host-sealed bundled copy of a publisher-signed plugin | ✅ | Not declared | [Package trust](domains/package-trust.md), [Trust](../contract/v1/README.md#trust) | -| `languageServers` `0` | `languageServers[]` (launch fields as in [Process start](../contract/v1/README.md#process-start)), including [`workspaceConfiguration`](../contract/v1/README.md#workspace-configuration) and the [session fields for a plugin's own server](../contract/v1/README.md#plugin-owned-sessions) | ✅ | ✅¹ | [Languages](domains/languages.md), [Language servers](../contract/v1/README.md#language-servers) | +| `languageServers` `0` | `languageServers[]` (launch fields as in [Process start](../contract/v1/README.md#process-start)), including [`workspaceConfiguration`](../contract/v1/README.md#workspace-configuration), [`indexingExclusions`](../contract/v1/README.md#indexing-exclusions) and the [session fields for a plugin's own server](../contract/v1/README.md#plugin-owned-sessions) | ✅ | ✅¹ | [Languages](domains/languages.md), [Language servers](../contract/v1/README.md#language-servers) | | `executionProviders` `0` | `executionProviders[]`: run and discover tests through the declared commands | ✅ | Not declared | [Languages](domains/languages.md), [Execution providers](../contract/v1/README.md#execution-providers) | | `settings` `0` | `settings[]` and `settingActions[]`, with [placement, scope, effect, and page buttons](../contract/v1/README.md#placement-scope-effect-and-page-buttons) | ✅ | ✅ | [Plugin settings](domains/settings.md), [Plugin settings](../contract/v1/README.md#plugin-settings) | | `sourceSettings` `0` | Native source forms, compiler pages, private staging and explicit Save | ✅ | 待宿主接入 / Pending host integration | [Source-backed settings editors](../contract/v1/README.md#source-backed-settings-editors) | diff --git a/shared/plugins/reference/domains/languages.md b/shared/plugins/reference/domains/languages.md index 851a1452..a4cb0400 100644 --- a/shared/plugins/reference/domains/languages.md +++ b/shared/plugins/reference/domains/languages.md @@ -56,6 +56,7 @@ | `validationArguments` | 候选在使用前必须以状态 0 退出的探针;为空时宿主信任候选,由 LSP 握手决定。 | | `runtimeDependencies` | 宿主要发现并传给服务器的工具,每一项是 `requiresTools` 列出的工具定义 ID。宿主把每个路径导出为 `LITHE__PATH`(用户设置的值优先),并把其目录加到服务器的 `PATH` 前面。项目本地副本不会被选中。 | | `initializationOptions` | 作为 LSP `initializationOptions` 发送的 JSON 对象;其中每个字符串值都是启动模板。 | +| `indexingExclusions` | 服务器工作区配置里由宿主填入工作区排除目录的数组,见“索引排除”。 | | `hostIntegration` | 保留字段,见下一节。 | | `requestMethods`、`commands`、`serializedCommands`、`forwardNotifications`、`state`、`remote` | 后端可以向运行中的服务器发什么,以及宿主怎样保存它的状态,见“插件自有会话”。 | @@ -86,6 +87,25 @@ 语言服务器可以声明 `workspaceConfiguration`:一个对象,其中的字符串叶子可以是 `${setting:}`。Core 用合并后的设置展开它,按节路径回答服务器的 `workspace/configuration` 请求,并在 `initialized` 之后发送 `workspace/didChangeConfiguration`。`immediate` 设置变化时,宿主通过 `lsp.updateWorkspaceConfiguration` 推送新值,运行中的服务器无需重启即可收到。 +#### 索引排除(`indexingExclusions`) + +用户可以把工作区目录排除在索引之外,Git 忽略的目录也可以一起排除。很多服务器默认索引所有目录,只有自己的某个设置列出要跳过的目录时才会跳过。服务器用 `indexingExclusions` 声明这个设置,宿主负责把它填好;Core 不按语言、服务器或工具名去猜是哪个设置。 + +| 字段 | 含义 | +| --- | --- | +| `section` | 工作区配置里数组的点分路径,例如 `gopls.directoryFilters`;最多 8 个不含空白的非空键。 | +| `entry` | 一个排除目录的写法。`${path}` 恰好出现一次,替换为目录相对工作区、以 `/` 分隔的路径;不允许其他模板。 | +| `rootEntry` | 工作区根目录本身的写法。缺省时根目录按 `entry` 写,路径为 `.`。 | +| `default` | 配置里没有这个数组时服务器使用的默认值,最多 32 项。 | +| `pathSyntax` | `literal`(默认)或 `glob`:服务器怎样读路径。 | + +- 宿主回答 `workspace/configuration`、发送 `workspace/didChangeConfiguration` 时,把排除目录按顺序追加到 `section` 指向的数组后面。存储的配置不会被改,所以去掉排除后用户原来的数组原样恢复。 +- 配置里已有数组时保留它,排除项追加在后面;已存在的同一项移到末尾,因为 gopls 这类过滤器按顺序读、最后一条匹配生效。没有数组时从 `default` 开始,服务器自己的默认值仍然生效。 +- 用点分键写的配置(`"gopls.directoryFilters"`、`"gopls": {"directoryFilters": …}`)会先沿 `section` 规整成嵌套对象再追加,无关设置保留。 +- `glob` 时,名字含 `*`、`?`、`[`、`]`、`{` 或 `}` 的目录不写入,否则会把模式匹配到的其他目录也排除掉。 +- 排除目录变化时,运行中的服务器会再收到一次 `workspace/didChangeConfiguration`。没有声明 `indexingExclusions` 的服务器配置不变;宿主仍然不向它发送排除目录里的文档、诊断和文件变化。 +- 文本字段最多 256 字节、不含控制字符,`rootEntry` 和 `default` 的各项是字面文本。违反时是 `plugin.manifest.invalid`,字段为 `languageServers[].indexingExclusions.`。 + ### 后端决定启动方式(`launch.kind: "backend"`) 服务器的命令行取决于启动时才知道的东西(解析出的版本、引导出来的工具、从工程推导的选项)时,不写死 `launch`,让插件后端每次回答: @@ -119,7 +139,7 @@ - 名称是不含空白和控制字符、最多 256 字节的非空文本,在各自列表里唯一。宿主自己发送的方法(`initialize`、`initialized`、`shutdown`、`exit`、`textDocument/didOpen` 等文档同步方法、`workspace/didChangeWorkspaceFolders` 和所有 `$/` 方法)不能出现在 `requestMethods` 或 `forwardNotifications` 里。 - 服务器列出 `requestMethods` 或 `forwardNotifications` 时必须声明 `languageServer.request` 权限;没有这样的服务器却声明该权限,是 `plugin.manifest.invalid`。 -- 启动计划的 `sessionPolicy` 就是这些字段(排序后的列表)加 `serverID`(即 `languageID`)和 `gates`。宿主原样交给 `lsp.startServer.sessionPolicy`,由 Core 的 LSP 引擎执行:宿主不能放宽,后端不能越界。 +- 启动计划的 `sessionPolicy` 就是这些字段(排序后的列表)加 `serverID`(即 `languageID`)、`gates`,以及声明了的 `indexingExclusions`。宿主原样交给 `lsp.startServer.sessionPolicy`,由 Core 的 LSP 引擎执行:宿主不能放宽,后端不能越界。 - 请求必须在 `requestMethods` 里,`workspace/executeCommand` 的 `params.command` 必须在 `commands` 里,否则是 `plugin.host.methodNotDeclared`。通知可以是 `workspace/didChangeConfiguration`,或 `requestMethods` 里除 `workspace/executeCommand` 以外的方法;宿主自己的方法仍然被拒绝。 - 会话必须属于调用方插件,并且正在运行;请求等待最多 `timeoutMilliseconds`(默认 60000,最大 300000),取消时向服务器发 `$/cancelRequest`。服务器的 JSON-RPC 错误不转发 `data`。 - **gate** 是 `{id, until: "notification", method, match}`,由启动应答声明:服务器发出该 `method` 的通知、且参数包含 `match` 的所有成员时才打开。所有 gate 打开之前,`request` 按顺序等待,最多 128 个,第 129 个是 `plugin.host.busy`;通知从不被挡住。 @@ -222,6 +242,7 @@ | [Language servers](../../contract/v1/README.md#language-servers) | 启动方式(含 `backend`)、参数、探测参数、运行时依赖 | | [Language server host integrations](../../contract/v1/README.md#language-server-host-integrations) | 宿主集成(保留字段,Core 不实现) | | [Workspace configuration](../../contract/v1/README.md#workspace-configuration) | `workspaceConfiguration` 的展开与推送 | +| [Indexing exclusions](../../contract/v1/README.md#indexing-exclusions) | `indexingExclusions` 的声明与填充 | | [Plugin-owned sessions](../../contract/v1/README.md#plugin-owned-sessions) | 会话字段、会话策略、gate、状态目录与回收、准备状态 | | [Runtime launch](../../contract/v1/README.md#runtime-launch) | 用 `java` 或 `node` 等工具启动包内入口文件 | | [Tool references](../../contract/v1/README.md#tool-references) | 按工具定义 ID 引用运行时、启动计划里的 `tool` 启动方式 | @@ -308,6 +329,7 @@ The rules for `id`, `fileExtensions`, `fileNames`, `projectFileNames`, and `depe | `validationArguments` | A probe that must exit with status 0 before a candidate is used; empty means the host trusts the candidate and lets the LSP handshake decide. | | `runtimeDependencies` | Tools the host discovers and passes to the server, each a tool-definition ID that `requiresTools` lists. The host exports each path as `LITHE__PATH` (a user-set value takes precedence) and prepends its directory to the server's `PATH`. A project-local copy is never chosen. | | `initializationOptions` | A JSON object sent as the LSP `initializationOptions`. Every string value inside it is a launch template. | +| `indexingExclusions` | The array in the server's workspace configuration that the host fills with the workspace's excluded directories; see "Indexing exclusions". | | `hostIntegration` | Reserved; see the next section. | | `requestMethods`, `commands`, `serializedCommands`, `forwardNotifications`, `state`, `remote` | What the backend may ask of the running server and how the host keeps its state; see "Plugin-owned sessions". | @@ -338,6 +360,25 @@ A plugin that declares a language owns its process-backed features: the host sto A language server may declare `workspaceConfiguration`, an object whose string leaves may be `${setting:}` templates. Core expands it with the merged settings, answers the server's `workspace/configuration` requests by section path, and sends `workspace/didChangeConfiguration` after `initialized`. When an `immediate` setting changes, the host sends the new value with `lsp.updateWorkspaceConfiguration`, and the running server receives it without a restart. +#### Indexing exclusions (`indexingExclusions`) + +The user can exclude workspace directories from indexing, and directories Git ignores can be excluded too. Many servers index every directory unless one of their own settings lists the ones to skip. A server whose setting does so declares `indexingExclusions`, and the host keeps that setting filled; Core never guesses the setting from the language, the server or the tool. + +| Field | Meaning | +| --- | --- | +| `section` | Dotted path of the array in the workspace configuration, such as `gopls.directoryFilters`; at most 8 non-empty keys without whitespace. | +| `entry` | One excluded directory. `${path}` appears exactly once and is the directory's workspace-relative path separated by `/`; no other template is allowed. | +| `rootEntry` | The entry for the workspace root itself. Without it the root is `entry` with the path `.`. | +| `default` | What the server uses when the configuration has no such array, at most 32 entries. | +| `pathSyntax` | `literal` (default) or `glob`: how the server reads the path. | + +- The host answers `workspace/configuration` and sends `workspace/didChangeConfiguration` with the excluded directories appended, in order, to the array at `section`. It never changes the stored configuration, so removing an exclusion restores the user's array exactly. +- An array the configuration already has is kept and the entries are added after it; an entry already present moves to the end, because filters such as gopls's are read in order and the last match wins. Without an array the host starts from `default`, so the server's own default still applies. +- A configuration written with dotted keys (`"gopls.directoryFilters"`, `"gopls": {"directoryFilters": …}`) is normalized to nested objects along `section` before the entries are added; unrelated settings are kept. +- With `glob`, a directory whose name contains `*`, `?`, `[`, `]`, `{` or `}` is left out, since writing it would exclude every directory the pattern matches. +- When the excluded directories change, a running server receives `workspace/didChangeConfiguration` again. A server without `indexingExclusions` sees its configuration unchanged; the host still stops sending it the documents, diagnostics and file changes of excluded directories. +- A text field is at most 256 bytes without control characters, and `rootEntry` and `default` entries are literal. A violation is `plugin.manifest.invalid` at `languageServers[].indexingExclusions.`. + ### Backend-resolved launch (`launch.kind: "backend"`) When a server's command line depends on what is known only at start (a version it resolves, a tool it bootstraps, options derived from the project), do not write `launch`; let the plugin backend answer it each time: @@ -371,7 +412,7 @@ A plugin backend drives its own server only through what the server declares: - A name is non-empty text of at most 256 bytes without whitespace or control characters, unique within its list. The names the host sends itself (`initialize`, `initialized`, `shutdown`, `exit`, the document sync methods such as `textDocument/didOpen`, `workspace/didChangeWorkspaceFolders`, and every `$/` method) cannot appear in `requestMethods` or `forwardNotifications`. - A server that lists `requestMethods` or `forwardNotifications` requires the `languageServer.request` permission; declaring the permission without such a server is `plugin.manifest.invalid`. -- The launch plan's `sessionPolicy` is these fields as sorted lists plus `serverID` (the `languageID`) and `gates`. The host passes it unchanged to `lsp.startServer.sessionPolicy`; Core's LSP engine enforces it, so the host cannot widen it and the backend cannot step outside it. +- The launch plan's `sessionPolicy` is these fields as sorted lists plus `serverID` (the `languageID`), `gates` and, when declared, the server's `indexingExclusions`. The host passes it unchanged to `lsp.startServer.sessionPolicy`; Core's LSP engine enforces it, so the host cannot widen it and the backend cannot step outside it. - A request must be in `requestMethods`, and a `workspace/executeCommand` must carry a `params.command` in `commands`; anything else is `plugin.host.methodNotDeclared`. A notification may be `workspace/didChangeConfiguration`, or a `requestMethods` entry other than `workspace/executeCommand`. The host's own methods stay refused. - The session must belong to the calling plugin and be running. A request waits at most `timeoutMilliseconds` (default 60000, at most 300000); cancelling it sends the server `$/cancelRequest`. A server's JSON-RPC error does not forward its `data`. - A **gate** is `{id, until: "notification", method, match}`, declared by the launch answer. It opens when the server sends a notification with that `method` whose params contain every member of `match`. Until every gate has opened, `request` calls wait in order, at most 128; the 129th is `plugin.host.busy`. Notifications are never held. @@ -474,6 +515,7 @@ Discovery returns `{id: ":workspace", kind: "workspace"}` followed by | [Language servers](../../contract/v1/README.md#language-servers) | Launch kinds (including `backend`), arguments, probe arguments, runtime dependencies | | [Language server host integrations](../../contract/v1/README.md#language-server-host-integrations) | Host integrations (reserved; Core implements none) | | [Workspace configuration](../../contract/v1/README.md#workspace-configuration) | Expanding and pushing `workspaceConfiguration` | +| [Indexing exclusions](../../contract/v1/README.md#indexing-exclusions) | Declaring and filling `indexingExclusions` | | [Plugin-owned sessions](../../contract/v1/README.md#plugin-owned-sessions) | Session fields, session policy, gates, state directories and pruning, preparation status | | [Runtime launch](../../contract/v1/README.md#runtime-launch) | Starting a package entry file with a tool such as `java` or `node` | | [Tool references](../../contract/v1/README.md#tool-references) | Referencing runtimes by tool-definition ID; the `tool` launch in a launch plan | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 53d72397..0ba95176 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -137,6 +137,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | +| [#68](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/68) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-25 | `languageServers` 0 内的补充 | 语言服务器新增可选字段 `indexingExclusions`([1lck/Lithe-IDEA#1856](https://github.com/1lck/Lithe-IDEA/issues/1856)):声明工作区配置里列出排除目录的数组 `section`、一项的写法 `entry`(恰好一个 `${path}`)、根目录写法 `rootEntry?`、配置没有该数组时的 `default?`(最多 32 项)和 `pathSyntax?`(`literal` 默认或 `glob`,`glob` 时名字含通配符的目录不写入)。LSP 引擎只按这份声明把排除目录追加进服务器读到的配置,不再按 `rust`、`go` 识别 rust-analyzer 和 gopls;没有声明的服务器配置不变。启动计划的 `sessionPolicy` 带上这份声明,宿主原样交给 `lsp.startServer`。违反时以 `plugin.manifest.invalid`(字段 `languageServers[].indexingExclusions.`)拒绝。旧宿主不认识这个字段,会拒绝带它的清单,所以 Go 插件要等包含本改动的桌面端发布后再声明。没有新增宿主方法、通知或能力版本。 | | [#61](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/61) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | `languageServers` 0 内的补充 | LSP 引擎在一次会话里保留语言服务器的悬浮提示答案([1lck/Lithe-IDEA#1995](https://github.com/1lck/Lithe-IDEA/issues/1995)):同一文档版本的同一位置,或答案 `range` 在同一行内覆盖的位置,直接用保留的答案完成请求,不再发 `textDocument/hover`。每个会话最多 32 个,先丢最久没用的;空答案、错误、文本超过 64 KiB 的答案和清空之后才到达的答案照常交付但不保留。文档打开、修改、保存、关闭,工作区文件变化,设置或索引排除项变化,运行命令,后端的 `languageServer/request`、`languageServer/notify` 和宿主通知,服务器发来的任何请求和 `$/progress` 结束,以及会话停止时全部清空。`requestCompleted` 的结果形状不变,没有新增方法、字段或能力版本。 | ### 2026-11-15