Skip to content

Commit d0dacdc

Browse files
authored
Merge pull request #127 from Lithe-IDEA/codex/2122-first-line-language
feat(languages): 支持插件按首行识别无后缀文档
2 parents 9399f16 + 3c0fcff commit d0dacdc

20 files changed

Lines changed: 592 additions & 47 deletions

File tree

‎rust/Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

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

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -485,6 +485,7 @@ or removing a command fails until the table changes in the same commit.
485485
| `plugins.installed.lifecycle` | Report installed plugins' enablement and plan confirming an install, enabling, disabling or uninstalling one |
486486
| `plugins.declarative.editSettings` | Validate one atomic setting edit batch and return replacement text while preserving unrelated plugins and dormant values |
487487
| `plugins.declarative.workspaceConfiguration` | Expand a language server's `workspaceConfiguration` with the merged setting values |
488+
| `languages.matchFirstLine` | Select the first matching registered language for an extensionless document |
488489
| `plugins.declarative.decodeGrammar` | Validate independent static editor resources |
489490
| `plugins.editorActions.decode` | Validate independent action registration, collection or click results |
490491
| `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
51755176
installation starts as a first one. Shared cases are in
51765177
`rust/fixtures/plugins/installed-lifecycle.json`.
51775178

5179+
`languages.matchFirstLine` accepts `{firstLine, candidates:[{languageID,
5180+
firstLineMatch}]}` and returns `{languageID}`, with `null` for no match. The
5181+
host calls it after existing explicit, file-name and extension associations
5182+
fail for a dotless basename. Send only the complete first decoded line minus
5183+
its terminator. Empty input, CR, LF, NUL and lines over 1024 UTF-8 bytes produce
5184+
no match. Never send a truncated prefix. Supply the enabled declarations in
5185+
registry precedence order, in batches of up to 64, stopping on the first match.
5186+
The result preserves the winning ID unchanged. A malformed batch, language ID
5187+
or pattern is an `invalid_request`. Core retains only bounded compiled
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
5190+
contract](../../shared/plugins/contract/v1/README.md#first-line-matching).
5191+
51785192
`plugins.declarative.decodeGrammar` accepts `{ manifest, languageID, grammar }`,
51795193
where `grammar` is the text the host read from the language's `grammar.path`
51805194
inside the installed package, and returns `language: { id, fileExtensions,
5181-
fileNames, grammar: { kind, scopeName, source }, configuration }`. `kind` is
5182-
`textmate`; `source` is the validated original JSON text, byte for byte, which
5183-
the editor's TextMate engine parses and registers under `scopeName`, the
5184-
grammar's own scope. Hosts run plugin grammars only off the editor UI thread,
5195+
fileNames, grammar: { kind, scopeName, source, firstLineMatch? }, configuration }`.
5196+
The editor registers the validated `textmate` JSON `source` byte for byte under
5197+
`scopeName`.
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`.
5206+
Hosts run plugin grammars only off the editor UI thread,
51855207
with bounded backtracking and a time budget per line. A grammar Core
51865208
refuses is `plugin.grammar.invalid` with the failing `field`; a language
51875209
without static editor resources is `plugin.grammar.unavailable`. Configuration-only

‎rust/crates/core/src/protocol/command.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@ pub enum CoreCommand {
7070
Toolchains(ToolchainsCommand),
7171
/// Validates a plugin backend's Run start request (`run.decodeStart`).
7272
RunDecodeStart,
73+
/// Selects a plugin language from an extensionless document's first line.
74+
LanguagesMatchFirstLine,
7375
/// Finds the output links plugin matchers declare in console lines (`outputLinks.match`).
7476
OutputLinksMatch,
7577
/// Checks a plugin function's answer to an output link (`outputLinks.decodeResolution`).
@@ -1189,6 +1191,7 @@ impl CoreCommand {
11891191
"debug.decodeBackendConfiguration" => {
11901192
Some(Self::Debug(DebugCommand::DecodeBackendConfiguration))
11911193
}
1194+
"languages.matchFirstLine" => Some(Self::LanguagesMatchFirstLine),
11921195
"outputLinks.match" => Some(Self::OutputLinksMatch),
11931196
"outputLinks.decodeResolution" => Some(Self::OutputLinksDecodeResolution),
11941197
"build.detect" => Some(Self::Build(BuildCommand::Detect)),
@@ -1853,6 +1856,7 @@ mod tests {
18531856
"toolchains.instantiateLaunch",
18541857
"run.decodeStart",
18551858
"debug.decodeBackendConfiguration",
1859+
"languages.matchFirstLine",
18561860
"outputLinks.match",
18571861
"outputLinks.decodeResolution",
18581862
"outputStyle.decode",

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,9 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon
197197
parsed.payload,
198198
crate::build::run_decode_start_command::<Manifest>,
199199
),
200+
CoreCommand::LanguagesMatchFirstLine => {
201+
plugin_response(id, parsed.payload, lithe_plugin_manifest::match_first_line)
202+
}
200203
CoreCommand::OutputLinksMatch => {
201204
plugin_response(id, parsed.payload, lithe_plugin_output_links::match_lines)
202205
}

‎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: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ macro_rules! contract_file {
1515

1616
const GRAMMAR_PLUGIN: &str = contract_file!("fixtures/languages/language-grammar.plugin.json");
1717
const HTTP_GRAMMAR: &str = contract_file!("fixtures/languages/grammars/http.tmLanguage.json");
18+
const FIRST_LINE_PLUGIN: &str = contract_file!("fixtures/languages/first-line.plugin.json");
19+
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");
1822

1923
fn manifest(source: &str) -> Value {
2024
serde_json::from_str(source).expect("fixture manifest is JSON")
@@ -379,3 +383,177 @@ fn configuration_only_contribution_decodes_without_grammar() {
379383
assert!(result["language"]["grammar"].is_null());
380384
assert_eq!(result["language"]["configuration"]["lineComment"], "#");
381385
}
386+
387+
#[test]
388+
fn first_line_grammar_uses_the_existing_language_capability() {
389+
let plugin = manifest(FIRST_LINE_PLUGIN);
390+
let admission = validate_command(json!({
391+
"manifest": plugin,
392+
"hostCapabilities": { "languages": [0] },
393+
}))
394+
.unwrap();
395+
assert_eq!(admission["status"], "ok", "{admission}");
396+
let outcome = decode_grammar_command(json!({
397+
"manifest": admission["plugin"],
398+
"languageID": "sample",
399+
"grammar": SAMPLE_GRAMMAR,
400+
}))
401+
.unwrap();
402+
assert_eq!(outcome["status"], "ok", "{outcome}");
403+
let language = &outcome["language"];
404+
assert_eq!(language["fileExtensions"], json!(["sample"]));
405+
assert_eq!(language["configuration"]["lineComment"], "//");
406+
assert_eq!(language["grammar"]["scopeName"], "source.sample");
407+
assert_eq!(language["grammar"]["source"], SAMPLE_GRAMMAR);
408+
assert_eq!(
409+
language["grammar"]["firstLineMatch"],
410+
manifest(SAMPLE_GRAMMAR)["firstLineMatch"]
411+
);
412+
}
413+
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+
458+
#[test]
459+
fn unsupported_first_line_metadata_keeps_its_grammar() {
460+
for pattern in [
461+
Value::Null,
462+
json!(42),
463+
json!(""),
464+
json!("a*"),
465+
json!("["),
466+
json!(r"(a)\1"),
467+
json!("a{10000000}"),
468+
json!("é".repeat(257)),
469+
] {
470+
let mut grammar = grammar_with(json!([]));
471+
grammar["firstLineMatch"] = pattern;
472+
let source = grammar.to_string();
473+
let outcome = decode_grammar(&source);
474+
assert_eq!(outcome["status"], "ok", "{outcome}");
475+
let grammar = &outcome["language"]["grammar"];
476+
assert!(!grammar.as_object().unwrap().contains_key("firstLineMatch"));
477+
assert_eq!(grammar["scopeName"], "source.test");
478+
assert_eq!(grammar["source"], source);
479+
}
480+
}
481+
482+
#[test]
483+
fn first_line_matching_keeps_registered_priority_and_never_reads_past_the_line() {
484+
let specific = json!({
485+
"languageID": "sample",
486+
"firstLineMatch": manifest(SAMPLE_GRAMMAR)["firstLineMatch"],
487+
});
488+
let generic = json!({"languageID":"other", "firstLineMatch": "#!"});
489+
let choose = |line: &str, candidates: &[Value]| {
490+
let response = lithe_plugin_manifest::match_first_line(
491+
json!({"firstLine":line, "candidates":candidates}),
492+
)
493+
.unwrap();
494+
response["languageID"].clone()
495+
};
496+
for line in [
497+
"#!/opt/tools/sample",
498+
"#! /usr/bin/env sample3",
499+
"#!/usr/bin/env -S sample3 -f",
500+
] {
501+
assert_eq!(choose(line, &[specific.clone(), generic.clone()]), "sample");
502+
assert_eq!(choose(line, &[generic.clone(), specific.clone()]), "other");
503+
}
504+
for line in [
505+
"x#!/opt/tools/sample",
506+
"#!/opt/tools/sample-extra",
507+
"#!/opt/tools/sample\0",
508+
"\n#!/opt/tools/sample",
509+
"#!/opt/tools/sample\r",
510+
] {
511+
assert_eq!(choose(line, std::slice::from_ref(&specific)), Value::Null);
512+
}
513+
assert_eq!(
514+
choose(
515+
&format!("#!{}", "é".repeat(511)),
516+
std::slice::from_ref(&generic)
517+
),
518+
"other"
519+
);
520+
assert_eq!(
521+
choose(
522+
&format!("#!{}x", "é".repeat(511)),
523+
std::slice::from_ref(&generic)
524+
),
525+
Value::Null
526+
);
527+
assert_eq!(choose("#!/opt/tools/sample", &[]), Value::Null);
528+
// A word boundary alone may match at the start of nonempty text but claims no bytes.
529+
assert_eq!(
530+
choose(
531+
"word",
532+
&[json!({"languageID":"other","firstLineMatch":"\\b"})]
533+
),
534+
Value::Null
535+
);
536+
}
537+
538+
#[test]
539+
fn first_line_matching_validates_the_whole_candidate_batch() {
540+
let entry = json!({"languageID":"sample","firstLineMatch":"#!"});
541+
let call = |candidates: Vec<Value>| {
542+
lithe_plugin_manifest::match_first_line(json!({"firstLine":"#!", "candidates":candidates}))
543+
};
544+
assert_eq!(
545+
call(vec![entry.clone(); 64]).unwrap()["languageID"],
546+
"sample"
547+
);
548+
assert!(call(vec![entry.clone(); 65]).is_err());
549+
assert!(call(vec![
550+
entry.clone(),
551+
json!({"languageID":"UPPER","firstLineMatch":"#!"})
552+
])
553+
.is_err());
554+
assert!(call(vec![
555+
entry,
556+
json!({"languageID":"rest","firstLineMatch":"("})
557+
])
558+
.is_err());
559+
}

‎rust/crates/plugin-grammar/src/lib.rs‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -152,9 +152,17 @@ fn grammar_error(field: impl Into<String>, message: impl Into<String>) -> Plugin
152152
PluginRejection::at("plugin.grammar.invalid", field, message)
153153
}
154154

155-
/// Validates the text of a TextMate grammar file and returns its `scopeName`.
156-
/// Hosts register the original text, which the editor's engine parses itself.
157-
pub fn decode_textmate(text: &str) -> Validation<String> {
155+
/// Metadata read during grammar decoding. The editor still parses the source
156+
/// text itself for highlighting.
157+
pub struct TextmateMetadata {
158+
/// The grammar's validated `scopeName` for editor registration.
159+
pub scope_name: String,
160+
/// The optional root-level pattern for the host to check before matching.
161+
pub first_line_match: Option<String>,
162+
}
163+
164+
/// Validates a TextMate grammar and returns the metadata for editor registration.
165+
pub fn decode_textmate(text: &str) -> Validation<TextmateMetadata> {
158166
if text.len() > MAX_GRAMMAR_BYTES {
159167
return Err(grammar_error(
160168
"grammar",
@@ -163,7 +171,7 @@ pub fn decode_textmate(text: &str) -> Validation<String> {
163171
}
164172
let value: Value = serde_json::from_str(text)
165173
.map_err(|error| grammar_error("grammar", format!("The grammar is not JSON: {error}.")))?;
166-
let Value::Object(grammar) = &value else {
174+
let Value::Object(mut grammar) = value else {
167175
return Err(grammar_error(
168176
"grammar",
169177
"A TextMate grammar is a JSON object.",
@@ -197,7 +205,16 @@ pub fn decode_textmate(text: &str) -> Validation<String> {
197205
if let Some(injections) = grammar.get("injections") {
198206
rules.injections(injections, "grammar.injections")?;
199207
}
200-
Ok(scope_name)
208+
// Other metadata types were accepted by older hosts. Keep the original
209+
// source available for highlighting regardless of the shape of this hint.
210+
let first_line_match = match grammar.remove("firstLineMatch") {
211+
Some(Value::String(pattern)) => Some(pattern),
212+
_ => None,
213+
};
214+
Ok(TextmateMetadata {
215+
scope_name,
216+
first_line_match,
217+
})
201218
}
202219

203220
/// Walks the rules of a grammar, counting them against [`MAX_RULES`].

‎rust/crates/plugin-manifest/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ lithe-project-generators = { path = "../project-generators" }
2222
lithe-protocol = { path = "../protocol" }
2323
lithe-toolchain = { path = "../toolchain" }
2424
lithe-vcs = { path = "../vcs" }
25+
regex = "1.11"
2526
serde = { version = "1.0", features = ["derive"] }
2627
serde_json = { version = "1.0", features = ["preserve_order"] }
2728
sha2 = "0.10"

0 commit comments

Comments
 (0)