Skip to content

Commit 3c0fcff

Browse files
committed
fix(languages): 保留首行编译缓存与已有高亮
1 parent 4d45d66 commit 3c0fcff

10 files changed

Lines changed: 237 additions & 30 deletions

File tree

‎rust/contracts/rust-core-api.md‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5185,7 +5185,8 @@ no match. Never send a truncated prefix. Supply the enabled declarations in
51855185
registry precedence order, in batches of up to 64, stopping on the first match.
51865186
The result preserves the winning ID unchanged. A malformed batch, language ID
51875187
or pattern is an `invalid_request`. Core retains only bounded compiled
5188-
declarations and performs no I/O. See the [first-line pattern
5188+
declarations and performs no I/O. See the shared
5189+
[ABI fixture](../fixtures/plugins/first-line-match-v1.json) and the [first-line pattern
51895190
contract](../../shared/plugins/contract/v1/README.md#first-line-matching).
51905191

51915192
`plugins.declarative.decodeGrammar` accepts `{ manifest, languageID, grammar }`,
@@ -5194,8 +5195,14 @@ inside the installed package, and returns `language: { id, fileExtensions,
51945195
fileNames, grammar: { kind, scopeName, source, firstLineMatch? }, configuration }`.
51955196
The editor registers the validated `textmate` JSON `source` byte for byte under
51965197
`scopeName`.
5197-
When present, `firstLineMatch` holds validated optional root-level metadata
5198-
for `languages.matchFirstLine`. Unsupported or malformed hints are omitted.
5198+
When present, `grammar.firstLineMatch` holds validated optional root-level
5199+
metadata for `languages.matchFirstLine`. For a language without an explicit
5200+
`grammar.path`, the host can instead pass the text from
5201+
`grammars/<language-id>.first-line.json` as `grammar`. Core returns a valid hint
5202+
as `language.firstLineMatch`, with `language.grammar` set to `null` so the editor
5203+
uses its existing grammar. Unsupported or malformed hints are omitted. A
5204+
standalone file with invalid JSON or above its size limit is rejected as
5205+
`plugin.grammar.invalid`.
51995206
Hosts run plugin grammars only off the editor UI thread,
52005207
with bounded backtracking and a time budget per line. A grammar Core
52015208
refuses is `plugin.grammar.invalid` with the failing `field`; a language

‎rust/crates/core/src/runtime/ffi.rs‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,38 @@ mod text_content_tests {
253253
mod editor_essentials_tests {
254254
use super::*;
255255
use serde_json::{json, Value};
256+
257+
#[test]
258+
fn first_line_match_abi_matches_shared_vectors() {
259+
let fixture: Value = serde_json::from_str(include_str!(
260+
"../../../../fixtures/plugins/first-line-match-v1.json"
261+
))
262+
.unwrap();
263+
for case in fixture["cases"].as_array().unwrap() {
264+
let request = CString::new(
265+
json!({
266+
"id": case["name"],
267+
"command": fixture["command"],
268+
"payload": case["payload"]
269+
})
270+
.to_string(),
271+
)
272+
.unwrap();
273+
let pointer = unsafe { lithe_core_execute_json(request.as_ptr()) };
274+
assert!(!pointer.is_null());
275+
let response = unsafe { serde_json::from_slice(CStr::from_ptr(pointer).to_bytes()) };
276+
unsafe { lithe_core_free_string(pointer) };
277+
let response: Value = response.unwrap();
278+
if case["errorCode"].is_string() {
279+
assert_eq!(response["id"], case["name"]);
280+
assert_eq!(response["ok"], false, "{response}");
281+
assert_eq!(response["error"]["code"], case["errorCode"]);
282+
} else {
283+
assert_eq!(response, case["expected"], "{}", case["name"]);
284+
}
285+
}
286+
}
287+
256288
#[test]
257289
fn borrowed_document_abi_matches_shared_vectors() {
258290
let fixture: Value = serde_json::from_str(include_str!(

‎rust/crates/core/src/tests/plugin_editor_resources.rs‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ const GRAMMAR_PLUGIN: &str = contract_file!("fixtures/languages/language-grammar
1717
const HTTP_GRAMMAR: &str = contract_file!("fixtures/languages/grammars/http.tmLanguage.json");
1818
const FIRST_LINE_PLUGIN: &str = contract_file!("fixtures/languages/first-line.plugin.json");
1919
const SAMPLE_GRAMMAR: &str = contract_file!("fixtures/languages/grammars/sample.tmLanguage.json");
20+
const SAMPLE_FIRST_LINE: &str =
21+
contract_file!("fixtures/languages/grammars/sample.first-line.json");
2022

2123
fn manifest(source: &str) -> Value {
2224
serde_json::from_str(source).expect("fixture manifest is JSON")
@@ -409,6 +411,50 @@ fn first_line_grammar_uses_the_existing_language_capability() {
409411
);
410412
}
411413

414+
#[test]
415+
fn standalone_first_line_metadata_keeps_the_existing_grammar() {
416+
let mut plugin = manifest(FIRST_LINE_PLUGIN);
417+
plugin["languages"][0]
418+
.as_object_mut()
419+
.unwrap()
420+
.remove("grammar");
421+
let admission = validate_command(json!({
422+
"manifest": plugin,
423+
"hostCapabilities": { "languages": [0] },
424+
}))
425+
.unwrap();
426+
assert_eq!(admission["status"], "ok", "{admission}");
427+
let decode = |source: &str| {
428+
decode_grammar_command(json!({
429+
"manifest": admission["plugin"],
430+
"languageID": "sample",
431+
"grammar": source,
432+
}))
433+
.unwrap()
434+
};
435+
let decoded = decode(SAMPLE_FIRST_LINE);
436+
assert_eq!(decoded["status"], "ok", "{decoded}");
437+
assert!(decoded["language"]["grammar"].is_null());
438+
assert_eq!(
439+
decoded["language"]["firstLineMatch"],
440+
manifest(SAMPLE_FIRST_LINE)["firstLineMatch"]
441+
);
442+
assert_eq!(decoded["language"]["configuration"]["lineComment"], "//");
443+
let unsupported = decode(r#"{"firstLineMatch":"["}"#);
444+
assert_eq!(unsupported["status"], "ok", "{unsupported}");
445+
assert!(unsupported["language"]["grammar"].is_null());
446+
assert!(!unsupported["language"]
447+
.as_object()
448+
.unwrap()
449+
.contains_key("firstLineMatch"));
450+
451+
for source in ["invalid JSON", "[]", &" ".repeat(4097)] {
452+
let result = decode(source);
453+
assert_eq!(result["status"], "rejected", "{result}");
454+
assert_eq!(result["error"]["code"], "plugin.grammar.invalid");
455+
}
456+
}
457+
412458
#[test]
413459
fn unsupported_first_line_metadata_keeps_its_grammar() {
414460
for pattern in [

‎rust/crates/plugin-manifest/src/commands.rs‎

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -157,12 +157,12 @@ struct GrammarPayload {
157157
manifest: Value,
158158
#[serde(rename = "languageID")]
159159
language_id: String,
160-
/// Text of the grammar file the host read from the package.
160+
/// Text of the grammar or first-line metadata file the host read from the package.
161161
grammar: String,
162162
}
163163

164-
/// `plugins.declarative.decodeGrammar`: validates the grammar file of one
165-
/// language and returns what the editor registers for it.
164+
/// `plugins.declarative.decodeGrammar`: validates the grammar or metadata of
165+
/// one language and returns what the editor registers for it.
166166
pub fn decode_grammar_command(payload: Value) -> Result<Value, CoreError> {
167167
let payload: GrammarPayload = decode_payload(payload, "plugins.declarative.decodeGrammar")?;
168168
Ok(outcome(validate_manifest_value(payload.manifest).and_then(
@@ -171,7 +171,11 @@ pub fn decode_grammar_command(payload: Value) -> Result<Value, CoreError> {
171171
.languages
172172
.iter()
173173
.find(|language| language.id == payload.language_id)
174-
.filter(|language| language.grammar.is_some() || language.configuration.is_some())
174+
.filter(|language| {
175+
language.grammar.is_some()
176+
|| language.configuration.is_some()
177+
|| !payload.grammar.is_empty()
178+
})
175179
.ok_or_else(|| {
176180
PluginRejection::new(
177181
"plugin.grammar.unavailable",
@@ -205,16 +209,22 @@ pub fn decode_grammar_command(payload: Value) -> Result<Value, CoreError> {
205209
}
206210
})
207211
.transpose()?;
208-
Ok((
209-
"language",
210-
json!({
211-
"id": language.id,
212-
"fileExtensions": language.file_extensions,
213-
"fileNames": language.file_names,
214-
"grammar": grammar,
215-
"configuration": language.configuration,
216-
}),
217-
))
212+
let mut decoded = json!({
213+
"id": language.id,
214+
"fileExtensions": language.file_extensions,
215+
"fileNames": language.file_names,
216+
"grammar": grammar,
217+
"configuration": language.configuration,
218+
});
219+
let standalone_hint = if language.grammar.is_none() && !payload.grammar.is_empty() {
220+
crate::first_line::decode_metadata(&payload.grammar)?
221+
} else {
222+
None
223+
};
224+
if let Some(pattern) = standalone_hint {
225+
decoded["firstLineMatch"] = json!(pattern);
226+
}
227+
Ok(("language", decoded))
218228
},
219229
)))
220230
}

‎rust/crates/plugin-manifest/src/first_line.rs‎

Lines changed: 77 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Bounded, data-only first-line language matching for documents with no path association.
22
33
use super::{declarations::is_language_id, decode_payload, CoreError, ErrorCode};
4+
use lithe_plugin_model::{PluginRejection, Validation};
45
use regex::{Regex, RegexBuilder};
56
use serde::Deserialize;
67
use serde_json::{json, Value};
@@ -10,21 +11,33 @@ use std::sync::{Arc, Mutex, OnceLock};
1011
const MAX_PATTERN_BYTES: usize = 512;
1112
const MAX_FIRST_LINE_BYTES: usize = 1024;
1213
const MAX_CANDIDATES: usize = 64;
14+
const CACHE_CAPACITY: usize = 64;
1315
const REGEX_SIZE_LIMIT: usize = 256 * 1024;
16+
const MAX_METADATA_BYTES: usize = 4096;
1417

15-
/// Use the same compiled program in grammar decoding and on repeated document opens.
16-
/// The cache contains only declaration text and programs, never document content.
17-
fn compiled(source: &str) -> Result<Arc<Regex>, &'static str> {
18+
type PatternCache = VecDeque<(String, Arc<Regex>)>;
19+
20+
#[derive(Clone, Copy)]
21+
enum CacheAccess {
22+
Register,
23+
Match,
24+
}
25+
26+
fn compiled_in(
27+
cache: &Mutex<PatternCache>,
28+
source: &str,
29+
access: CacheAccess,
30+
) -> Result<Arc<Regex>, &'static str> {
1831
if source.is_empty() || source.len() > MAX_PATTERN_BYTES {
1932
return Err("A first-line pattern must be 1 to 512 UTF-8 bytes.");
2033
}
21-
type Cache = VecDeque<(String, Arc<Regex>)>;
22-
static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
23-
let cache = CACHE.get_or_init(Mutex::default);
24-
let mut entries = cache.lock().unwrap_or_else(|poison| poison.into_inner());
34+
let entries = cache.lock().unwrap_or_else(|poison| poison.into_inner());
2535
if let Some((_, regex)) = entries.iter().find(|(pattern, _)| pattern == source) {
2636
return Ok(Arc::clone(regex));
2737
}
38+
drop(entries);
39+
40+
// A cold compilation should not block other workers' cache hits.
2841
let regex = RegexBuilder::new(source)
2942
.size_limit(REGEX_SIZE_LIMIT)
3043
.dfa_size_limit(REGEX_SIZE_LIMIT)
@@ -34,16 +47,52 @@ fn compiled(source: &str) -> Result<Arc<Regex>, &'static str> {
3447
return Err("A first-line pattern cannot match empty input.");
3548
}
3649
let regex = Arc::new(regex);
37-
if entries.len() == MAX_CANDIDATES {
50+
let mut entries = cache.lock().unwrap_or_else(|poison| poison.into_inner());
51+
if let Some((_, existing)) = entries.iter().find(|(pattern, _)| pattern == source) {
52+
return Ok(Arc::clone(existing));
53+
}
54+
if entries.len() == CACHE_CAPACITY {
55+
// Document matching can encounter more than one batch. Filling the
56+
// cache is useful, but evicting warm patterns during a scan makes the
57+
// next opening repeat the same compilations.
58+
if matches!(access, CacheAccess::Match) {
59+
return Ok(regex);
60+
}
3861
entries.pop_front();
3962
}
4063
entries.push_back((source.to_owned(), Arc::clone(&regex)));
4164
Ok(regex)
4265
}
4366

67+
/// Use the same compiled program in grammar decoding and on repeated document opens.
68+
/// The cache contains only declaration text and programs, never document content.
69+
fn compiled(source: &str, access: CacheAccess) -> Result<Arc<Regex>, &'static str> {
70+
static CACHE: OnceLock<Mutex<PatternCache>> = OnceLock::new();
71+
compiled_in(CACHE.get_or_init(Mutex::default), source, access)
72+
}
73+
4474
/// Whether a grammar hint uses the syntax and budget of the first-line matcher.
4575
pub(crate) fn supports_pattern(source: &str) -> bool {
46-
compiled(source).is_ok()
76+
compiled(source, CacheAccess::Register).is_ok()
77+
}
78+
79+
/// Reads only the hint from a standalone TextMate metadata file. An absent or
80+
/// unsupported hint leaves the language's existing highlighting intact.
81+
pub(crate) fn decode_metadata(source: &str) -> Validation<Option<String>> {
82+
let invalid =
83+
|message| PluginRejection::at("plugin.grammar.invalid", "firstLineMatch", message);
84+
if source.len() > MAX_METADATA_BYTES {
85+
return Err(invalid(
86+
"The first-line metadata file is larger than 4096 bytes.",
87+
));
88+
}
89+
let metadata = serde_json::from_str::<serde_json::Map<String, Value>>(source)
90+
.map_err(|_| invalid("The first-line metadata file must be a JSON object."))?;
91+
Ok(metadata
92+
.get("firstLineMatch")
93+
.and_then(Value::as_str)
94+
.filter(|pattern| supports_pattern(pattern))
95+
.map(str::to_owned))
4796
}
4897

4998
#[derive(Deserialize)]
@@ -81,7 +130,8 @@ pub fn match_first_line(payload: Value) -> Result<Value, CoreError> {
81130
if !is_language_id(&candidate.language_id) {
82131
return Err(invalid_request("Invalid first-line candidate language ID."));
83132
}
84-
let regex = compiled(&candidate.first_line_match).map_err(invalid_request)?;
133+
let regex =
134+
compiled(&candidate.first_line_match, CacheAccess::Match).map_err(invalid_request)?;
85135
if eligible
86136
&& selected.is_none()
87137
&& regex
@@ -93,3 +143,20 @@ pub fn match_first_line(payload: Value) -> Result<Value, CoreError> {
93143
}
94144
Ok(json!({"languageID": selected}))
95145
}
146+
147+
#[cfg(test)]
148+
mod tests {
149+
use super::*;
150+
151+
#[test]
152+
fn scanning_more_than_one_batch_keeps_cached_patterns() {
153+
let cache = Mutex::default();
154+
let initial = compiled_in(&cache, "^sample-0$", CacheAccess::Register).unwrap();
155+
for i in 1..=MAX_CANDIDATES {
156+
compiled_in(&cache, &format!("^sample-{i}$"), CacheAccess::Match).unwrap();
157+
}
158+
let repeated = compiled_in(&cache, "^sample-0$", CacheAccess::Match).unwrap();
159+
assert!(Arc::ptr_eq(&initial, &repeated));
160+
assert_eq!(cache.lock().unwrap().len(), CACHE_CAPACITY);
161+
}
162+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
{
2+
"schemaVersion": 1,
3+
"command": "languages.matchFirstLine",
4+
"cases": [
5+
{
6+
"name": "uses-registry-order",
7+
"payload": {
8+
"firstLine": "#!/usr/bin/env -S sample3 -f",
9+
"candidates": [
10+
{ "languageID": "sample", "firstLineMatch": "^#! */usr/bin/env +-S +sample[0-9]*(?: |$)" },
11+
{ "languageID": "other", "firstLineMatch": "^#!" }
12+
]
13+
},
14+
"expected": { "id": "uses-registry-order", "ok": true, "data": { "languageID": "sample" } }
15+
},
16+
{
17+
"name": "returns-null-for-no-match",
18+
"payload": {
19+
"firstLine": "#!/usr/bin/env other",
20+
"candidates": [{ "languageID": "sample", "firstLineMatch": "^#! */usr/bin/env +sample(?: |$)" }]
21+
},
22+
"expected": { "id": "returns-null-for-no-match", "ok": true, "data": { "languageID": null } }
23+
},
24+
{
25+
"name": "rejects-an-invalid-candidate",
26+
"payload": {
27+
"firstLine": "#!/usr/bin/env sample",
28+
"candidates": [{ "languageID": "sample", "firstLineMatch": "[" }]
29+
},
30+
"errorCode": "invalid_request"
31+
}
32+
]
33+
}

‎shared/plugins/contract/v1/README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,13 @@ still install the package and apply its existing file associations and
309309
highlighting. See the [fixture manifest](fixtures/languages/first-line.plugin.json)
310310
and [grammar](fixtures/languages/grammars/sample.tmLanguage.json).
311311

312+
To keep the editor's existing highlighting for a contributed language, omit
313+
`languages[].grammar` and package the hint in
314+
[`grammars/<language-id>.first-line.json`](fixtures/languages/grammars/sample.first-line.json).
315+
The standalone file is a JSON object of at most 4096 UTF-8 bytes with the same
316+
`firstLineMatch` field. Earlier hosts ignore this resource. An explicit grammar
317+
declaration takes precedence over the standalone file.
318+
312319
Core interprets this hint as a Rust regular expression of 1–512 UTF-8 bytes.
313320
For example, `"firstLineMatch": "^#! */opt/tools/sample(?: |$)"` matches the
314321
interpreter followed by a space or the end of the line. The pattern cannot
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"firstLineMatch": "^#![ \\t]*(?:/usr/bin/env[ \\t]+(?:-S[ \\t]+)?|/opt/tools/)sample[0-9]*(?:[ \\t]|$)"
3+
}

‎shared/plugins/reference/domains/languages.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
`languages[]` 的 `id`、`fileExtensions`、`fileNames`、`projectFileNames` 和 `dependencies` 的规则见[契约的 Languages 一节](../../contract/v1/README.md#languages)。语法和编辑器配置是纯数据:宿主从包里读取,编辑器直接应用,不启动任何进程。只有语法的插件不需要语言服务器、后端或激活事件。
2222

23-
无后缀脚本可以通过包内 TextMate 语法文件的顶层 `firstLineMatch` 声明 shebang。格式为 Rust 正则表达式,旧桌面可以忽略这项提示,插件仍声明 `languages: 0`。文件的既有语言关联优先,编辑器只检查至多 1024 UTF-8 字节的完整首行。详见[首行匹配](../../contract/v1/README.md#first-line-matching)。
23+
无后缀脚本可以通过包内 TextMate 语法文件的顶层 `firstLineMatch` 声明 shebang。沿用宿主已有语法的插件把同一字段放在 `grammars/<language-id>.first-line.json`,并省略语法声明。旧桌面可以忽略这项提示,插件仍声明 `languages: 0`。既有文件关联优先,编辑器只检查至多 1024 UTF-8 字节的完整首行。详见[首行匹配](../../contract/v1/README.md#first-line-matching)。
2424

2525
```json
2626
{
@@ -299,7 +299,9 @@ Languages let Lithe recognize a language: identify its files, highlight them wit
299299
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.
300300

301301
Extensionless scripts can declare a shebang as a root-level `firstLineMatch`
302-
Rust regex in the packaged TextMate grammar. Keep `languages: 0` so older
302+
Rust regex in the packaged TextMate grammar. To inherit the editor's
303+
highlighting, put the field in `grammars/<language-id>.first-line.json` and omit
304+
the grammar declaration. Keep `languages: 0` so older
303305
hosts can install the same package and ignore the hint. Existing file
304306
associations take priority. The editor checks a complete first line of up to
305307
1024 UTF-8 bytes. See [first-line matching](../../contract/v1/README.md#first-line-matching).

0 commit comments

Comments
 (0)