From 066f9c7817a47b50ea7852ee13e3e9ed18fd0a6d Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Fri, 20 Nov 2026 07:40:37 +0800 Subject: [PATCH 1/4] feat(languages): recognize extensionless documents by their first line --- rust/Cargo.lock | 1 + rust/contracts/rust-core-api.md | 13 ++ rust/crates/core/src/protocol/command.rs | 4 + rust/crates/core/src/runtime/dispatcher.rs | 3 + .../core/src/tests/plugin_editor_resources.rs | 140 ++++++++++++++++++ rust/crates/plugin-manifest/Cargo.toml | 1 + .../plugin-manifest/src/declarations.rs | 21 +-- rust/crates/plugin-manifest/src/first_line.rs | 103 +++++++++++++ rust/crates/plugin-manifest/src/lib.rs | 2 + rust/crates/plugin-manifest/src/manifest.rs | 7 + rust/crates/plugin-manifest/src/validation.rs | 20 ++- rust/crates/plugin-model/src/capabilities.rs | 5 +- shared/plugins/contract/v1/README.md | 24 ++- .../fixtures/languages/first-line.plugin.json | 19 +++ .../contract/v1/plugin-manifest.schema.json | 4 +- .../reference/capabilities-and-versions.md | 2 + shared/plugins/reference/domains/languages.md | 11 +- .../plugins/reference/protocol-changelog.md | 3 + 18 files changed, 365 insertions(+), 18 deletions(-) create mode 100644 rust/crates/plugin-manifest/src/first_line.rs create mode 100644 shared/plugins/contract/v1/fixtures/languages/first-line.plugin.json diff --git a/rust/Cargo.lock b/rust/Cargo.lock index cf1d8b8f..6207bb1a 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1308,6 +1308,7 @@ dependencies = [ "lithe-protocol", "lithe-toolchain", "lithe-vcs", + "regex", "serde", "serde_json", "sha2", diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 8e61ba32..2c087dec 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -485,6 +485,7 @@ or removing a command fails until the table changes in the same commit. | `plugins.installed.lifecycle` | Report installed plugins' enablement and plan confirming an install, enabling, disabling or uninstalling one | | `plugins.declarative.editSettings` | Validate one atomic setting edit batch and return replacement text while preserving unrelated plugins and dormant values | | `plugins.declarative.workspaceConfiguration` | Expand a language server's `workspaceConfiguration` with the merged setting values | +| `languages.matchFirstLine` | Select the first matching registered language for an extensionless document | | `plugins.declarative.decodeGrammar` | Validate independent static editor resources | | `plugins.editorActions.decode` | Validate independent action registration, collection or click results | | `plugins.hostApi.describe` | Describe backend host methods and their required grants from Core's method table | @@ -5175,6 +5176,18 @@ order, forgets the choice if there is one and removes the state, so a later installation starts as a first one. Shared cases are in `rust/fixtures/plugins/installed-lifecycle.json`. +`languages.matchFirstLine` accepts `{firstLine, candidates:[{languageID, +firstLineMatch}]}` and returns `{languageID}`, with `null` for no match. The +host calls it after existing explicit, file-name and extension associations +fail for a dotless basename. Send only the complete first decoded line minus +its terminator. Empty input, CR, LF, NUL and lines over 1024 UTF-8 bytes produce +no match. Never send a truncated prefix. Supply the enabled declarations in +registry precedence order, in batches of up to 64, stopping on the first match. +The result preserves the winning ID unchanged. A malformed batch, language ID +or pattern is an `invalid_request`. Core retains only bounded compiled +declarations and performs no I/O. See the [first-line pattern +contract](../../shared/plugins/contract/v1/README.md#first-line-matching-languages-1). + `plugins.declarative.decodeGrammar` accepts `{ manifest, languageID, grammar }`, where `grammar` is the text the host read from the language's `grammar.path` inside the installed package, and returns `language: { id, fileExtensions, diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 73174887..3de8115b 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -70,6 +70,8 @@ pub enum CoreCommand { Toolchains(ToolchainsCommand), /// Validates a plugin backend's Run start request (`run.decodeStart`). RunDecodeStart, + /// Selects a plugin language from an extensionless document's first line. + LanguagesMatchFirstLine, /// Finds the output links plugin matchers declare in console lines (`outputLinks.match`). OutputLinksMatch, /// Checks a plugin function's answer to an output link (`outputLinks.decodeResolution`). @@ -1189,6 +1191,7 @@ impl CoreCommand { "debug.decodeBackendConfiguration" => { Some(Self::Debug(DebugCommand::DecodeBackendConfiguration)) } + "languages.matchFirstLine" => Some(Self::LanguagesMatchFirstLine), "outputLinks.match" => Some(Self::OutputLinksMatch), "outputLinks.decodeResolution" => Some(Self::OutputLinksDecodeResolution), "build.detect" => Some(Self::Build(BuildCommand::Detect)), @@ -1853,6 +1856,7 @@ mod tests { "toolchains.instantiateLaunch", "run.decodeStart", "debug.decodeBackendConfiguration", + "languages.matchFirstLine", "outputLinks.match", "outputLinks.decodeResolution", "outputStyle.decode", diff --git a/rust/crates/core/src/runtime/dispatcher.rs b/rust/crates/core/src/runtime/dispatcher.rs index 190ee0cb..4cfc9c3a 100644 --- a/rust/crates/core/src/runtime/dispatcher.rs +++ b/rust/crates/core/src/runtime/dispatcher.rs @@ -197,6 +197,9 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon parsed.payload, crate::build::run_decode_start_command::, ), + CoreCommand::LanguagesMatchFirstLine => { + plugin_response(id, parsed.payload, lithe_plugin_manifest::match_first_line) + } CoreCommand::OutputLinksMatch => { plugin_response(id, parsed.payload, lithe_plugin_output_links::match_lines) } diff --git a/rust/crates/core/src/tests/plugin_editor_resources.rs b/rust/crates/core/src/tests/plugin_editor_resources.rs index 9b09b397..52b5f8e0 100644 --- a/rust/crates/core/src/tests/plugin_editor_resources.rs +++ b/rust/crates/core/src/tests/plugin_editor_resources.rs @@ -379,3 +379,143 @@ fn configuration_only_contribution_decodes_without_grammar() { assert!(result["language"]["grammar"].is_null()); assert_eq!(result["language"]["configuration"]["lineComment"], "#"); } + +#[test] +fn first_line_only_language_requires_a_compatible_manifest_and_host() { + let mut plugin = manifest(contract_file!("fixtures/languages/first-line.plugin.json")); + plugin["languages"][0] + .as_object_mut() + .unwrap() + .remove("configuration"); + let validate = |plugin: &Value, versions: &[u32]| { + validate_command(json!({ "manifest": plugin, "hostCapabilities": {"languages": versions} })) + .unwrap() + }; + let outcome = validate(&plugin, &[0, 1]); + assert_eq!(outcome["status"], "ok", "{outcome}"); + assert_eq!( + outcome["plugin"]["languages"][0]["firstLineMatch"], + plugin["languages"][0]["firstLineMatch"] + ); + + let unsupported = validate(&plugin, &[0]); + assert_eq!(unsupported["status"], "rejected"); + assert_eq!(unsupported["error"]["field"], "requires.languages"); + let mut downgraded = plugin; + downgraded["requires"]["languages"] = json!(0); + let invalid = validate(&downgraded, &[0, 1]); + assert_eq!( + invalid["error"]["code"], "plugin.manifest.invalid", + "{invalid}" + ); + assert_eq!(invalid["error"]["field"], "requires.languages"); + + let legacy = validate(&manifest(GRAMMAR_PLUGIN), &[0, 1]); + assert_eq!(legacy["status"], "ok", "{legacy}"); + assert!(legacy["plugin"]["languages"][0] + .get("firstLineMatch") + .is_none()); +} + +#[test] +fn first_line_languages_reject_invalid_and_unbounded_patterns_at_installation() { + let mut plugin = manifest(contract_file!("fixtures/languages/first-line.plugin.json")); + for pattern in [ + "".into(), + "a*".into(), + "[".into(), + "(a)\\1".into(), + "a{10000000}".into(), + "é".repeat(257), + ] { + plugin["languages"][0]["firstLineMatch"] = json!(pattern); + let outcome = validate_command(json!({"manifest": plugin})).unwrap(); + assert_eq!( + outcome["error"]["field"], "languages[0].firstLineMatch", + "{outcome}" + ); + } + plugin["languages"][0]["firstLineMatch"] = Value::Null; + assert_eq!( + validate_command(json!({"manifest": plugin})).unwrap()["status"], + "rejected" + ); +} + +#[test] +fn first_line_matching_keeps_registered_priority_and_never_reads_past_the_line() { + let plugin = manifest(contract_file!("fixtures/languages/first-line.plugin.json")); + let specific = + json!({"languageID":"sample", "firstLineMatch": plugin["languages"][0]["firstLineMatch"]}); + let generic = json!({"languageID":"other", "firstLineMatch": "#!"}); + let choose = |line: &str, candidates: &[Value]| { + let response = lithe_plugin_manifest::match_first_line( + json!({"firstLine":line, "candidates":candidates}), + ) + .unwrap(); + response["languageID"].clone() + }; + for line in [ + "#!/opt/tools/sample", + "#! /usr/bin/env sample3", + "#!/usr/bin/env -S sample3 -f", + ] { + assert_eq!(choose(line, &[specific.clone(), generic.clone()]), "sample"); + assert_eq!(choose(line, &[generic.clone(), specific.clone()]), "other"); + } + for line in [ + "x#!/opt/tools/sample", + "#!/opt/tools/sample-extra", + "#!/opt/tools/sample\0", + "\n#!/opt/tools/sample", + "#!/opt/tools/sample\r", + ] { + assert_eq!(choose(line, std::slice::from_ref(&specific)), Value::Null); + } + assert_eq!( + choose( + &format!("#!{}", "é".repeat(511)), + std::slice::from_ref(&generic) + ), + "other" + ); + assert_eq!( + choose( + &format!("#!{}x", "é".repeat(511)), + std::slice::from_ref(&generic) + ), + Value::Null + ); + assert_eq!(choose("#!/opt/tools/sample", &[]), Value::Null); + // A word boundary alone may match at the start of nonempty text but claims no bytes. + assert_eq!( + choose( + "word", + &[json!({"languageID":"other","firstLineMatch":"\\b"})] + ), + Value::Null + ); +} + +#[test] +fn first_line_matching_validates_the_whole_candidate_batch() { + let entry = json!({"languageID":"sample","firstLineMatch":"#!"}); + let call = |candidates: Vec| { + lithe_plugin_manifest::match_first_line(json!({"firstLine":"#!", "candidates":candidates})) + }; + assert_eq!( + call(vec![entry.clone(); 64]).unwrap()["languageID"], + "sample" + ); + assert!(call(vec![entry.clone(); 65]).is_err()); + assert!(call(vec![ + entry.clone(), + json!({"languageID":"UPPER","firstLineMatch":"#!"}) + ]) + .is_err()); + assert!(call(vec![ + entry, + json!({"languageID":"rest","firstLineMatch":"("}) + ]) + .is_err()); +} diff --git a/rust/crates/plugin-manifest/Cargo.toml b/rust/crates/plugin-manifest/Cargo.toml index 6f1bbf8d..1effaba3 100644 --- a/rust/crates/plugin-manifest/Cargo.toml +++ b/rust/crates/plugin-manifest/Cargo.toml @@ -22,6 +22,7 @@ lithe-project-generators = { path = "../project-generators" } lithe-protocol = { path = "../protocol" } lithe-toolchain = { path = "../toolchain" } lithe-vcs = { path = "../vcs" } +regex = "1.11" serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"] } sha2 = "0.10" diff --git a/rust/crates/plugin-manifest/src/declarations.rs b/rust/crates/plugin-manifest/src/declarations.rs index 954b74ca..f3173b57 100644 --- a/rust/crates/plugin-manifest/src/declarations.rs +++ b/rust/crates/plugin-manifest/src/declarations.rs @@ -3,6 +3,13 @@ use super::*; +pub(crate) fn is_language_id(id: &str) -> bool { + !id.is_empty() + && id.bytes().all(|byte| { + byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"+-_".contains(&byte) + }) +} + impl LanguageDeclaration { pub(crate) fn normalize(&mut self, index: usize) -> Validation<()> { let field = format!("languages[{index}]"); @@ -12,15 +19,7 @@ impl LanguageDeclaration { if let Some(configuration) = &self.configuration { configuration.validate(&format!("{field}.configuration"))?; } - let id = self.id.trim().to_lowercase(); - if id.is_empty() - || id != self.id - || !id.chars().all(|character| { - character.is_ascii_lowercase() - || character.is_ascii_digit() - || "+-_".contains(character) - }) - { + if !is_language_id(&self.id) { return Err(invalid( format!("{field}.id"), "The language ID must be lowercase.", @@ -35,9 +34,13 @@ impl LanguageDeclaration { self.file_extensions = normalized_extensions(&self.file_extensions); self.file_names = normalized_names(&self.file_names); self.project_file_names = normalized_names(&self.project_file_names); + if let Some(pattern) = &self.first_line_match { + first_line::validate_pattern(pattern, &format!("{field}.firstLineMatch"))?; + } if self.file_extensions.is_empty() && self.file_names.is_empty() && self.project_file_names.is_empty() + && self.first_line_match.is_none() { return Err(invalid( field, diff --git a/rust/crates/plugin-manifest/src/first_line.rs b/rust/crates/plugin-manifest/src/first_line.rs new file mode 100644 index 00000000..d52d2682 --- /dev/null +++ b/rust/crates/plugin-manifest/src/first_line.rs @@ -0,0 +1,103 @@ +//! Bounded, data-only first-line language matching for documents with no path association. + +use super::{ + declarations::is_language_id, decode_payload, invalid, CoreError, ErrorCode, Validation, +}; +use regex::{Regex, RegexBuilder}; +use serde::{Deserialize, Deserializer}; +use serde_json::{json, Value}; +use std::collections::VecDeque; +use std::sync::{Arc, Mutex, OnceLock}; + +const MAX_PATTERN_BYTES: usize = 512; +const MAX_FIRST_LINE_BYTES: usize = 1024; +const MAX_CANDIDATES: usize = 64; +const REGEX_SIZE_LIMIT: usize = 256 * 1024; + +/// An omitted declaration is distinct from an explicitly invalid JSON null. +pub(crate) fn present_pattern<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + String::deserialize(d).map(Some) +} + +/// Use the same compiled program on manifest acceptance and on repeated document opens. +/// The cache contains only declaration text and programs, never document content. +fn compiled(source: &str) -> Result, &'static str> { + if source.is_empty() || source.len() > MAX_PATTERN_BYTES { + return Err("A first-line pattern must be 1 to 512 UTF-8 bytes."); + } + type Cache = VecDeque<(String, Arc)>; + static CACHE: OnceLock> = OnceLock::new(); + let cache = CACHE.get_or_init(Mutex::default); + let mut entries = cache.lock().unwrap_or_else(|poison| poison.into_inner()); + if let Some((_, regex)) = entries.iter().find(|(pattern, _)| pattern == source) { + return Ok(Arc::clone(regex)); + } + let regex = RegexBuilder::new(source) + .size_limit(REGEX_SIZE_LIMIT) + .dfa_size_limit(REGEX_SIZE_LIMIT) + .build() + .map_err(|_| "Invalid first-line regular expression or compiled size limit exceeded.")?; + if regex.is_match("") { + return Err("A first-line pattern cannot match empty input."); + } + let regex = Arc::new(regex); + if entries.len() == MAX_CANDIDATES { + entries.pop_front(); + } + entries.push_back((source.to_owned(), Arc::clone(®ex))); + Ok(regex) +} + +pub(crate) fn validate_pattern(source: &str, field: &str) -> Validation<()> { + compiled(source) + .map(|_| ()) + .map_err(|reason| invalid(field, reason)) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Candidate { + #[serde(rename = "languageID")] + language_id: String, + first_line_match: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Request { + candidates: Vec, + first_line: String, +} + +/// `languages.matchFirstLine` selects the first matching registered ID in +/// host-supplied precedence order. The host sends only a complete decoded first +/// line after path and explicit user associations have failed. +pub fn match_first_line(payload: Value) -> Result { + let request: Request = decode_payload(payload, "languages.matchFirstLine")?; + let invalid_request = |message| CoreError::new(ErrorCode::InvalidRequest, message); + if request.candidates.len() > MAX_CANDIDATES { + return Err(invalid_request( + "A first-line request accepts up to 64 candidates.", + )); + } + let line = request.first_line; + let eligible = !line.is_empty() + && line.len() <= MAX_FIRST_LINE_BYTES + && !line.contains(['\0', '\r', '\n']); + let mut selected = None; + for candidate in request.candidates { + if !is_language_id(&candidate.language_id) { + return Err(invalid_request("Invalid first-line candidate language ID.")); + } + let regex = compiled(&candidate.first_line_match).map_err(invalid_request)?; + if eligible + && selected.is_none() + && regex + .find(&line) + .is_some_and(|hit| hit.start() == 0 && !hit.is_empty()) + { + selected = Some(candidate.language_id); + } + } + Ok(json!({"languageID": selected})) +} diff --git a/rust/crates/plugin-manifest/src/lib.rs b/rust/crates/plugin-manifest/src/lib.rs index 14fe219f..f37419e0 100644 --- a/rust/crates/plugin-manifest/src/lib.rs +++ b/rust/crates/plugin-manifest/src/lib.rs @@ -34,6 +34,7 @@ use std::collections::{BTreeMap, BTreeSet}; mod command_installers; mod commands; mod declarations; +mod first_line; mod launch; mod managed_runtimes; mod manifest; @@ -53,6 +54,7 @@ pub use command_installers::{ command_installer_requirements_command, }; pub use commands::*; +pub use first_line::match_first_line; pub use launch::*; pub use managed_runtimes::{managed_runtime_plan_command, managed_runtime_resolution_command}; pub use manifest::*; diff --git a/rust/crates/plugin-manifest/src/manifest.rs b/rust/crates/plugin-manifest/src/manifest.rs index 0918fed7..1ddca59d 100644 --- a/rust/crates/plugin-manifest/src/manifest.rs +++ b/rust/crates/plugin-manifest/src/manifest.rs @@ -230,6 +230,13 @@ pub(crate) struct LanguageDeclaration { pub(crate) file_names: Vec, #[serde(default)] pub(crate) project_file_names: Vec, + /// Optional prefix expression for unassociated extensionless documents (languages 1). + #[serde( + default, + deserialize_with = "crate::first_line::present_pattern", + skip_serializing_if = "Option::is_none" + )] + pub(crate) first_line_match: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) dependencies: Option, /// Syntax highlighting from a package file; see `lithe_plugin_grammar`. diff --git a/rust/crates/plugin-manifest/src/validation.rs b/rust/crates/plugin-manifest/src/validation.rs index 097043ba..4bd81ef9 100644 --- a/rust/crates/plugin-manifest/src/validation.rs +++ b/rust/crates/plugin-manifest/src/validation.rs @@ -141,6 +141,22 @@ impl DeclarativePluginManifest { "Command test discovery needs buildSystems 1.", )); } + if self + .languages + .iter() + .any(|language| language.first_line_match.is_some()) + && self + .requires + .get(capabilities::LANGUAGES) + .copied() + .unwrap_or(0) + < 1 + { + return Err(invalid( + "requires.languages", + "First-line language matching needs languages 1.", + )); + } if self.tool_definitions.iter().any(|definition| { definition.get("category").is_some() || definition.get("audience").is_some() }) && self @@ -254,11 +270,11 @@ impl DeclarativePluginManifest { // Console links alone are a complete plugin: Core matches them. && self.output_link_matchers.is_empty() && self.backend.is_none() - // A grammar alone is a complete highlighting plugin. + // A static editor contribution can be the entire plugin. && !self .languages .iter() - .any(|language| language.grammar.is_some() || language.configuration.is_some()) + .any(|language| language.grammar.is_some() || language.configuration.is_some() || language.first_line_match.is_some()) { return Err(invalid( "languages", diff --git a/rust/crates/plugin-model/src/capabilities.rs b/rust/crates/plugin-model/src/capabilities.rs index 3ce7d39f..c982a30d 100644 --- a/rust/crates/plugin-model/src/capabilities.rs +++ b/rust/crates/plugin-model/src/capabilities.rs @@ -42,7 +42,8 @@ use std::collections::{BTreeMap, BTreeSet}; pub const SUPPORTED_PLUGIN_API_VERSIONS: &[u32] = &[0]; /// `languages[]`: file types and project markers, a TextMate `grammar`, and an -/// editing `configuration`; see `lithe_plugin_grammar`. +/// editing `configuration`; see `lithe_plugin_grammar`. Version 1 adds the +/// optional `firstLineMatch` pattern for extensionless documents. pub const LANGUAGES: &str = "languages"; /// `languageServers[]`: the launch, `workspaceConfiguration`, and the session /// fields a plugin backend uses to talk to its own server (`requestMethods`, @@ -135,7 +136,7 @@ pub const SUPPORTED_CAPABILITIES: &[(&str, &[u32])] = &[ (EXECUTION_PROVIDERS, &[0]), (KEYMAP_IMPORT_PROVIDERS, &[0]), (LANGUAGE_SERVERS, &[0]), - (LANGUAGES, &[0]), + (LANGUAGES, &[0, 1]), (MANAGED_RUNTIMES, &[0, 1]), (OUTPUT_LINK_MATCHERS, &[0]), (PACKAGE_TRUST, &[0]), diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 4e7f6194..01a7bd3d 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -196,12 +196,32 @@ declare it (see [Versioning](#versioning)). ### Languages `id` is lowercase (`[a-z0-9+_-]`). `fileExtensions`, `fileNames`, and -`projectFileNames` are matched case-insensitively; at least one must be -present. A leading dot is optional only in `fileExtensions` (`.php` equals +`projectFileNames` are matched case-insensitively. Each language declares at +least one file name, project marker, extension, or first-line pattern. A leading dot is optional only in `fileExtensions` (`.php` equals `php`). In complete file names, project markers, and management file names it is part of the name, so `.toolrc` and `.env.example` stay hidden-file names. Optional `dependencies` lists `managementFileNames`, `projectDependencyPaths`, and `projectBinaryPaths` relative to the project. +#### First-line matching (languages 1) + +An extensionless script can identify its language with a shebang. Other formats +can declare a signature at the start of the file. Set `requires.languages` to +`1` and supply `languages[].firstLineMatch`, a Rust regular expression of +1–512 UTF-8 bytes. For example, `"firstLineMatch": "^#! */opt/tools/sample(?: |$)"` +matches the interpreter followed by a space or the end of the line. A language +can declare the pattern alone or alongside file names and extensions. Hosts +that only implement `languages: 0` reject plugins requiring version 1. + +The editor tries this fallback only for a text document whose basename +contains no dot, after all existing user and path associations. It matches the +complete decoded first line, excluding its terminator. Empty lines, lines +longer than 1024 UTF-8 bytes and lines containing NUL are ineligible. Core +accepts a match only at the start of the line and only when it consumes text. +Patterns cannot match empty input. The regex compiler and its DFA cache each +have a 256 KiB size limit. Among matching enabled languages the host's existing +registration priority wins. The result is the registered language ID for +editing and language services. Matching reads text and starts no process. + #### Grammars and editor configuration A language has two optional fields, `grammar` and `configuration`. Both are data: the host diff --git a/shared/plugins/contract/v1/fixtures/languages/first-line.plugin.json b/shared/plugins/contract/v1/fixtures/languages/first-line.plugin.json new file mode 100644 index 00000000..771d3609 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/languages/first-line.plugin.json @@ -0,0 +1,19 @@ +{ + "schemaVersion": 0, + "pluginAPIVersion": 0, + "id": "dev.lithe.test.first-line", + "displayName": "First-line fixture", + "version": "1.0.0", + "requires": { "languages": 1 }, + "vendor": { "id": "org.example", "displayName": "Example", "signatureRequirement": "publisherPackage" }, + "permissions": [], + "activationEvents": [], + "languages": [ + { + "id": "sample", + "displayName": "Sample", + "configuration": { "lineComment": "//" }, + "firstLineMatch": "^#![ \\t]*(?:/usr/bin/env[ \\t]+(?:-S[ \\t]+)?|/opt/tools/)sample[0-9]*(?:[ \\t]|$)" + } + ] +} diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 6d85e865..0ea7702e 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -7,6 +7,7 @@ "additionalProperties": false, "required": ["schemaVersion", "id", "displayName", "version", "pluginAPIVersion", "requires", "vendor"], "allOf": [ + {"if": {"required": ["languages"], "properties": {"languages": {"contains": {"required": ["firstLineMatch"]}}}}, "then": {"properties": {"requires": {"required": ["languages"], "properties": {"languages": {"const": 1}}}}}}, {"if": {"required": ["outputLinkMatchers"]}, "then": {"properties": {"requires": {"required": ["outputLinkMatchers"]}}}}, {"if": {"required": ["toolDefinitions"]}, "then": {"properties": {"requires": {"required": ["toolDefinitions"]}}}}, {"if": {"required": ["buildSystems"], "properties": {"buildSystems": {"contains": {"required": ["runConfigurationTypes"]}}}}, "then": {"properties": {"requires": {"required": ["runConfigurationTypes"]}}}}, @@ -41,7 +42,7 @@ "debugAdapters": { "description": "Required exactly when debugAdapters is non-empty. Covers bounded target argument and environment bindings and debugAdapters[].features and defaults. The DAP session itself is negotiated by the adapter in initialize.", "enum": [0] }, "executionProviders": { "enum": [0] }, "languageServers": { "description": "Required exactly when languageServers is non-empty. Covers languageServers[].workspaceConfiguration and the session fields requestMethods, commands, serializedCommands, forwardNotifications, state, and remote.", "enum": [0] }, - "languages": { "description": "Required exactly when languages is non-empty. Covers languages[].grammar, a TextMate grammar, and languages[].configuration.", "enum": [0] }, + "languages": { "description": "Required exactly when languages is non-empty. Covers languages[].grammar and languages[].configuration. Version 1 adds firstLineMatch for extensionless documents.", "enum": [0, 1] }, "managedRuntimes": { "description": "Required exactly when managedRuntimes is present: approved pinned runtime archives, plugin-owned qualification and host-owned installation outside versioned packages. Version 1 adds optional artifact mirror URLs.", "enum": [0, 1] }, "outputLinkMatchers": { "description": "Required exactly when outputLinkMatchers is non-empty.", "enum": [0] }, "packageTrust": { "description": "Required exactly when vendor.bundledSignatureRequirement is present.", "enum": [0] }, @@ -1547,6 +1548,7 @@ "fileExtensions": { "$ref": "#/$defs/fileNameList" }, "fileNames": { "$ref": "#/$defs/fileNameList" }, "projectFileNames": { "$ref": "#/$defs/fileNameList" }, + "firstLineMatch": { "description": "Rust regex matching a nonempty prefix of the complete first line of an unassociated dotless file. At most 512 UTF-8 bytes. Requires languages 1.", "type": "string", "minLength": 1, "maxLength": 512 }, "dependencies": { "type": "object", "additionalProperties": false, diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 57a655e7..06c8db8b 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -41,6 +41,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | 版本 | 内容 | Core | Lithe 桌面端 | 详见 | | --- | --- | --- | --- | --- | | `languages` `0` | `languages[]`:语言 ID、文件扩展名,以及包内 TextMate [`grammar` 与 `configuration`](../contract/v1/README.md#grammars-and-editor-configuration);宿主从包里读取并在编辑器里应用,不启动进程 | ✅ | ✅ | [语言](domains/languages.md) | +| `languages` `1` | 无路径或用户关联的无后缀文件可通过 `firstLineMatch` 匹配首行 | ✅ | 配套宿主接入后声明 | [契约](../contract/v1/README.md#first-line-matching-languages-1) | | `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)、[`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) | @@ -156,6 +157,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | Version | Content | Core | Lithe desktop | See | | --- | --- | --- | --- | --- | | `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) | +| `languages` `1` | `firstLineMatch` recognizes unassociated extensionless files by their first line | ✅ | Requires corresponding host support | [Contract](../contract/v1/README.md#first-line-matching-languages-1) | | `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), [`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) | diff --git a/shared/plugins/reference/domains/languages.md b/shared/plugins/reference/domains/languages.md index 2f2140fd..5e6bfe0a 100644 --- a/shared/plugins/reference/domains/languages.md +++ b/shared/plugins/reference/domains/languages.md @@ -9,7 +9,7 @@ | 项目 | 内容 | | --- | --- | | 清单字段 | `languages`、`languageServers`、`executionProviders`、`outputLinkMatchers` | -| 能力 | `languages`、`languageServers`、`executionProviders`、`outputLinkMatchers`,版本都是 `0`。`languageServers` 的后端启动方式需要 `backend`;会话、输出链接的 `resolve`、内容提供者都需要 `backend` | +| 能力 | `languages`、`languageServers`、`executionProviders`、`outputLinkMatchers`,均有版本 `0`。`languages` 版本 `1` 增加首行匹配。`languageServers` 的后端启动方式需要 `backend`;会话、输出链接的 `resolve`、内容提供者都需要 `backend` | | 协议 | LSP。后端驱动服务器用的 `languageServer/*` 宿主方法和通知见下文,它们属于插件后端的 `litheFunctions` 协议(见[插件后端](backend.md)) | | API 编号 | [API-25](../api-catalog.md#现在能用的-api):语言、语法、LSP。[API-12](../api-catalog.md#现在能用的-api):按 URI scheme 提供的只读文档(`documents/registerContentProvider`)。[API-20](../api-catalog.md#现在能用的-api):语言服务器按工作区的状态目录及其回收。[API-22](../api-catalog.md#现在能用的-api):语言服务器的准备状态(`languageServer/setStatus`)和 Run、测试控制台输出里的链接。插件函数提供的编辑器语言功能见[编辑器](editor.md) | | 权限 | `languageServer.launch`;`executionProviders` 声明 `run`、`test` 时加 `process.run`、`process.test`;`languageServer.request`(服务器列出 `requestMethods` 或 `forwardNotifications` 时才可声明,需要 `backend`);`documents.contentProvider`(需要 `backend`) | @@ -20,6 +20,8 @@ `languages[]` 的 `id`、`fileExtensions`、`fileNames`、`projectFileNames` 和 `dependencies` 的规则见[契约的 Languages 一节](../../contract/v1/README.md#languages)。语法和编辑器配置是纯数据:宿主从包里读取,编辑器直接应用,不启动任何进程。只有语法的插件不需要语言服务器、后端或激活事件。 +无后缀文件可用 `firstLineMatch` 声明开头的特征,例如脚本的 shebang。将 `requires.languages` 设为 `1`,并在 `languages[]` 里填写 Rust 正则表达式。文件的既有语言关联优先,编辑器只检查至多 1024 字节的完整首行。[契约示例](../../contract/v1/README.md#first-line-matching-languages-1) + ```json { "id": "http", @@ -285,7 +287,7 @@ Languages let Lithe recognize a language: identify its files, highlight them wit | Item | Value | | --- | --- | | Manifest fields | `languages`, `languageServers`, `executionProviders`, `outputLinkMatchers` | -| Capabilities | `languages`, `languageServers`, `executionProviders`, `outputLinkMatchers`, each at version `0`. A `languageServers` backend launch needs `backend`; sessions, a matcher's `resolve`, and content providers need `backend` too | +| Capabilities | `languages`, `languageServers`, `executionProviders`, `outputLinkMatchers`, all support version `0`. `languages` version `1` adds first-line matching. A `languageServers` backend launch needs `backend`; sessions, a matcher's `resolve`, and content providers need `backend` too | | Protocols | LSP. The `languageServer/*` host methods and notifications below belong to the plugin backend's `litheFunctions` protocol (see [Plugin backend](backend.md)) | | API IDs | [API-25](../api-catalog.md#apis-usable-now): languages, grammars, LSP. [API-12](../api-catalog.md#apis-usable-now): read-only documents by URI scheme (`documents/registerContentProvider`). [API-20](../api-catalog.md#apis-usable-now): per-workspace state directories of language servers, and their pruning. [API-22](../api-catalog.md#apis-usable-now): language server preparation status (`languageServer/setStatus`) and links in Run and Test output. Editor language features supplied by plugin functions are in [Editor](editor.md) | | Permissions | `languageServer.launch`; `process.run`, `process.test` when an execution provider declares `run` or `test`; `languageServer.request` (only when a server lists `requestMethods` or `forwardNotifications`; needs `backend`); `documents.contentProvider` (needs `backend`) | @@ -296,6 +298,11 @@ Languages let Lithe recognize a language: identify its files, highlight them wit The rules for `id`, `fileExtensions`, `fileNames`, `projectFileNames`, and `dependencies` are in [the contract's Languages section](../../contract/v1/README.md#languages). A grammar and editor configuration are pure data: the host reads them from the package and the editor applies them without starting any process. A plugin with only grammars needs no language server, backend, or activation event. +For extensionless documents set `requires.languages` to `1` and declare a +`firstLineMatch` Rust regex, for example to recognize a shebang. Existing file +associations take priority. The editor checks a complete first line of up to +1024 UTF-8 bytes. [Contract example](../../contract/v1/README.md#first-line-matching-languages-1) + ```json { "id": "http", diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 5bf19364..8b57ba62 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,6 +14,8 @@ ## 待合入 +- [首行语言识别](https://github.com/Lithe-IDEA/Lithe-core-rust/compare/main...codex/2122-first-line-language),[@Mucheen](https://github.com/Mucheen),**`languages` 1**(API-25):`languages[].firstLineMatch` 让插件识别无路径关联的无后缀文档。Core 校验并匹配完整首行,保留原有路径和用户关联优先级。见 [1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)。 + - [#112](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/112),[@Mucheen](https://github.com/Mucheen),**`buildSystems` 1**(API-29):清单新增 `buildSystems[].test.discoveryCommand`,已有测试运行可以独立采用命令或 provider。命令使用现有构建工具,把 `litheTestDiscovery` v0 写到宿主提供的 `${outputFile}`。Core 的 `build.testDiscoveryPlan`、`build.decodeTestDiscovery` 和测试树兼容两种发现来源,检查每条选择器可原样运行,命令尝试沿用 `lithe/build/discoverTests` 的结构化终态。没有新增宿主方法、通知或 SDK 版本。见 [1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)。 ## 按协议查首次出现 @@ -52,6 +54,7 @@ | `keymapImportProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `languageServers` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `languages` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| `languages` | 1 | 待合入 | [首行语言识别](https://github.com/Lithe-IDEA/Lithe-core-rust/compare/main...codex/2122-first-line-language) | | `outputLinkMatchers` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `packageTrust` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `pluginFunctions` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | From 871f12a176303039dc655688af9d269091ff20df Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Fri, 20 Nov 2026 07:45:33 +0800 Subject: [PATCH 2/4] docs(plugins): link languages 1 to its introducing PR --- shared/plugins/reference/protocol-changelog.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 8b57ba62..82a77cd2 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- [首行语言识别](https://github.com/Lithe-IDEA/Lithe-core-rust/compare/main...codex/2122-first-line-language),[@Mucheen](https://github.com/Mucheen),**`languages` 1**(API-25):`languages[].firstLineMatch` 让插件识别无路径关联的无后缀文档。Core 校验并匹配完整首行,保留原有路径和用户关联优先级。见 [1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)。 +- [#127](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/127),[@Mucheen](https://github.com/Mucheen),**`languages` 1**(API-25):`languages[].firstLineMatch` 让插件识别无路径关联的无后缀文档。Core 校验并匹配完整首行,保留原有路径和用户关联优先级。见 [1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)。 - [#112](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/112),[@Mucheen](https://github.com/Mucheen),**`buildSystems` 1**(API-29):清单新增 `buildSystems[].test.discoveryCommand`,已有测试运行可以独立采用命令或 provider。命令使用现有构建工具,把 `litheTestDiscovery` v0 写到宿主提供的 `${outputFile}`。Core 的 `build.testDiscoveryPlan`、`build.decodeTestDiscovery` 和测试树兼容两种发现来源,检查每条选择器可原样运行,命令尝试沿用 `lithe/build/discoverTests` 的结构化终态。没有新增宿主方法、通知或 SDK 版本。见 [1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)。 @@ -54,7 +54,7 @@ | `keymapImportProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `languageServers` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `languages` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | -| `languages` | 1 | 待合入 | [首行语言识别](https://github.com/Lithe-IDEA/Lithe-core-rust/compare/main...codex/2122-first-line-language) | +| `languages` | 1 | 待合入 | [#127](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/127) | | `outputLinkMatchers` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `packageTrust` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `pluginFunctions` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | From 4d45d668223c30e818f67270fb06efd08aef95be Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Fri, 20 Nov 2026 09:02:50 +0800 Subject: [PATCH 3/4] feat(languages): read first-line hints from TextMate grammars --- rust/contracts/rust-core-api.md | 12 ++- .../core/src/tests/plugin_editor_resources.rs | 98 +++++++++---------- rust/crates/plugin-grammar/src/lib.rs | 27 ++++- rust/crates/plugin-manifest/src/commands.rs | 19 ++-- .../plugin-manifest/src/declarations.rs | 4 - rust/crates/plugin-manifest/src/first_line.rs | 20 ++-- rust/crates/plugin-manifest/src/manifest.rs | 7 -- rust/crates/plugin-manifest/src/validation.rs | 20 +--- rust/crates/plugin-model/src/capabilities.rs | 5 +- shared/plugins/contract/v1/README.md | 59 ++++++----- .../fixtures/languages/first-line.plugin.json | 7 +- .../languages/grammars/sample.tmLanguage.json | 7 ++ .../contract/v1/plugin-manifest.schema.json | 4 +- shared/plugins/reference/api-catalog.md | 4 +- .../reference/capabilities-and-versions.md | 2 - shared/plugins/reference/domains/languages.md | 13 +-- .../plugins/reference/protocol-changelog.md | 3 +- 17 files changed, 151 insertions(+), 160 deletions(-) create mode 100644 shared/plugins/contract/v1/fixtures/languages/grammars/sample.tmLanguage.json diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 2c087dec..7eeea0a4 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -5186,15 +5186,17 @@ registry precedence order, in batches of up to 64, stopping on the first match. The result preserves the winning ID unchanged. A malformed batch, language ID or pattern is an `invalid_request`. Core retains only bounded compiled declarations and performs no I/O. See the [first-line pattern -contract](../../shared/plugins/contract/v1/README.md#first-line-matching-languages-1). +contract](../../shared/plugins/contract/v1/README.md#first-line-matching). `plugins.declarative.decodeGrammar` accepts `{ manifest, languageID, grammar }`, where `grammar` is the text the host read from the language's `grammar.path` inside the installed package, and returns `language: { id, fileExtensions, -fileNames, grammar: { kind, scopeName, source }, configuration }`. `kind` is -`textmate`; `source` is the validated original JSON text, byte for byte, which -the editor's TextMate engine parses and registers under `scopeName`, the -grammar's own scope. Hosts run plugin grammars only off the editor UI thread, +fileNames, grammar: { kind, scopeName, source, firstLineMatch? }, configuration }`. +The editor registers the validated `textmate` JSON `source` byte for byte under +`scopeName`. +When present, `firstLineMatch` holds validated optional root-level metadata +for `languages.matchFirstLine`. Unsupported or malformed hints are omitted. +Hosts run plugin grammars only off the editor UI thread, with bounded backtracking and a time budget per line. A grammar Core refuses is `plugin.grammar.invalid` with the failing `field`; a language without static editor resources is `plugin.grammar.unavailable`. Configuration-only diff --git a/rust/crates/core/src/tests/plugin_editor_resources.rs b/rust/crates/core/src/tests/plugin_editor_resources.rs index 52b5f8e0..5527f90d 100644 --- a/rust/crates/core/src/tests/plugin_editor_resources.rs +++ b/rust/crates/core/src/tests/plugin_editor_resources.rs @@ -15,6 +15,8 @@ macro_rules! contract_file { const GRAMMAR_PLUGIN: &str = contract_file!("fixtures/languages/language-grammar.plugin.json"); const HTTP_GRAMMAR: &str = contract_file!("fixtures/languages/grammars/http.tmLanguage.json"); +const FIRST_LINE_PLUGIN: &str = contract_file!("fixtures/languages/first-line.plugin.json"); +const SAMPLE_GRAMMAR: &str = contract_file!("fixtures/languages/grammars/sample.tmLanguage.json"); fn manifest(source: &str) -> Value { serde_json::from_str(source).expect("fixture manifest is JSON") @@ -381,72 +383,62 @@ fn configuration_only_contribution_decodes_without_grammar() { } #[test] -fn first_line_only_language_requires_a_compatible_manifest_and_host() { - let mut plugin = manifest(contract_file!("fixtures/languages/first-line.plugin.json")); - plugin["languages"][0] - .as_object_mut() - .unwrap() - .remove("configuration"); - let validate = |plugin: &Value, versions: &[u32]| { - validate_command(json!({ "manifest": plugin, "hostCapabilities": {"languages": versions} })) - .unwrap() - }; - let outcome = validate(&plugin, &[0, 1]); +fn first_line_grammar_uses_the_existing_language_capability() { + let plugin = manifest(FIRST_LINE_PLUGIN); + let admission = validate_command(json!({ + "manifest": plugin, + "hostCapabilities": { "languages": [0] }, + })) + .unwrap(); + assert_eq!(admission["status"], "ok", "{admission}"); + let outcome = decode_grammar_command(json!({ + "manifest": admission["plugin"], + "languageID": "sample", + "grammar": SAMPLE_GRAMMAR, + })) + .unwrap(); assert_eq!(outcome["status"], "ok", "{outcome}"); + let language = &outcome["language"]; + assert_eq!(language["fileExtensions"], json!(["sample"])); + assert_eq!(language["configuration"]["lineComment"], "//"); + assert_eq!(language["grammar"]["scopeName"], "source.sample"); + assert_eq!(language["grammar"]["source"], SAMPLE_GRAMMAR); assert_eq!( - outcome["plugin"]["languages"][0]["firstLineMatch"], - plugin["languages"][0]["firstLineMatch"] - ); - - let unsupported = validate(&plugin, &[0]); - assert_eq!(unsupported["status"], "rejected"); - assert_eq!(unsupported["error"]["field"], "requires.languages"); - let mut downgraded = plugin; - downgraded["requires"]["languages"] = json!(0); - let invalid = validate(&downgraded, &[0, 1]); - assert_eq!( - invalid["error"]["code"], "plugin.manifest.invalid", - "{invalid}" + language["grammar"]["firstLineMatch"], + manifest(SAMPLE_GRAMMAR)["firstLineMatch"] ); - assert_eq!(invalid["error"]["field"], "requires.languages"); - - let legacy = validate(&manifest(GRAMMAR_PLUGIN), &[0, 1]); - assert_eq!(legacy["status"], "ok", "{legacy}"); - assert!(legacy["plugin"]["languages"][0] - .get("firstLineMatch") - .is_none()); } #[test] -fn first_line_languages_reject_invalid_and_unbounded_patterns_at_installation() { - let mut plugin = manifest(contract_file!("fixtures/languages/first-line.plugin.json")); +fn unsupported_first_line_metadata_keeps_its_grammar() { for pattern in [ - "".into(), - "a*".into(), - "[".into(), - "(a)\\1".into(), - "a{10000000}".into(), - "é".repeat(257), + Value::Null, + json!(42), + json!(""), + json!("a*"), + json!("["), + json!(r"(a)\1"), + json!("a{10000000}"), + json!("é".repeat(257)), ] { - plugin["languages"][0]["firstLineMatch"] = json!(pattern); - let outcome = validate_command(json!({"manifest": plugin})).unwrap(); - assert_eq!( - outcome["error"]["field"], "languages[0].firstLineMatch", - "{outcome}" - ); + let mut grammar = grammar_with(json!([])); + grammar["firstLineMatch"] = pattern; + let source = grammar.to_string(); + let outcome = decode_grammar(&source); + assert_eq!(outcome["status"], "ok", "{outcome}"); + let grammar = &outcome["language"]["grammar"]; + assert!(!grammar.as_object().unwrap().contains_key("firstLineMatch")); + assert_eq!(grammar["scopeName"], "source.test"); + assert_eq!(grammar["source"], source); } - plugin["languages"][0]["firstLineMatch"] = Value::Null; - assert_eq!( - validate_command(json!({"manifest": plugin})).unwrap()["status"], - "rejected" - ); } #[test] fn first_line_matching_keeps_registered_priority_and_never_reads_past_the_line() { - let plugin = manifest(contract_file!("fixtures/languages/first-line.plugin.json")); - let specific = - json!({"languageID":"sample", "firstLineMatch": plugin["languages"][0]["firstLineMatch"]}); + let specific = json!({ + "languageID": "sample", + "firstLineMatch": manifest(SAMPLE_GRAMMAR)["firstLineMatch"], + }); let generic = json!({"languageID":"other", "firstLineMatch": "#!"}); let choose = |line: &str, candidates: &[Value]| { let response = lithe_plugin_manifest::match_first_line( diff --git a/rust/crates/plugin-grammar/src/lib.rs b/rust/crates/plugin-grammar/src/lib.rs index 7b8056e5..60c130e4 100644 --- a/rust/crates/plugin-grammar/src/lib.rs +++ b/rust/crates/plugin-grammar/src/lib.rs @@ -152,9 +152,17 @@ fn grammar_error(field: impl Into, message: impl Into) -> Plugin PluginRejection::at("plugin.grammar.invalid", field, message) } -/// Validates the text of a TextMate grammar file and returns its `scopeName`. -/// Hosts register the original text, which the editor's engine parses itself. -pub fn decode_textmate(text: &str) -> Validation { +/// Metadata read during grammar decoding. The editor still parses the source +/// text itself for highlighting. +pub struct TextmateMetadata { + /// The grammar's validated `scopeName` for editor registration. + pub scope_name: String, + /// The optional root-level pattern for the host to check before matching. + pub first_line_match: Option, +} + +/// Validates a TextMate grammar and returns the metadata for editor registration. +pub fn decode_textmate(text: &str) -> Validation { if text.len() > MAX_GRAMMAR_BYTES { return Err(grammar_error( "grammar", @@ -163,7 +171,7 @@ pub fn decode_textmate(text: &str) -> Validation { } let value: Value = serde_json::from_str(text) .map_err(|error| grammar_error("grammar", format!("The grammar is not JSON: {error}.")))?; - let Value::Object(grammar) = &value else { + let Value::Object(mut grammar) = value else { return Err(grammar_error( "grammar", "A TextMate grammar is a JSON object.", @@ -197,7 +205,16 @@ pub fn decode_textmate(text: &str) -> Validation { if let Some(injections) = grammar.get("injections") { rules.injections(injections, "grammar.injections")?; } - Ok(scope_name) + // Other metadata types were accepted by older hosts. Keep the original + // source available for highlighting regardless of the shape of this hint. + let first_line_match = match grammar.remove("firstLineMatch") { + Some(Value::String(pattern)) => Some(pattern), + _ => None, + }; + Ok(TextmateMetadata { + scope_name, + first_line_match, + }) } /// Walks the rules of a grammar, counting them against [`MAX_RULES`]. diff --git a/rust/crates/plugin-manifest/src/commands.rs b/rust/crates/plugin-manifest/src/commands.rs index 62bd7297..1c98b199 100644 --- a/rust/crates/plugin-manifest/src/commands.rs +++ b/rust/crates/plugin-manifest/src/commands.rs @@ -185,15 +185,22 @@ pub fn decode_grammar_command(payload: Value) -> Result { .grammar .as_ref() .map(|grammar| match grammar.kind { - // The editor's engine parses the original text; Core only - // proves that it can and names the scope it registers. lithe_plugin_grammar::GrammarKind::Textmate => { - lithe_plugin_grammar::decode_textmate(&payload.grammar).map(|scope_name| { - json!({ + lithe_plugin_grammar::decode_textmate(&payload.grammar).map(|metadata| { + let mut decoded = json!({ "kind": grammar.kind, - "scopeName": scope_name, + "scopeName": metadata.scope_name, "source": payload.grammar, - }) + }); + // The optional hint has a different regex dialect + // from the original highlighting source. + if let Some(pattern) = metadata + .first_line_match + .filter(|pattern| crate::first_line::supports_pattern(pattern)) + { + decoded["firstLineMatch"] = json!(pattern); + } + decoded }) } }) diff --git a/rust/crates/plugin-manifest/src/declarations.rs b/rust/crates/plugin-manifest/src/declarations.rs index f3173b57..659e6c19 100644 --- a/rust/crates/plugin-manifest/src/declarations.rs +++ b/rust/crates/plugin-manifest/src/declarations.rs @@ -34,13 +34,9 @@ impl LanguageDeclaration { self.file_extensions = normalized_extensions(&self.file_extensions); self.file_names = normalized_names(&self.file_names); self.project_file_names = normalized_names(&self.project_file_names); - if let Some(pattern) = &self.first_line_match { - first_line::validate_pattern(pattern, &format!("{field}.firstLineMatch"))?; - } if self.file_extensions.is_empty() && self.file_names.is_empty() && self.project_file_names.is_empty() - && self.first_line_match.is_none() { return Err(invalid( field, diff --git a/rust/crates/plugin-manifest/src/first_line.rs b/rust/crates/plugin-manifest/src/first_line.rs index d52d2682..6b8b8336 100644 --- a/rust/crates/plugin-manifest/src/first_line.rs +++ b/rust/crates/plugin-manifest/src/first_line.rs @@ -1,10 +1,8 @@ //! Bounded, data-only first-line language matching for documents with no path association. -use super::{ - declarations::is_language_id, decode_payload, invalid, CoreError, ErrorCode, Validation, -}; +use super::{declarations::is_language_id, decode_payload, CoreError, ErrorCode}; use regex::{Regex, RegexBuilder}; -use serde::{Deserialize, Deserializer}; +use serde::Deserialize; use serde_json::{json, Value}; use std::collections::VecDeque; use std::sync::{Arc, Mutex, OnceLock}; @@ -14,12 +12,7 @@ const MAX_FIRST_LINE_BYTES: usize = 1024; const MAX_CANDIDATES: usize = 64; const REGEX_SIZE_LIMIT: usize = 256 * 1024; -/// An omitted declaration is distinct from an explicitly invalid JSON null. -pub(crate) fn present_pattern<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { - String::deserialize(d).map(Some) -} - -/// Use the same compiled program on manifest acceptance and on repeated document opens. +/// Use the same compiled program in grammar decoding and on repeated document opens. /// The cache contains only declaration text and programs, never document content. fn compiled(source: &str) -> Result, &'static str> { if source.is_empty() || source.len() > MAX_PATTERN_BYTES { @@ -48,10 +41,9 @@ fn compiled(source: &str) -> Result, &'static str> { Ok(regex) } -pub(crate) fn validate_pattern(source: &str, field: &str) -> Validation<()> { - compiled(source) - .map(|_| ()) - .map_err(|reason| invalid(field, reason)) +/// Whether a grammar hint uses the syntax and budget of the first-line matcher. +pub(crate) fn supports_pattern(source: &str) -> bool { + compiled(source).is_ok() } #[derive(Deserialize)] diff --git a/rust/crates/plugin-manifest/src/manifest.rs b/rust/crates/plugin-manifest/src/manifest.rs index 1ddca59d..0918fed7 100644 --- a/rust/crates/plugin-manifest/src/manifest.rs +++ b/rust/crates/plugin-manifest/src/manifest.rs @@ -230,13 +230,6 @@ pub(crate) struct LanguageDeclaration { pub(crate) file_names: Vec, #[serde(default)] pub(crate) project_file_names: Vec, - /// Optional prefix expression for unassociated extensionless documents (languages 1). - #[serde( - default, - deserialize_with = "crate::first_line::present_pattern", - skip_serializing_if = "Option::is_none" - )] - pub(crate) first_line_match: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) dependencies: Option, /// Syntax highlighting from a package file; see `lithe_plugin_grammar`. diff --git a/rust/crates/plugin-manifest/src/validation.rs b/rust/crates/plugin-manifest/src/validation.rs index 4bd81ef9..097043ba 100644 --- a/rust/crates/plugin-manifest/src/validation.rs +++ b/rust/crates/plugin-manifest/src/validation.rs @@ -141,22 +141,6 @@ impl DeclarativePluginManifest { "Command test discovery needs buildSystems 1.", )); } - if self - .languages - .iter() - .any(|language| language.first_line_match.is_some()) - && self - .requires - .get(capabilities::LANGUAGES) - .copied() - .unwrap_or(0) - < 1 - { - return Err(invalid( - "requires.languages", - "First-line language matching needs languages 1.", - )); - } if self.tool_definitions.iter().any(|definition| { definition.get("category").is_some() || definition.get("audience").is_some() }) && self @@ -270,11 +254,11 @@ impl DeclarativePluginManifest { // Console links alone are a complete plugin: Core matches them. && self.output_link_matchers.is_empty() && self.backend.is_none() - // A static editor contribution can be the entire plugin. + // A grammar alone is a complete highlighting plugin. && !self .languages .iter() - .any(|language| language.grammar.is_some() || language.configuration.is_some() || language.first_line_match.is_some()) + .any(|language| language.grammar.is_some() || language.configuration.is_some()) { return Err(invalid( "languages", diff --git a/rust/crates/plugin-model/src/capabilities.rs b/rust/crates/plugin-model/src/capabilities.rs index c982a30d..3ce7d39f 100644 --- a/rust/crates/plugin-model/src/capabilities.rs +++ b/rust/crates/plugin-model/src/capabilities.rs @@ -42,8 +42,7 @@ use std::collections::{BTreeMap, BTreeSet}; pub const SUPPORTED_PLUGIN_API_VERSIONS: &[u32] = &[0]; /// `languages[]`: file types and project markers, a TextMate `grammar`, and an -/// editing `configuration`; see `lithe_plugin_grammar`. Version 1 adds the -/// optional `firstLineMatch` pattern for extensionless documents. +/// editing `configuration`; see `lithe_plugin_grammar`. pub const LANGUAGES: &str = "languages"; /// `languageServers[]`: the launch, `workspaceConfiguration`, and the session /// fields a plugin backend uses to talk to its own server (`requestMethods`, @@ -136,7 +135,7 @@ pub const SUPPORTED_CAPABILITIES: &[(&str, &[u32])] = &[ (EXECUTION_PROVIDERS, &[0]), (KEYMAP_IMPORT_PROVIDERS, &[0]), (LANGUAGE_SERVERS, &[0]), - (LANGUAGES, &[0, 1]), + (LANGUAGES, &[0]), (MANAGED_RUNTIMES, &[0, 1]), (OUTPUT_LINK_MATCHERS, &[0]), (PACKAGE_TRUST, &[0]), diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 01a7bd3d..1ceb55af 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -196,32 +196,12 @@ declare it (see [Versioning](#versioning)). ### Languages `id` is lowercase (`[a-z0-9+_-]`). `fileExtensions`, `fileNames`, and -`projectFileNames` are matched case-insensitively. Each language declares at -least one file name, project marker, extension, or first-line pattern. A leading dot is optional only in `fileExtensions` (`.php` equals +`projectFileNames` are matched case-insensitively; at least one must be +present. A leading dot is optional only in `fileExtensions` (`.php` equals `php`). In complete file names, project markers, and management file names it is part of the name, so `.toolrc` and `.env.example` stay hidden-file names. Optional `dependencies` lists `managementFileNames`, `projectDependencyPaths`, and `projectBinaryPaths` relative to the project. -#### First-line matching (languages 1) - -An extensionless script can identify its language with a shebang. Other formats -can declare a signature at the start of the file. Set `requires.languages` to -`1` and supply `languages[].firstLineMatch`, a Rust regular expression of -1–512 UTF-8 bytes. For example, `"firstLineMatch": "^#! */opt/tools/sample(?: |$)"` -matches the interpreter followed by a space or the end of the line. A language -can declare the pattern alone or alongside file names and extensions. Hosts -that only implement `languages: 0` reject plugins requiring version 1. - -The editor tries this fallback only for a text document whose basename -contains no dot, after all existing user and path associations. It matches the -complete decoded first line, excluding its terminator. Empty lines, lines -longer than 1024 UTF-8 bytes and lines containing NUL are ineligible. Core -accepts a match only at the start of the line and only when it consumes text. -Patterns cannot match empty input. The regex compiler and its DFA cache each -have a 256 KiB size limit. Among matching enabled languages the host's existing -registration priority wins. The result is the registered language ID for -editing and language services. Matching reads text and starts no process. - #### Grammars and editor configuration A language has two optional fields, `grammar` and `configuration`. Both are data: the host @@ -281,17 +261,17 @@ activation event, and a plugin may consist of grammars alone. or `1`), and Core refuses a grammar where one of them has another type. Captures are an object keyed by group number or an array by position; object keys that are not group numbers are ignored. Every other key, such as - `comment`, `fileTypes`, `firstLineMatch`, or `uuid`, is ignored and not - checked. + `comment`, `fileTypes`, or `uuid`, is ignored. Root-level `firstLineMatch` + is optional [file association metadata](#first-line-matching). - Core accepts at most 2 MiB, 16384 rules counting every pattern, repository entry, and capture, rules nested 32 deep, regexes of 32 KiB, capture group 4096, `name` and `contentName` of 1024 bytes, `include` targets and repository keys of 256 bytes, and 64 injections with selectors of 1024 bytes. VS Code's own grammars, the largest of which is C++ at 662 KiB and 3165 rules, are well within these bounds. -- Regexes use the Oniguruma syntax TextMate grammars are written in. Core does - not compile them: a pattern the editor's engine cannot compile never - matches, and the rest of the grammar still applies. +- Highlighting rules use the Oniguruma syntax TextMate grammars are written + in. The editor compiles them. An unsupported rule never matches, and the + rest of the grammar still applies. - `include` is `$self`, `$base`, `#name` for a repository entry, or `scope` or `scope#name` for another grammar. Another grammar resolves against those the editor has, its own and those of enabled plugins, which is how a grammar @@ -319,6 +299,31 @@ activation event, and a plugin may consist of grammars alone. grammar cannot stall editing; a line not yet tokenized, or that the grammar could not tokenize within that budget, is drawn as plain text. +#### First-line matching + +A packaged TextMate grammar can add an optional root-level `firstLineMatch` +pattern for extensionless scripts or formats with a signature on the first +line. The package uses its existing `languages: 0` declaration and points +`grammar.path` at the grammar file. Earlier hosts ignore the hint and can +still install the package and apply its existing file associations and +highlighting. See the [fixture manifest](fixtures/languages/first-line.plugin.json) +and [grammar](fixtures/languages/grammars/sample.tmLanguage.json). + +Core interprets this hint as a Rust regular expression of 1–512 UTF-8 bytes. +For example, `"firstLineMatch": "^#! */opt/tools/sample(?: |$)"` matches the +interpreter followed by a space or the end of the line. The pattern cannot +match empty input. The regex compiler and its DFA cache each have a 256 KiB +size limit. Unsupported or invalid hints are treated as absent. The original +grammar source continues to supply highlighting rules. + +The editor tries this hint for text whose basename contains no dot, after +existing user and path associations. It checks only the complete decoded +first line without the terminator. Empty lines, lines longer than 1024 UTF-8 +bytes and lines containing CR, LF or NUL are ineligible. A match must consume +text at the start of the line. The first match in the enabled language +registry supplies the language ID for editing and for language services. +The matcher reads text without starting a process. + ### Language servers | Field | Meaning | diff --git a/shared/plugins/contract/v1/fixtures/languages/first-line.plugin.json b/shared/plugins/contract/v1/fixtures/languages/first-line.plugin.json index 771d3609..00f0727f 100644 --- a/shared/plugins/contract/v1/fixtures/languages/first-line.plugin.json +++ b/shared/plugins/contract/v1/fixtures/languages/first-line.plugin.json @@ -4,7 +4,7 @@ "id": "dev.lithe.test.first-line", "displayName": "First-line fixture", "version": "1.0.0", - "requires": { "languages": 1 }, + "requires": { "languages": 0 }, "vendor": { "id": "org.example", "displayName": "Example", "signatureRequirement": "publisherPackage" }, "permissions": [], "activationEvents": [], @@ -12,8 +12,9 @@ { "id": "sample", "displayName": "Sample", - "configuration": { "lineComment": "//" }, - "firstLineMatch": "^#![ \\t]*(?:/usr/bin/env[ \\t]+(?:-S[ \\t]+)?|/opt/tools/)sample[0-9]*(?:[ \\t]|$)" + "fileExtensions": ["sample"], + "grammar": { "kind": "textmate", "path": "grammars/sample.tmLanguage.json" }, + "configuration": { "lineComment": "//" } } ] } diff --git a/shared/plugins/contract/v1/fixtures/languages/grammars/sample.tmLanguage.json b/shared/plugins/contract/v1/fixtures/languages/grammars/sample.tmLanguage.json new file mode 100644 index 00000000..f106e841 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/languages/grammars/sample.tmLanguage.json @@ -0,0 +1,7 @@ +{ + "scopeName": "source.sample", + "firstLineMatch": "^#![ \\t]*(?:/usr/bin/env[ \\t]+(?:-S[ \\t]+)?|/opt/tools/)sample[0-9]*(?:[ \\t]|$)", + "patterns": [ + { "match": "\\bsample\\b", "name": "keyword.control.sample" } + ] +} diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 0ea7702e..6d85e865 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -7,7 +7,6 @@ "additionalProperties": false, "required": ["schemaVersion", "id", "displayName", "version", "pluginAPIVersion", "requires", "vendor"], "allOf": [ - {"if": {"required": ["languages"], "properties": {"languages": {"contains": {"required": ["firstLineMatch"]}}}}, "then": {"properties": {"requires": {"required": ["languages"], "properties": {"languages": {"const": 1}}}}}}, {"if": {"required": ["outputLinkMatchers"]}, "then": {"properties": {"requires": {"required": ["outputLinkMatchers"]}}}}, {"if": {"required": ["toolDefinitions"]}, "then": {"properties": {"requires": {"required": ["toolDefinitions"]}}}}, {"if": {"required": ["buildSystems"], "properties": {"buildSystems": {"contains": {"required": ["runConfigurationTypes"]}}}}, "then": {"properties": {"requires": {"required": ["runConfigurationTypes"]}}}}, @@ -42,7 +41,7 @@ "debugAdapters": { "description": "Required exactly when debugAdapters is non-empty. Covers bounded target argument and environment bindings and debugAdapters[].features and defaults. The DAP session itself is negotiated by the adapter in initialize.", "enum": [0] }, "executionProviders": { "enum": [0] }, "languageServers": { "description": "Required exactly when languageServers is non-empty. Covers languageServers[].workspaceConfiguration and the session fields requestMethods, commands, serializedCommands, forwardNotifications, state, and remote.", "enum": [0] }, - "languages": { "description": "Required exactly when languages is non-empty. Covers languages[].grammar and languages[].configuration. Version 1 adds firstLineMatch for extensionless documents.", "enum": [0, 1] }, + "languages": { "description": "Required exactly when languages is non-empty. Covers languages[].grammar, a TextMate grammar, and languages[].configuration.", "enum": [0] }, "managedRuntimes": { "description": "Required exactly when managedRuntimes is present: approved pinned runtime archives, plugin-owned qualification and host-owned installation outside versioned packages. Version 1 adds optional artifact mirror URLs.", "enum": [0, 1] }, "outputLinkMatchers": { "description": "Required exactly when outputLinkMatchers is non-empty.", "enum": [0] }, "packageTrust": { "description": "Required exactly when vendor.bundledSignatureRequirement is present.", "enum": [0] }, @@ -1548,7 +1547,6 @@ "fileExtensions": { "$ref": "#/$defs/fileNameList" }, "fileNames": { "$ref": "#/$defs/fileNameList" }, "projectFileNames": { "$ref": "#/$defs/fileNameList" }, - "firstLineMatch": { "description": "Rust regex matching a nonempty prefix of the complete first line of an unassociated dotless file. At most 512 UTF-8 bytes. Requires languages 1.", "type": "string", "minLength": 1, "maxLength": 512 }, "dependencies": { "type": "object", "additionalProperties": false, diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 02622547..853c1f30 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -48,7 +48,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-22 | 输出、日志、进度 | 部分完成 | [插件函数的进度和取消](../contract/v1/README.md#progress);面向开发者的[结构化诊断日志 `litheLogging`](../contract/v1/README.md#structured-plugin-diagnostics);[`languageServer/setStatus`](../contract/v1/README.md#language-server-host-methods) 在宿主状态界面显示插件自己的语言服务器准备状态(只有消息和百分比,没有 actions);[`outputLinkMatchers`](../contract/v1/README.md#output-link-matchers):插件声明的匹配器让 Run 与测试控制台的输出出现链接 | 独立的输出面板、面向用户的日志和进度 API | [插件后端](domains/backend.md) | | API-23 | 工具链与受管进程 | 部分完成 | [进程启动](../contract/v1/README.md#process-start)、运行时解析、[共享可执行文件候选](../contract/v1/README.md#executable-resolution)、工具定义、工具链提供者(`toolchainProviders`);[按工具定义 ID 引用运行时](../contract/v1/README.md#tool-references)(清单 `requiresTools`);后端发起的[`run/start`、`run/stop` 和 `run/didExit` 通知](../contract/v1/README.md#run-and-debug-sessions),由宿主拥有 Run 会话(权限 `run.start`;工具解析不到可执行文件时返回 `plugin.host.toolUnresolved`);[安装缺失的命令](../contract/v1/README.md#command-installers)(`commandInstallers`,权限 `commands.install`);[受管运行时](../contract/v1/README.md#managed-runtimes)(`managedRuntimes`,权限 `runtimes.install`,Core 计划与应答校验,无新增宿主 RPC) | 后端可调用的通用工具链和进程服务;保存固定(pin)、`toolchainConsumers`;Lithe 桌面端未声明 `toolchainProviders` 和 `commandInstallers` | [工具链](domains/toolchains.md) | | API-24 | 终端 | 部分完成 | [插件自有原生终端](../contract/v1/README.md#plugin-owned-native-terminals) `terminal/create`、`show`、`close`、`reopen`、`dispose`、`onExit`(本机工作区) | 向终端发送文本、读取终端输出 | [插件后端](domains/backend.md) | -| API-25 | 语言、语法、LSP | 部分完成 | [语言](../contract/v1/README.md#languages)与[语言服务器](../contract/v1/README.md#language-servers);[`languages` 的包内 Monarch 语法和编辑器配置](../contract/v1/README.md#grammars-and-editor-configuration);[编辑器语言功能 Provider `editor/registerProviders`](../contract/v1/README.md#editor-language-feature-providers),把 `definition`、`hover`、`completion`、`codeLens`、`foldingRange`、`semanticTokens`、`documentLink` 这 7 种类型绑定到普通插件函数,语言服务器优先、插件结果只补充;插件自有的语言服务器会话:[`languageServers` 的会话声明](../contract/v1/README.md#plugin-owned-sessions)给出后端可用的请求、命令、转发通知,[`languageServer/request`、`notify`、`setStatus`](../contract/v1/README.md#language-server-host-methods) 与 `languageServer/didChangeState`、`languageServer/didReceiveNotification` 两个通知,会话策略由 Core 执行;[`launch.kind: "backend"`](../contract/v1/README.md#backend-resolved-launch) 由插件后端决定启动方式 | 符号、格式化、重命名、Code Action、签名帮助、内联提示、运行期传入 JSON 动态注册高亮;远程工作区中由后端决定启动方式的服务器 | [语言](domains/languages.md)、[编辑器](domains/editor.md) | +| API-25 | 语言、语法、LSP | 部分完成 | [语言](../contract/v1/README.md#languages)与[语言服务器](../contract/v1/README.md#language-servers);[`languages` 的包内 TextMate 语法和编辑器配置](../contract/v1/README.md#grammars-and-editor-configuration)及[无后缀文件首行关联](../contract/v1/README.md#first-line-matching);[编辑器语言功能 Provider `editor/registerProviders`](../contract/v1/README.md#editor-language-feature-providers),把 `definition`、`hover`、`completion`、`codeLens`、`foldingRange`、`semanticTokens`、`documentLink` 这 7 种类型绑定到普通插件函数,语言服务器优先、插件结果只补充;插件自有的语言服务器会话:[`languageServers` 的会话声明](../contract/v1/README.md#plugin-owned-sessions)给出后端可用的请求、命令、转发通知,[`languageServer/request`、`notify`、`setStatus`](../contract/v1/README.md#language-server-host-methods) 与 `languageServer/didChangeState`、`languageServer/didReceiveNotification` 两个通知,会话策略由 Core 执行;[`launch.kind: "backend"`](../contract/v1/README.md#backend-resolved-launch) 由插件后端决定启动方式 | 符号、格式化、重命名、Code Action、签名帮助、内联提示、运行期传入 JSON 动态注册高亮;远程工作区中由后端决定启动方式的服务器 | [语言](domains/languages.md)、[编辑器](domains/editor.md) | | API-27 | 编辑器动作、主题、装饰 | 部分完成 | [独立编辑器动作 `editor/registerActions`](../contract/v1/README.md#independent-editor-actions),绑定普通函数和文件范围,不依赖 LSP、构建或运行;支持行首多图标、至多 4 个 `alternatives`、点击结果的 `reveal` | 主题、代码片段、其他装饰 | [编辑器](domains/editor.md) | | API-29 | 构建、任务、测试、运行准备 | 部分完成 | [`buildSystems`](../contract/v1/README.md#build-systems)、[`buildProviders`](../contract/v1/README.md#build-providers)、[`buildModelInputs`](../contract/v1/README.md#optional-read-only-model-inputs)、[`runConfigurationTypes`](../contract/v1/README.md#run-configuration-types)、[`beforeLaunchTasks`](../contract/v1/README.md#before-launch-tasks) | 开发指南还不完整;Lithe 桌面端未声明 `buildModelInputs`;`runConfigurationTypes` 自 [1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148) 起声明,插件类型只能运行、不能调试;`beforeLaunchTasks` 自 [1lck/Lithe-IDEA#2169](https://github.com/1lck/Lithe-IDEA/pull/2169) 起声明 | [声明式构建](domains/build-systems.md)、[构建提供者](domains/build-providers.md) | | API-30 | 调试适配器 | 部分完成 | [`debugAdapters`](../contract/v1/README.md#debug-adapters) 与宿主的 DAP 会话;[`features`、`defaults`](../contract/v1/README.md#adapter-features-and-defaults)(热代码替换、步进过滤器);后端发起的 [`debug/start`](../contract/v1/README.md#run-and-debug-sessions)(权限 `debug.start`) | 后端只能在本插件自己声明的适配器上启动会话,不能使用其他插件的适配器 | [调试适配器](domains/debug-adapters.md) | @@ -220,7 +220,7 @@ Status meanings: | API-22 | Output, log, progress | Partial | [Plugin function progress and cancellation](../contract/v1/README.md#progress); developer-facing [structured diagnostics `litheLogging`](../contract/v1/README.md#structured-plugin-diagnostics); [`languageServer/setStatus`](../contract/v1/README.md#language-server-host-methods) shows the plugin's own language server preparation state in the host's status UI (a message and a percentage only, no actions); [`outputLinkMatchers`](../contract/v1/README.md#output-link-matchers): matchers a plugin declares make output in the Run and Test consoles clickable | A dedicated output panel, user-facing log and progress APIs | [Plugin backend](domains/backend.md) | | API-23 | Toolchains and managed processes | Partial | [Process start](../contract/v1/README.md#process-start), runtime resolution, [shared executable candidates](../contract/v1/README.md#executable-resolution), tool definitions, toolchain providers (`toolchainProviders`); [references to runtimes by tool-definition ID](../contract/v1/README.md#tool-references) (manifest `requiresTools`); backend-started [`run/start`, `run/stop`, and the `run/didExit` notification](../contract/v1/README.md#run-and-debug-sessions), where the host owns the Run session (permission `run.start`; a tool that resolves to no executable returns `plugin.host.toolUnresolved`); [installing missing commands](../contract/v1/README.md#command-installers) (`commandInstallers`, permission `commands.install`); [managed runtimes](../contract/v1/README.md#managed-runtimes) (`managedRuntimes`, permission `runtimes.install`, Core plans and reply validation with no new host RPC) | A general toolchain and process service backends can call; saving pins, `toolchainConsumers`; the Lithe desktop client does not declare `toolchainProviders` or `commandInstallers` | [Toolchains](domains/toolchains.md) | | API-24 | Terminals | Partial | [Plugin-owned native terminals](../contract/v1/README.md#plugin-owned-native-terminals) `terminal/create`, `show`, `close`, `reopen`, `dispose`, `onExit` (local workspaces) | Sending text to a terminal, reading its output | [Plugin backend](domains/backend.md) | -| API-25 | Languages, grammars, LSP | Partial | [Languages](../contract/v1/README.md#languages) and [language servers](../contract/v1/README.md#language-servers); [packaged Monarch grammars and editor configuration in `languages`](../contract/v1/README.md#grammars-and-editor-configuration); [editor language-feature providers `editor/registerProviders`](../contract/v1/README.md#editor-language-feature-providers), binding 7 types (`definition`, `hover`, `completion`, `codeLens`, `foldingRange`, `semanticTokens`, `documentLink`) to ordinary plugin functions, where the language server answers first and plugin results only add; plugin-owned language server sessions: [the session declaration of `languageServers`](../contract/v1/README.md#plugin-owned-sessions) lists the requests, commands, and forwarded notifications a backend may use, with [`languageServer/request`, `notify`, `setStatus`](../contract/v1/README.md#language-server-host-methods) and the `languageServer/didChangeState` and `languageServer/didReceiveNotification` notifications, and Core enforces the session policy; [`launch.kind: "backend"`](../contract/v1/README.md#backend-resolved-launch) lets the plugin backend decide how the server starts | Symbols, formatting, rename, code actions, signature help, inlay hints, dynamic registration of highlighting from JSON passed at runtime; servers whose launch the backend decides in remote workspaces | [Languages](domains/languages.md), [Editor](domains/editor.md) | +| API-25 | Languages, grammars, LSP | Partial | [Languages](../contract/v1/README.md#languages) and [language servers](../contract/v1/README.md#language-servers); [packaged TextMate grammars and editor configuration in `languages`](../contract/v1/README.md#grammars-and-editor-configuration) and [first-line associations for extensionless files](../contract/v1/README.md#first-line-matching); [editor language-feature providers `editor/registerProviders`](../contract/v1/README.md#editor-language-feature-providers), binding 7 types (`definition`, `hover`, `completion`, `codeLens`, `foldingRange`, `semanticTokens`, `documentLink`) to ordinary plugin functions, where the language server answers first and plugin results only add; plugin-owned language server sessions: [the session declaration of `languageServers`](../contract/v1/README.md#plugin-owned-sessions) lists the requests, commands, and forwarded notifications a backend may use, with [`languageServer/request`, `notify`, `setStatus`](../contract/v1/README.md#language-server-host-methods) and the `languageServer/didChangeState` and `languageServer/didReceiveNotification` notifications, and Core enforces the session policy; [`launch.kind: "backend"`](../contract/v1/README.md#backend-resolved-launch) lets the plugin backend decide how the server starts | Symbols, formatting, rename, code actions, signature help, inlay hints, dynamic registration of highlighting from JSON passed at runtime; servers whose launch the backend decides in remote workspaces | [Languages](domains/languages.md), [Editor](domains/editor.md) | | API-27 | Editor actions, themes, decorations | Partial | [Independent editor actions `editor/registerActions`](../contract/v1/README.md#independent-editor-actions), binding ordinary functions to file ranges without LSP, build, or run; several icons at a line start, up to 4 `alternatives`, and a `reveal` in the click result | Themes, snippets, other decorations | [Editor](domains/editor.md) | | API-29 | Build, tasks, tests, run preparation | Partial | [`buildSystems`](../contract/v1/README.md#build-systems), [`buildProviders`](../contract/v1/README.md#build-providers), [`buildModelInputs`](../contract/v1/README.md#optional-read-only-model-inputs), [`runConfigurationTypes`](../contract/v1/README.md#run-configuration-types), [`beforeLaunchTasks`](../contract/v1/README.md#before-launch-tasks) | The developer guides are incomplete; the Lithe desktop client does not declare `buildModelInputs`; it declares `runConfigurationTypes` since [1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148) and runs plugin types without debugging them, and it declares `beforeLaunchTasks` since [1lck/Lithe-IDEA#2169](https://github.com/1lck/Lithe-IDEA/pull/2169) | [Build systems](domains/build-systems.md), [Build providers](domains/build-providers.md) | | API-30 | Debug adapters | Partial | [`debugAdapters`](../contract/v1/README.md#debug-adapters) and the host's DAP sessions; [`features` and `defaults`](../contract/v1/README.md#adapter-features-and-defaults) (hot code replace, step filters); backend-started [`debug/start`](../contract/v1/README.md#run-and-debug-sessions) (permission `debug.start`) | A backend can start sessions only on adapters its own plugin declares, not on another plugin's adapters | [Debug adapters](domains/debug-adapters.md) | diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 06c8db8b..57a655e7 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -41,7 +41,6 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | 版本 | 内容 | Core | Lithe 桌面端 | 详见 | | --- | --- | --- | --- | --- | | `languages` `0` | `languages[]`:语言 ID、文件扩展名,以及包内 TextMate [`grammar` 与 `configuration`](../contract/v1/README.md#grammars-and-editor-configuration);宿主从包里读取并在编辑器里应用,不启动进程 | ✅ | ✅ | [语言](domains/languages.md) | -| `languages` `1` | 无路径或用户关联的无后缀文件可通过 `firstLineMatch` 匹配首行 | ✅ | 配套宿主接入后声明 | [契约](../contract/v1/README.md#first-line-matching-languages-1) | | `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)、[`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) | @@ -157,7 +156,6 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | Version | Content | Core | Lithe desktop | See | | --- | --- | --- | --- | --- | | `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) | -| `languages` `1` | `firstLineMatch` recognizes unassociated extensionless files by their first line | ✅ | Requires corresponding host support | [Contract](../contract/v1/README.md#first-line-matching-languages-1) | | `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), [`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) | diff --git a/shared/plugins/reference/domains/languages.md b/shared/plugins/reference/domains/languages.md index 5e6bfe0a..a251fb28 100644 --- a/shared/plugins/reference/domains/languages.md +++ b/shared/plugins/reference/domains/languages.md @@ -9,7 +9,7 @@ | 项目 | 内容 | | --- | --- | | 清单字段 | `languages`、`languageServers`、`executionProviders`、`outputLinkMatchers` | -| 能力 | `languages`、`languageServers`、`executionProviders`、`outputLinkMatchers`,均有版本 `0`。`languages` 版本 `1` 增加首行匹配。`languageServers` 的后端启动方式需要 `backend`;会话、输出链接的 `resolve`、内容提供者都需要 `backend` | +| 能力 | `languages`、`languageServers`、`executionProviders`、`outputLinkMatchers`,均有版本 `0`。`languageServers` 的后端启动方式需要 `backend`;会话、输出链接的 `resolve`、内容提供者都需要 `backend` | | 协议 | LSP。后端驱动服务器用的 `languageServer/*` 宿主方法和通知见下文,它们属于插件后端的 `litheFunctions` 协议(见[插件后端](backend.md)) | | API 编号 | [API-25](../api-catalog.md#现在能用的-api):语言、语法、LSP。[API-12](../api-catalog.md#现在能用的-api):按 URI scheme 提供的只读文档(`documents/registerContentProvider`)。[API-20](../api-catalog.md#现在能用的-api):语言服务器按工作区的状态目录及其回收。[API-22](../api-catalog.md#现在能用的-api):语言服务器的准备状态(`languageServer/setStatus`)和 Run、测试控制台输出里的链接。插件函数提供的编辑器语言功能见[编辑器](editor.md) | | 权限 | `languageServer.launch`;`executionProviders` 声明 `run`、`test` 时加 `process.run`、`process.test`;`languageServer.request`(服务器列出 `requestMethods` 或 `forwardNotifications` 时才可声明,需要 `backend`);`documents.contentProvider`(需要 `backend`) | @@ -20,7 +20,7 @@ `languages[]` 的 `id`、`fileExtensions`、`fileNames`、`projectFileNames` 和 `dependencies` 的规则见[契约的 Languages 一节](../../contract/v1/README.md#languages)。语法和编辑器配置是纯数据:宿主从包里读取,编辑器直接应用,不启动任何进程。只有语法的插件不需要语言服务器、后端或激活事件。 -无后缀文件可用 `firstLineMatch` 声明开头的特征,例如脚本的 shebang。将 `requires.languages` 设为 `1`,并在 `languages[]` 里填写 Rust 正则表达式。文件的既有语言关联优先,编辑器只检查至多 1024 字节的完整首行。[契约示例](../../contract/v1/README.md#first-line-matching-languages-1) +无后缀脚本可以通过包内 TextMate 语法文件的顶层 `firstLineMatch` 声明 shebang。格式为 Rust 正则表达式,旧桌面可以忽略这项提示,插件仍声明 `languages: 0`。文件的既有语言关联优先,编辑器只检查至多 1024 UTF-8 字节的完整首行。详见[首行匹配](../../contract/v1/README.md#first-line-matching)。 ```json { @@ -287,7 +287,7 @@ Languages let Lithe recognize a language: identify its files, highlight them wit | Item | Value | | --- | --- | | Manifest fields | `languages`, `languageServers`, `executionProviders`, `outputLinkMatchers` | -| Capabilities | `languages`, `languageServers`, `executionProviders`, `outputLinkMatchers`, all support version `0`. `languages` version `1` adds first-line matching. A `languageServers` backend launch needs `backend`; sessions, a matcher's `resolve`, and content providers need `backend` too | +| Capabilities | `languages`, `languageServers`, `executionProviders`, `outputLinkMatchers`, all support version `0`. A `languageServers` backend launch needs `backend`; sessions, a matcher's `resolve`, and content providers need `backend` too | | Protocols | LSP. The `languageServer/*` host methods and notifications below belong to the plugin backend's `litheFunctions` protocol (see [Plugin backend](backend.md)) | | API IDs | [API-25](../api-catalog.md#apis-usable-now): languages, grammars, LSP. [API-12](../api-catalog.md#apis-usable-now): read-only documents by URI scheme (`documents/registerContentProvider`). [API-20](../api-catalog.md#apis-usable-now): per-workspace state directories of language servers, and their pruning. [API-22](../api-catalog.md#apis-usable-now): language server preparation status (`languageServer/setStatus`) and links in Run and Test output. Editor language features supplied by plugin functions are in [Editor](editor.md) | | Permissions | `languageServer.launch`; `process.run`, `process.test` when an execution provider declares `run` or `test`; `languageServer.request` (only when a server lists `requestMethods` or `forwardNotifications`; needs `backend`); `documents.contentProvider` (needs `backend`) | @@ -298,10 +298,11 @@ Languages let Lithe recognize a language: identify its files, highlight them wit The rules for `id`, `fileExtensions`, `fileNames`, `projectFileNames`, and `dependencies` are in [the contract's Languages section](../../contract/v1/README.md#languages). A grammar and editor configuration are pure data: the host reads them from the package and the editor applies them without starting any process. A plugin with only grammars needs no language server, backend, or activation event. -For extensionless documents set `requires.languages` to `1` and declare a -`firstLineMatch` Rust regex, for example to recognize a shebang. Existing file +Extensionless scripts can declare a shebang as a root-level `firstLineMatch` +Rust regex in the packaged TextMate grammar. Keep `languages: 0` so older +hosts can install the same package and ignore the hint. Existing file associations take priority. The editor checks a complete first line of up to -1024 UTF-8 bytes. [Contract example](../../contract/v1/README.md#first-line-matching-languages-1) +1024 UTF-8 bytes. See [first-line matching](../../contract/v1/README.md#first-line-matching). ```json { diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 82a77cd2..f97ecf50 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- [#127](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/127),[@Mucheen](https://github.com/Mucheen),**`languages` 1**(API-25):`languages[].firstLineMatch` 让插件识别无路径关联的无后缀文档。Core 校验并匹配完整首行,保留原有路径和用户关联优先级。见 [1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)。 +- [#127](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/127),[@Mucheen](https://github.com/Mucheen),**API-25**:按现有 `grammar.path` 读取 TextMate 语法的可选 `firstLineMatch`,识别无路径关联的无后缀文档。旧桌面仍可安装 `languages: 0` 的同一插件包。Core 解码返回可选提示并匹配完整首行,既有路径与用户关联优先。见 [1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)。 - [#112](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/112),[@Mucheen](https://github.com/Mucheen),**`buildSystems` 1**(API-29):清单新增 `buildSystems[].test.discoveryCommand`,已有测试运行可以独立采用命令或 provider。命令使用现有构建工具,把 `litheTestDiscovery` v0 写到宿主提供的 `${outputFile}`。Core 的 `build.testDiscoveryPlan`、`build.decodeTestDiscovery` 和测试树兼容两种发现来源,检查每条选择器可原样运行,命令尝试沿用 `lithe/build/discoverTests` 的结构化终态。没有新增宿主方法、通知或 SDK 版本。见 [1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)。 @@ -54,7 +54,6 @@ | `keymapImportProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `languageServers` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `languages` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | -| `languages` | 1 | 待合入 | [#127](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/127) | | `outputLinkMatchers` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `packageTrust` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `pluginFunctions` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | From 3c0fcffcbc7067be86b832ca2ee3acfc48bf6187 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Fri, 20 Nov 2026 10:26:43 +0800 Subject: [PATCH 4/4] =?UTF-8?q?fix(languages):=20=E4=BF=9D=E7=95=99?= =?UTF-8?q?=E9=A6=96=E8=A1=8C=E7=BC=96=E8=AF=91=E7=BC=93=E5=AD=98=E4=B8=8E?= =?UTF-8?q?=E5=B7=B2=E6=9C=89=E9=AB=98=E4=BA=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/contracts/rust-core-api.md | 13 ++- rust/crates/core/src/runtime/ffi.rs | 32 +++++++ .../core/src/tests/plugin_editor_resources.rs | 46 ++++++++++ rust/crates/plugin-manifest/src/commands.rs | 38 +++++--- rust/crates/plugin-manifest/src/first_line.rs | 87 ++++++++++++++++--- .../fixtures/plugins/first-line-match-v1.json | 33 +++++++ shared/plugins/contract/v1/README.md | 7 ++ .../languages/grammars/sample.first-line.json | 3 + shared/plugins/reference/domains/languages.md | 6 +- .../plugins/reference/protocol-changelog.md | 2 +- 10 files changed, 237 insertions(+), 30 deletions(-) create mode 100644 rust/fixtures/plugins/first-line-match-v1.json create mode 100644 shared/plugins/contract/v1/fixtures/languages/grammars/sample.first-line.json diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 7eeea0a4..c531738a 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -5185,7 +5185,8 @@ no match. Never send a truncated prefix. Supply the enabled declarations in registry precedence order, in batches of up to 64, stopping on the first match. The result preserves the winning ID unchanged. A malformed batch, language ID or pattern is an `invalid_request`. Core retains only bounded compiled -declarations and performs no I/O. See the [first-line pattern +declarations and performs no I/O. See the shared +[ABI fixture](../fixtures/plugins/first-line-match-v1.json) and the [first-line pattern contract](../../shared/plugins/contract/v1/README.md#first-line-matching). `plugins.declarative.decodeGrammar` accepts `{ manifest, languageID, grammar }`, @@ -5194,8 +5195,14 @@ inside the installed package, and returns `language: { id, fileExtensions, fileNames, grammar: { kind, scopeName, source, firstLineMatch? }, configuration }`. The editor registers the validated `textmate` JSON `source` byte for byte under `scopeName`. -When present, `firstLineMatch` holds validated optional root-level metadata -for `languages.matchFirstLine`. Unsupported or malformed hints are omitted. +When present, `grammar.firstLineMatch` holds validated optional root-level +metadata for `languages.matchFirstLine`. For a language without an explicit +`grammar.path`, the host can instead pass the text from +`grammars/.first-line.json` as `grammar`. Core returns a valid hint +as `language.firstLineMatch`, with `language.grammar` set to `null` so the editor +uses its existing grammar. Unsupported or malformed hints are omitted. A +standalone file with invalid JSON or above its size limit is rejected as +`plugin.grammar.invalid`. Hosts run plugin grammars only off the editor UI thread, with bounded backtracking and a time budget per line. A grammar Core refuses is `plugin.grammar.invalid` with the failing `field`; a language diff --git a/rust/crates/core/src/runtime/ffi.rs b/rust/crates/core/src/runtime/ffi.rs index 80496c40..3e13e9b4 100644 --- a/rust/crates/core/src/runtime/ffi.rs +++ b/rust/crates/core/src/runtime/ffi.rs @@ -253,6 +253,38 @@ mod text_content_tests { mod editor_essentials_tests { use super::*; use serde_json::{json, Value}; + + #[test] + fn first_line_match_abi_matches_shared_vectors() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../../fixtures/plugins/first-line-match-v1.json" + )) + .unwrap(); + for case in fixture["cases"].as_array().unwrap() { + let request = CString::new( + json!({ + "id": case["name"], + "command": fixture["command"], + "payload": case["payload"] + }) + .to_string(), + ) + .unwrap(); + let pointer = unsafe { lithe_core_execute_json(request.as_ptr()) }; + assert!(!pointer.is_null()); + let response = unsafe { serde_json::from_slice(CStr::from_ptr(pointer).to_bytes()) }; + unsafe { lithe_core_free_string(pointer) }; + let response: Value = response.unwrap(); + if case["errorCode"].is_string() { + assert_eq!(response["id"], case["name"]); + assert_eq!(response["ok"], false, "{response}"); + assert_eq!(response["error"]["code"], case["errorCode"]); + } else { + assert_eq!(response, case["expected"], "{}", case["name"]); + } + } + } + #[test] fn borrowed_document_abi_matches_shared_vectors() { let fixture: Value = serde_json::from_str(include_str!( diff --git a/rust/crates/core/src/tests/plugin_editor_resources.rs b/rust/crates/core/src/tests/plugin_editor_resources.rs index 5527f90d..6b69a2b8 100644 --- a/rust/crates/core/src/tests/plugin_editor_resources.rs +++ b/rust/crates/core/src/tests/plugin_editor_resources.rs @@ -17,6 +17,8 @@ const GRAMMAR_PLUGIN: &str = contract_file!("fixtures/languages/language-grammar const HTTP_GRAMMAR: &str = contract_file!("fixtures/languages/grammars/http.tmLanguage.json"); const FIRST_LINE_PLUGIN: &str = contract_file!("fixtures/languages/first-line.plugin.json"); const SAMPLE_GRAMMAR: &str = contract_file!("fixtures/languages/grammars/sample.tmLanguage.json"); +const SAMPLE_FIRST_LINE: &str = + contract_file!("fixtures/languages/grammars/sample.first-line.json"); fn manifest(source: &str) -> Value { serde_json::from_str(source).expect("fixture manifest is JSON") @@ -409,6 +411,50 @@ fn first_line_grammar_uses_the_existing_language_capability() { ); } +#[test] +fn standalone_first_line_metadata_keeps_the_existing_grammar() { + let mut plugin = manifest(FIRST_LINE_PLUGIN); + plugin["languages"][0] + .as_object_mut() + .unwrap() + .remove("grammar"); + let admission = validate_command(json!({ + "manifest": plugin, + "hostCapabilities": { "languages": [0] }, + })) + .unwrap(); + assert_eq!(admission["status"], "ok", "{admission}"); + let decode = |source: &str| { + decode_grammar_command(json!({ + "manifest": admission["plugin"], + "languageID": "sample", + "grammar": source, + })) + .unwrap() + }; + let decoded = decode(SAMPLE_FIRST_LINE); + assert_eq!(decoded["status"], "ok", "{decoded}"); + assert!(decoded["language"]["grammar"].is_null()); + assert_eq!( + decoded["language"]["firstLineMatch"], + manifest(SAMPLE_FIRST_LINE)["firstLineMatch"] + ); + assert_eq!(decoded["language"]["configuration"]["lineComment"], "//"); + let unsupported = decode(r#"{"firstLineMatch":"["}"#); + assert_eq!(unsupported["status"], "ok", "{unsupported}"); + assert!(unsupported["language"]["grammar"].is_null()); + assert!(!unsupported["language"] + .as_object() + .unwrap() + .contains_key("firstLineMatch")); + + for source in ["invalid JSON", "[]", &" ".repeat(4097)] { + let result = decode(source); + assert_eq!(result["status"], "rejected", "{result}"); + assert_eq!(result["error"]["code"], "plugin.grammar.invalid"); + } +} + #[test] fn unsupported_first_line_metadata_keeps_its_grammar() { for pattern in [ diff --git a/rust/crates/plugin-manifest/src/commands.rs b/rust/crates/plugin-manifest/src/commands.rs index 1c98b199..283f1c5c 100644 --- a/rust/crates/plugin-manifest/src/commands.rs +++ b/rust/crates/plugin-manifest/src/commands.rs @@ -157,12 +157,12 @@ struct GrammarPayload { manifest: Value, #[serde(rename = "languageID")] language_id: String, - /// Text of the grammar file the host read from the package. + /// Text of the grammar or first-line metadata file the host read from the package. grammar: String, } -/// `plugins.declarative.decodeGrammar`: validates the grammar file of one -/// language and returns what the editor registers for it. +/// `plugins.declarative.decodeGrammar`: validates the grammar or metadata of +/// one language and returns what the editor registers for it. pub fn decode_grammar_command(payload: Value) -> Result { let payload: GrammarPayload = decode_payload(payload, "plugins.declarative.decodeGrammar")?; Ok(outcome(validate_manifest_value(payload.manifest).and_then( @@ -171,7 +171,11 @@ pub fn decode_grammar_command(payload: Value) -> Result { .languages .iter() .find(|language| language.id == payload.language_id) - .filter(|language| language.grammar.is_some() || language.configuration.is_some()) + .filter(|language| { + language.grammar.is_some() + || language.configuration.is_some() + || !payload.grammar.is_empty() + }) .ok_or_else(|| { PluginRejection::new( "plugin.grammar.unavailable", @@ -205,16 +209,22 @@ pub fn decode_grammar_command(payload: Value) -> Result { } }) .transpose()?; - Ok(( - "language", - json!({ - "id": language.id, - "fileExtensions": language.file_extensions, - "fileNames": language.file_names, - "grammar": grammar, - "configuration": language.configuration, - }), - )) + let mut decoded = json!({ + "id": language.id, + "fileExtensions": language.file_extensions, + "fileNames": language.file_names, + "grammar": grammar, + "configuration": language.configuration, + }); + let standalone_hint = if language.grammar.is_none() && !payload.grammar.is_empty() { + crate::first_line::decode_metadata(&payload.grammar)? + } else { + None + }; + if let Some(pattern) = standalone_hint { + decoded["firstLineMatch"] = json!(pattern); + } + Ok(("language", decoded)) }, ))) } diff --git a/rust/crates/plugin-manifest/src/first_line.rs b/rust/crates/plugin-manifest/src/first_line.rs index 6b8b8336..e6bb376a 100644 --- a/rust/crates/plugin-manifest/src/first_line.rs +++ b/rust/crates/plugin-manifest/src/first_line.rs @@ -1,6 +1,7 @@ //! Bounded, data-only first-line language matching for documents with no path association. use super::{declarations::is_language_id, decode_payload, CoreError, ErrorCode}; +use lithe_plugin_model::{PluginRejection, Validation}; use regex::{Regex, RegexBuilder}; use serde::Deserialize; use serde_json::{json, Value}; @@ -10,21 +11,33 @@ use std::sync::{Arc, Mutex, OnceLock}; const MAX_PATTERN_BYTES: usize = 512; const MAX_FIRST_LINE_BYTES: usize = 1024; const MAX_CANDIDATES: usize = 64; +const CACHE_CAPACITY: usize = 64; const REGEX_SIZE_LIMIT: usize = 256 * 1024; +const MAX_METADATA_BYTES: usize = 4096; -/// Use the same compiled program in grammar decoding and on repeated document opens. -/// The cache contains only declaration text and programs, never document content. -fn compiled(source: &str) -> Result, &'static str> { +type PatternCache = VecDeque<(String, Arc)>; + +#[derive(Clone, Copy)] +enum CacheAccess { + Register, + Match, +} + +fn compiled_in( + cache: &Mutex, + source: &str, + access: CacheAccess, +) -> Result, &'static str> { if source.is_empty() || source.len() > MAX_PATTERN_BYTES { return Err("A first-line pattern must be 1 to 512 UTF-8 bytes."); } - type Cache = VecDeque<(String, Arc)>; - static CACHE: OnceLock> = OnceLock::new(); - let cache = CACHE.get_or_init(Mutex::default); - let mut entries = cache.lock().unwrap_or_else(|poison| poison.into_inner()); + let entries = cache.lock().unwrap_or_else(|poison| poison.into_inner()); if let Some((_, regex)) = entries.iter().find(|(pattern, _)| pattern == source) { return Ok(Arc::clone(regex)); } + drop(entries); + + // A cold compilation should not block other workers' cache hits. let regex = RegexBuilder::new(source) .size_limit(REGEX_SIZE_LIMIT) .dfa_size_limit(REGEX_SIZE_LIMIT) @@ -34,16 +47,52 @@ fn compiled(source: &str) -> Result, &'static str> { return Err("A first-line pattern cannot match empty input."); } let regex = Arc::new(regex); - if entries.len() == MAX_CANDIDATES { + let mut entries = cache.lock().unwrap_or_else(|poison| poison.into_inner()); + if let Some((_, existing)) = entries.iter().find(|(pattern, _)| pattern == source) { + return Ok(Arc::clone(existing)); + } + if entries.len() == CACHE_CAPACITY { + // Document matching can encounter more than one batch. Filling the + // cache is useful, but evicting warm patterns during a scan makes the + // next opening repeat the same compilations. + if matches!(access, CacheAccess::Match) { + return Ok(regex); + } entries.pop_front(); } entries.push_back((source.to_owned(), Arc::clone(®ex))); Ok(regex) } +/// Use the same compiled program in grammar decoding and on repeated document opens. +/// The cache contains only declaration text and programs, never document content. +fn compiled(source: &str, access: CacheAccess) -> Result, &'static str> { + static CACHE: OnceLock> = OnceLock::new(); + compiled_in(CACHE.get_or_init(Mutex::default), source, access) +} + /// Whether a grammar hint uses the syntax and budget of the first-line matcher. pub(crate) fn supports_pattern(source: &str) -> bool { - compiled(source).is_ok() + compiled(source, CacheAccess::Register).is_ok() +} + +/// Reads only the hint from a standalone TextMate metadata file. An absent or +/// unsupported hint leaves the language's existing highlighting intact. +pub(crate) fn decode_metadata(source: &str) -> Validation> { + let invalid = + |message| PluginRejection::at("plugin.grammar.invalid", "firstLineMatch", message); + if source.len() > MAX_METADATA_BYTES { + return Err(invalid( + "The first-line metadata file is larger than 4096 bytes.", + )); + } + let metadata = serde_json::from_str::>(source) + .map_err(|_| invalid("The first-line metadata file must be a JSON object."))?; + Ok(metadata + .get("firstLineMatch") + .and_then(Value::as_str) + .filter(|pattern| supports_pattern(pattern)) + .map(str::to_owned)) } #[derive(Deserialize)] @@ -81,7 +130,8 @@ pub fn match_first_line(payload: Value) -> Result { if !is_language_id(&candidate.language_id) { return Err(invalid_request("Invalid first-line candidate language ID.")); } - let regex = compiled(&candidate.first_line_match).map_err(invalid_request)?; + let regex = + compiled(&candidate.first_line_match, CacheAccess::Match).map_err(invalid_request)?; if eligible && selected.is_none() && regex @@ -93,3 +143,20 @@ pub fn match_first_line(payload: Value) -> Result { } Ok(json!({"languageID": selected})) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn scanning_more_than_one_batch_keeps_cached_patterns() { + let cache = Mutex::default(); + let initial = compiled_in(&cache, "^sample-0$", CacheAccess::Register).unwrap(); + for i in 1..=MAX_CANDIDATES { + compiled_in(&cache, &format!("^sample-{i}$"), CacheAccess::Match).unwrap(); + } + let repeated = compiled_in(&cache, "^sample-0$", CacheAccess::Match).unwrap(); + assert!(Arc::ptr_eq(&initial, &repeated)); + assert_eq!(cache.lock().unwrap().len(), CACHE_CAPACITY); + } +} diff --git a/rust/fixtures/plugins/first-line-match-v1.json b/rust/fixtures/plugins/first-line-match-v1.json new file mode 100644 index 00000000..4d112da3 --- /dev/null +++ b/rust/fixtures/plugins/first-line-match-v1.json @@ -0,0 +1,33 @@ +{ + "schemaVersion": 1, + "command": "languages.matchFirstLine", + "cases": [ + { + "name": "uses-registry-order", + "payload": { + "firstLine": "#!/usr/bin/env -S sample3 -f", + "candidates": [ + { "languageID": "sample", "firstLineMatch": "^#! */usr/bin/env +-S +sample[0-9]*(?: |$)" }, + { "languageID": "other", "firstLineMatch": "^#!" } + ] + }, + "expected": { "id": "uses-registry-order", "ok": true, "data": { "languageID": "sample" } } + }, + { + "name": "returns-null-for-no-match", + "payload": { + "firstLine": "#!/usr/bin/env other", + "candidates": [{ "languageID": "sample", "firstLineMatch": "^#! */usr/bin/env +sample(?: |$)" }] + }, + "expected": { "id": "returns-null-for-no-match", "ok": true, "data": { "languageID": null } } + }, + { + "name": "rejects-an-invalid-candidate", + "payload": { + "firstLine": "#!/usr/bin/env sample", + "candidates": [{ "languageID": "sample", "firstLineMatch": "[" }] + }, + "errorCode": "invalid_request" + } + ] +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 1ceb55af..4c7da40a 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -309,6 +309,13 @@ still install the package and apply its existing file associations and highlighting. See the [fixture manifest](fixtures/languages/first-line.plugin.json) and [grammar](fixtures/languages/grammars/sample.tmLanguage.json). +To keep the editor's existing highlighting for a contributed language, omit +`languages[].grammar` and package the hint in +[`grammars/.first-line.json`](fixtures/languages/grammars/sample.first-line.json). +The standalone file is a JSON object of at most 4096 UTF-8 bytes with the same +`firstLineMatch` field. Earlier hosts ignore this resource. An explicit grammar +declaration takes precedence over the standalone file. + Core interprets this hint as a Rust regular expression of 1–512 UTF-8 bytes. For example, `"firstLineMatch": "^#! */opt/tools/sample(?: |$)"` matches the interpreter followed by a space or the end of the line. The pattern cannot diff --git a/shared/plugins/contract/v1/fixtures/languages/grammars/sample.first-line.json b/shared/plugins/contract/v1/fixtures/languages/grammars/sample.first-line.json new file mode 100644 index 00000000..b3afdf0f --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/languages/grammars/sample.first-line.json @@ -0,0 +1,3 @@ +{ + "firstLineMatch": "^#![ \\t]*(?:/usr/bin/env[ \\t]+(?:-S[ \\t]+)?|/opt/tools/)sample[0-9]*(?:[ \\t]|$)" +} diff --git a/shared/plugins/reference/domains/languages.md b/shared/plugins/reference/domains/languages.md index a251fb28..2a3848e9 100644 --- a/shared/plugins/reference/domains/languages.md +++ b/shared/plugins/reference/domains/languages.md @@ -20,7 +20,7 @@ `languages[]` 的 `id`、`fileExtensions`、`fileNames`、`projectFileNames` 和 `dependencies` 的规则见[契约的 Languages 一节](../../contract/v1/README.md#languages)。语法和编辑器配置是纯数据:宿主从包里读取,编辑器直接应用,不启动任何进程。只有语法的插件不需要语言服务器、后端或激活事件。 -无后缀脚本可以通过包内 TextMate 语法文件的顶层 `firstLineMatch` 声明 shebang。格式为 Rust 正则表达式,旧桌面可以忽略这项提示,插件仍声明 `languages: 0`。文件的既有语言关联优先,编辑器只检查至多 1024 UTF-8 字节的完整首行。详见[首行匹配](../../contract/v1/README.md#first-line-matching)。 +无后缀脚本可以通过包内 TextMate 语法文件的顶层 `firstLineMatch` 声明 shebang。沿用宿主已有语法的插件把同一字段放在 `grammars/.first-line.json`,并省略语法声明。旧桌面可以忽略这项提示,插件仍声明 `languages: 0`。既有文件关联优先,编辑器只检查至多 1024 UTF-8 字节的完整首行。详见[首行匹配](../../contract/v1/README.md#first-line-matching)。 ```json { @@ -299,7 +299,9 @@ Languages let Lithe recognize a language: identify its files, highlight them wit The rules for `id`, `fileExtensions`, `fileNames`, `projectFileNames`, and `dependencies` are in [the contract's Languages section](../../contract/v1/README.md#languages). A grammar and editor configuration are pure data: the host reads them from the package and the editor applies them without starting any process. A plugin with only grammars needs no language server, backend, or activation event. Extensionless scripts can declare a shebang as a root-level `firstLineMatch` -Rust regex in the packaged TextMate grammar. Keep `languages: 0` so older +Rust regex in the packaged TextMate grammar. To inherit the editor's +highlighting, put the field in `grammars/.first-line.json` and omit +the grammar declaration. Keep `languages: 0` so older hosts can install the same package and ignore the hint. Existing file associations take priority. The editor checks a complete first line of up to 1024 UTF-8 bytes. See [first-line matching](../../contract/v1/README.md#first-line-matching). diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index f97ecf50..f3b2d39b 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- [#127](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/127),[@Mucheen](https://github.com/Mucheen),**API-25**:按现有 `grammar.path` 读取 TextMate 语法的可选 `firstLineMatch`,识别无路径关联的无后缀文档。旧桌面仍可安装 `languages: 0` 的同一插件包。Core 解码返回可选提示并匹配完整首行,既有路径与用户关联优先。见 [1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)。 +- [#127](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/127),[@Mucheen](https://github.com/Mucheen),**API-25**:从 `grammar.path` 指定的 TextMate 语法或独立的 `grammars/.first-line.json` 读取可选 `firstLineMatch`。独立文件可沿用宿主现有高亮。旧桌面仍可安装 `languages: 0` 的同一插件包。Core 解码返回可选提示并匹配完整首行,既有路径与用户关联优先。见 [1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)。 - [#112](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/112),[@Mucheen](https://github.com/Mucheen),**`buildSystems` 1**(API-29):清单新增 `buildSystems[].test.discoveryCommand`,已有测试运行可以独立采用命令或 provider。命令使用现有构建工具,把 `litheTestDiscovery` v0 写到宿主提供的 `${outputFile}`。Core 的 `build.testDiscoveryPlan`、`build.decodeTestDiscovery` 和测试树兼容两种发现来源,检查每条选择器可原样运行,命令尝试沿用 `lithe/build/discoverTests` 的结构化终态。没有新增宿主方法、通知或 SDK 版本。见 [1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)。