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..c531738a 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,13 +5176,34 @@ 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 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 }`, 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, `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 without static editor resources is `plugin.grammar.unavailable`. Configuration-only 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/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 9b09b397..6b69a2b8 100644 --- a/rust/crates/core/src/tests/plugin_editor_resources.rs +++ b/rust/crates/core/src/tests/plugin_editor_resources.rs @@ -15,6 +15,10 @@ 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"); +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") @@ -379,3 +383,177 @@ fn configuration_only_contribution_decodes_without_grammar() { assert!(result["language"]["grammar"].is_null()); assert_eq!(result["language"]["configuration"]["lineComment"], "#"); } + +#[test] +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!( + language["grammar"]["firstLineMatch"], + manifest(SAMPLE_GRAMMAR)["firstLineMatch"] + ); +} + +#[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 [ + Value::Null, + json!(42), + json!(""), + json!("a*"), + json!("["), + json!(r"(a)\1"), + json!("a{10000000}"), + json!("é".repeat(257)), + ] { + 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); + } +} + +#[test] +fn first_line_matching_keeps_registered_priority_and_never_reads_past_the_line() { + 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( + 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-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/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/commands.rs b/rust/crates/plugin-manifest/src/commands.rs index 62bd7297..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", @@ -185,29 +189,42 @@ 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 }) } }) .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/declarations.rs b/rust/crates/plugin-manifest/src/declarations.rs index 954b74ca..659e6c19 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.", 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..e6bb376a --- /dev/null +++ b/rust/crates/plugin-manifest/src/first_line.rs @@ -0,0 +1,162 @@ +//! 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}; +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 CACHE_CAPACITY: usize = 64; +const REGEX_SIZE_LIMIT: usize = 256 * 1024; +const MAX_METADATA_BYTES: usize = 4096; + +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."); + } + 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) + .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); + 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, 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)] +#[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, CacheAccess::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})) +} + +#[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/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/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 4e7f6194..4c7da40a 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -261,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 @@ -299,6 +299,38 @@ 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). + +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 +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 new file mode 100644 index 00000000..00f0727f --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/languages/first-line.plugin.json @@ -0,0 +1,20 @@ +{ + "schemaVersion": 0, + "pluginAPIVersion": 0, + "id": "dev.lithe.test.first-line", + "displayName": "First-line fixture", + "version": "1.0.0", + "requires": { "languages": 0 }, + "vendor": { "id": "org.example", "displayName": "Example", "signatureRequirement": "publisherPackage" }, + "permissions": [], + "activationEvents": [], + "languages": [ + { + "id": "sample", + "displayName": "Sample", + "fileExtensions": ["sample"], + "grammar": { "kind": "textmate", "path": "grammars/sample.tmLanguage.json" }, + "configuration": { "lineComment": "//" } + } + ] +} 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/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/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/domains/languages.md b/shared/plugins/reference/domains/languages.md index 2f2140fd..2a3848e9 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`。`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)。语法和编辑器配置是纯数据:宿主从包里读取,编辑器直接应用,不启动任何进程。只有语法的插件不需要语言服务器、后端或激活事件。 +无后缀脚本可以通过包内 TextMate 语法文件的顶层 `firstLineMatch` 声明 shebang。沿用宿主已有语法的插件把同一字段放在 `grammars/.first-line.json`,并省略语法声明。旧桌面可以忽略这项提示,插件仍声明 `languages: 0`。既有文件关联优先,编辑器只检查至多 1024 UTF-8 字节的完整首行。详见[首行匹配](../../contract/v1/README.md#first-line-matching)。 + ```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`. 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,14 @@ 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. 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). + ```json { "id": "http", diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 5bf19364..f3b2d39b 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,6 +14,8 @@ ## 待合入 +- [#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)。 ## 按协议查首次出现