Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 67 additions & 3 deletions rust/crates/core/src/tests/plugin_editor_resources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,9 +226,74 @@ fn grammar_size_rule_count_and_nesting_are_bounded() {
assert!(field.ends_with(".patterns[0]"), "{field}");
}

/// Injections are rules the editor runs, keyed by the scope selector where
/// they apply, so each is checked and counted like any other rule, and their
/// number and selector length are bounded because every scan tests them.
#[test]
fn injections_are_checked_like_the_rules_they_add() {
let rejected = |injections: Value, field: &str| {
let grammar =
json!({ "scopeName": "source.test", "patterns": [], "injections": injections });
let (code, actual) = grammar_rejection(&grammar.to_string());
assert_eq!(code, "plugin.grammar.invalid", "{grammar}");
assert_eq!(actual, field, "{grammar}");
};
rejected(json!([]), "grammar.injections");
rejected(
json!({ "L:source.test": "#php-tag" }),
"grammar.injections.L:source.test",
);
rejected(
json!({ "R:source.test": { "patterns": [{ "match": 1 }] } }),
"grammar.injections.R:source.test.patterns[0].match",
);
rejected(json!({ "": { "match": "a" } }), "grammar.injections.");
let long = "s".repeat(1025);
rejected(
json!({ long.clone(): { "match": "a" } }),
&format!("grammar.injections.{long}"),
);
let many: serde_json::Map<String, Value> = (0..65)
.map(|index| (format!("source.test{index}"), json!({ "match": "a" })))
.collect();
rejected(Value::Object(many), "grammar.injections");

let mut over_budget = grammar_with(Value::Array(vec![json!({ "match": "a" }); 16384]));
over_budget["injections"] = json!({ "source.test": { "match": "a" } });
assert_eq!(
grammar_rejection(&over_budget.to_string()),
("plugin.grammar.invalid".into(), "grammar".into())
);

let mut most: serde_json::Map<String, Value> = (0..63)
.map(|index| (format!("source.test{index}"), json!({ "match": "a" })))
.collect();
most.insert("s".repeat(1024), json!({ "include": "#tag" }));
let accepted = json!({
"scopeName": "text.html.test",
"patterns": [{ "include": "text.html.basic" }],
"repository": { "tag": { "match": "<\\?test", "name": "punctuation.section.embedded" } },
"injections": most,
});
assert_eq!(decode_grammar(&accepted.to_string())["status"], "ok");

let php = json!({
"scopeName": "text.html.test",
"patterns": [{ "include": "text.html.basic" }],
"repository": { "tag": { "match": "<\\?test" } },
"injections": {
"text.html.test - (meta.embedded | meta.tag), L:((text.html.test meta.tag) - (meta.embedded.block.test | meta.embedded.line.test))": {
"patterns": [{ "include": "#tag" }]
},
"L:meta.embedded.test.blade": { "patterns": [{ "include": "text.html.test.blade#blade" }] }
}
});
assert_eq!(decode_grammar(&php.to_string())["status"], "ok");
}

/// What VS Code grammars carry that the editor does not run is accepted
/// unchecked: notes, injections, includes of grammars the editor may not have,
/// and repository entries nothing includes.
/// unchecked: notes, `injectionSelector`, includes of grammars the editor may
/// not have, and repository entries nothing includes.
#[test]
fn what_the_engine_does_not_read_is_accepted_as_in_vs_code() {
let grammar = json!({
Expand All @@ -239,7 +304,6 @@ fn what_the_engine_does_not_read_is_accepted_as_in_vs_code() {
"fileTypes": 5,
"uuid": {},
"injectionSelector": "L:source.other",
"injections": { "R:source.test": { "patterns": [{ "match": 1 }] } },
"patterns": [
{ "include": "$self" },
{ "include": "$base" },
Expand Down
43 changes: 39 additions & 4 deletions rust/crates/plugin-grammar/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,13 @@
//! size, so every grammar Core accepts loads in the editor and none can make
//! it allocate without limit. An include of another grammar's scope resolves
//! against the grammars the editor has; an include nothing defines matches
//! nothing, as in VS Code. `injections` and `injectionSelector` are not run,
//! so they are not checked. Regex cost cannot be proven from the source: the
//! editor tokenizes plugin grammars off its UI thread with a time budget per
//! line, and a pattern its engine cannot compile never matches.
//! nothing, as in VS Code. `injections` run as in VS Code: the grammar being
//! tokenized applies its own, keyed by scope selector, and the injections of
//! a grammar it includes do not apply. `injectionSelector` is not run, since
//! no grammar is injected into another, so it is not checked. Regex cost
//! cannot be proven from the source: the editor tokenizes plugin grammars off
//! its UI thread with a time budget per line, and a pattern its engine cannot
//! compile never matches.
//!
//! Note: the decision is recorded in .agents/notes/implemented/architecture/2026-10-31-plugin-editor-extension-apis.md

Expand All @@ -41,6 +44,11 @@ const MAX_SCOPE_NAME_BYTES: usize = 128;
const MAX_SCOPES_BYTES: usize = 1024;
/// Longest `include` or repository key.
const MAX_REFERENCE_BYTES: usize = 256;
/// Most `injections` entries. The editor tests every selector where it
/// scans, so the count bounds the work each position adds.
const MAX_INJECTIONS: usize = 64;
/// Longest scope selector keying an injection. PHP's is 262 bytes.
const MAX_SELECTOR_BYTES: usize = 1024;
/// Most bracket pairs in a language configuration.
const MAX_BRACKETS: usize = 32;
/// Longest comment or bracket delimiter.
Expand Down Expand Up @@ -186,6 +194,9 @@ pub fn decode_textmate(text: &str) -> Validation<String> {
if let Some(repository) = grammar.get("repository") {
rules.repository(repository, "grammar.repository", 1)?;
}
if let Some(injections) = grammar.get("injections") {
rules.injections(injections, "grammar.injections")?;
}
Ok(scope_name)
}

Expand Down Expand Up @@ -215,6 +226,30 @@ impl RuleBudget {
Ok(())
}

/// Injections are an object of rules keyed by scope selector.
fn injections(&mut self, injections: &Value, field: &str) -> Validation<()> {
let Value::Object(entries) = injections else {
return Err(grammar_error(
field,
"injections is an object of rules keyed by scope selector.",
));
};
if entries.len() > MAX_INJECTIONS {
return Err(grammar_error(field, "A grammar has at most 64 injections."));
}
for (selector, rule) in entries {
let entry_field = format!("{field}.{selector}");
if selector.is_empty() || selector.len() > MAX_SELECTOR_BYTES {
return Err(grammar_error(
entry_field,
"An injection selector is 1 to 1024 bytes.",
));
}
self.rule(rule, &entry_field, 1)?;
}
Ok(())
}

fn rule(&mut self, rule: &Value, field: &str, depth: usize) -> Validation<()> {
self.count += 1;
if self.count > MAX_RULES {
Expand Down
24 changes: 17 additions & 7 deletions shared/plugins/contract/v1/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,8 @@ activation event, and a plugin may consist of grammars alone.
[`fixtures/languages/grammars/http.tmLanguage.json`](fixtures/languages/grammars/http.tmLanguage.json)
is a complete example. A grammar is an object with `scopeName`, 1 to 128
bytes of ASCII letters, digits, `.`, `-`, `_`, and `+`, and a `patterns`
array, and optionally `repository` and `name`. Every rule is an object. The
editor reads `include`, `match`, `begin`, `end`, `while`, `name`,
array, and optionally `repository`, `injections`, and `name`. Every rule is
an object. The editor reads `include`, `match`, `begin`, `end`, `while`, `name`,
`contentName`, `captures`, `beginCaptures`, `endCaptures`, `whileCaptures`,
`patterns`, `repository`, and `applyEndPatternLast` (`true`, `false`, `0`,
or `1`), and Core refuses a grammar where one of them has another type.
Expand All @@ -262,18 +262,28 @@ activation event, and a plugin may consist of grammars alone.
checked.
- 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, and `include` targets and
repository keys of 256 bytes. VS Code's own grammars, the largest of which is
C++ at 662 KiB and 3165 rules, are well within these bounds.
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.
- `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
embeds a language such as CSS inside HTML; an include that resolves to
nothing matches nothing, as in VS Code. `injections` and `injectionSelector`
are not supported, so they are ignored and not checked.
nothing matches nothing, as in VS Code.
- `injections` is an object of rules keyed by scope selector, run as VS Code
runs them: where the scopes at a position match a selector, the rule's
patterns are tried alongside the current rule's. The match that starts
earlier wins; at the same start the current rule wins, unless the selector
has the `L:` prefix. Only the grammar a document is tokenized with applies
its injections; those of a grammar it includes do not, which is how
`text.html.php` marks `<?php` inside the tags, scripts, and styles of the
HTML it includes. Each injection is a rule checked and counted like any
other. `injectionSelector` is not supported, since no grammar is injected
into another, so it is ignored and not checked.
- A plugin grammar replaces the editor's own grammar of the same `scopeName`
while the plugin is enabled. Two plugin languages cannot register the same
scope: the first keeps it, and the other is reported and opens as plain
Expand Down
10 changes: 6 additions & 4 deletions shared/plugins/reference/domains/languages.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@
```

- `grammar.kind` 只有 `textmate` 一种。`grammar.path` 指向包内的 `.tmLanguage.json`(plist 和 YAML 语法要先转成 JSON)。宿主只读地从已安装的包里读取它,交给 `plugins.declarative.decodeGrammar` 校验,然后用返回的 `scopeName` 注册校验过的 `source`。Core 拒绝的语法是 `plugin.grammar.invalid`,并带出错字段;该语言按纯文本打开,插件其余部分照常工作。
- 上限:语法最大 2 MiB,规则(含每个 pattern、repository 项和捕获)最多 16384 条,嵌套 32 层,正则 32 KiB,捕获组 4096 个,`name`、`contentName` 1024 字节,`include` 目标和 repository 键 256 字节。
- 上限:语法最大 2 MiB,规则(含每个 pattern、repository 项和捕获)最多 16384 条,嵌套 32 层,正则 32 KiB,捕获组 4096 个,`name`、`contentName` 1024 字节,`include` 目标和 repository 键 256 字节,`injections` 最多 64 项、选择器 1024 字节。
- 正则使用 TextMate 语法所用的 Oniguruma 语法。编辑器的引擎编译不了的模式永不匹配,语法的其余部分照常生效。
- `include` 可以是 `$self`、`$base`、`#name`(repository 项),或 `scope`、`scope#name`(另一个语法)。`injections` 和 `injectionSelector` 不支持,会被忽略。
- `include` 可以是 `$self`、`$base`、`#name`(repository 项),或 `scope`、`scope#name`(另一个语法)。
- `injections` 是以 scope 选择器为键的规则对象,按 VS Code 的方式运行:某个位置的 scope 符合选择器时,该规则的模式和当前规则的模式一起尝试,起点更靠前的匹配胜出;起点相同时当前规则胜出,除非选择器带 `L:` 前缀。只有给文档分词的那个语法会应用自己的 `injections`,被它包含的语法的 `injections` 不生效。`injectionSelector` 不支持,会被忽略。
- 插件语法在启用期间替换编辑器里同一 `scopeName` 的语法。两个插件语言不能注册同一个 scope:先注册的保留,另一个报告后按纯文本打开。
- `configuration` 包含 `lineComment`、`blockComment`(开始和结束)、`brackets`、`autoClosingPairs`。每个定界符 1–16 字节且不含控制字符,每个列表最多 32 对。
- 插件语法从不在编辑器界面线程上运行。宿主限制每次正则搜索的回溯和每行的耗时,无法在预算内分词的行按纯文本绘制。
Expand Down Expand Up @@ -311,9 +312,10 @@ The rules for `id`, `fileExtensions`, `fileNames`, `projectFileNames`, and `depe
```

- `grammar.kind` is only `textmate`. `grammar.path` names a `.tmLanguage.json` file in the package (plist and YAML grammars are converted to JSON first). The host reads it read-only from the installed package, passes it to `plugins.declarative.decodeGrammar`, and registers the returned `source` under the returned `scopeName`. A grammar Core refuses is `plugin.grammar.invalid` with the failing field; the language then opens as plain text and the rest of the plugin keeps working.
- Limits: a grammar is at most 2 MiB; at most 16384 rules, counting every pattern, repository entry, and capture; nesting 32 deep; regexes of 32 KiB; 4096 capture groups; `name` and `contentName` of 1024 bytes; `include` targets and repository keys of 256 bytes.
- Limits: a grammar is at most 2 MiB; at most 16384 rules, counting every pattern, repository entry, and capture; nesting 32 deep; regexes of 32 KiB; 4096 capture groups; `name` and `contentName` of 1024 bytes; `include` targets and repository keys of 256 bytes; 64 injections with selectors of 1024 bytes.
- Regexes use the Oniguruma syntax TextMate grammars are written in. A pattern the editor's engine cannot compile 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. `injections` and `injectionSelector` are not supported and are ignored.
- `include` is `$self`, `$base`, `#name` for a repository entry, or `scope` or `scope#name` for another grammar.
- `injections` is an object of rules keyed by scope selector, run as VS Code runs them: where the scopes at a position match a selector, the rule's patterns are tried alongside the current rule's, and the match that starts earlier wins; at the same start the current rule wins unless the selector has the `L:` prefix. Only the grammar a document is tokenized with applies its injections; those of a grammar it includes do not. `injectionSelector` is not supported and is ignored.
- A plugin grammar replaces the editor's own grammar of the same `scopeName` while the plugin is enabled. Two plugin languages cannot register the same scope: the first keeps it, and the other opens as plain text.
- `configuration` sets `lineComment`, `blockComment` (open and close), `brackets`, and `autoClosingPairs`. Each delimiter is 1 to 16 bytes without control characters; each list has at most 32 pairs.
- Plugin grammars never run on the editor UI thread. The host bounds the backtracking of each regex search and the time one line may take; a line that cannot be tokenized within that budget is drawn as plain text.
Expand Down
1 change: 1 addition & 0 deletions shared/plugins/reference/protocol-changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@

| PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 |
| --- | --- | --- | --- | --- |
| [#83](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/83) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | `languages` 0 内的补充 | 编辑器的 TextMate 引擎按 vscode-textmate 的方式运行语法的 `injections`([1lck/Lithe-IDEA#2112](https://github.com/1lck/Lithe-IDEA/issues/2112)):只有给文档分词的那个语法应用自己的 `injections`,被它包含的语法的不生效;某个位置的 scope 符合选择器时,注入规则和当前规则一起尝试,起点更靠前的匹配胜出,起点相同时当前规则胜出,除非选择器带 `L:` 前缀。Core 随之校验它:`injections` 是以 scope 选择器为键的规则对象,最多 64 项,选择器 1–1024 字节,每条规则和其他规则一样检查并计入 16384 条上限,违反时以 `plugin.grammar.invalid`(字段 `grammar.injections[.<选择器>…]`)拒绝。`injectionSelector` 仍不运行、不检查。清单格式和能力版本不变,不运行 `injections` 的旧宿主照常加载这些语法;没有新增宿主方法或通知。 |
| [#79](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/79) | [@1lck](https://github.com/1lck) | API-19 | **`sourceSettings` 1** | 原生来源设置可以做成“项目结构”页([1lck/Lithe-IDEA#2086](https://github.com/1lck/Lithe-IDEA/issues/2086)):分组布局 `sidebar` 把来源列成左侧模块列表,来源用 `parent` 嵌套(同组、在前、最多 8 层);字段 `section` 在 `sidebar` 中是标签页、在 `form` 中是小标题;新字段类型 `entryList` 是有序的类型化条目列表,`entryKinds` 声明添加菜单(`file` 可带扩展名、`directory`、`choice` 带可选项),`attributes` 声明至多 4 个布尔或枚举列。条目的 `title`、`detail` 只用于显示,比较和写回时忽略;新增的 `choice` 条目必须来自当前可选项或原值。`SourceInput` 新增 `entries`,`effectiveDisplays` 对条目列表给出 `count`。快照 `version` 仍为 0;用到这些成员的插件声明 `sourceSettings: 1`,只支持 0 的宿主不会安装。新增 fixture `settings-sources-modules.json`。没有新增宿主方法或通知。 |
| [#77](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/77) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-29 | `buildSystems` 0 内的说明修正 | Core 不再内置运行发现探测器([1lck/Lithe-IDEA#1856](https://github.com/1lck/Lithe-IDEA/issues/1856) 第 4 项):原来按 `Cargo.toml`、`go.mod`、`package.json`、`pyproject.toml`、`Makefile`、`justfile`、`Procfile`、`compose.yaml` 自己生成的 Run 配置、指纹输入和工具链要求全部删除。Run 列表里自动生成的条目只来自已启用构建插件声明的 `buildSystems[].run`,模型何时过期只由插件的 `sync.watch` 决定。插件想让项目出现在 Run 列表里,就要声明 `run`。契约 README 只改了一句措辞(不再提“探测器生成的 Run 配置”);清单字段、校验、fixture 和能力版本都没有变,没有新增宿主方法或通知。 |

Expand Down
Loading