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
1 change: 1 addition & 0 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 26 additions & 4 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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/<language-id>.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
Expand Down
4 changes: 4 additions & 0 deletions rust/crates/core/src/protocol/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand Down Expand Up @@ -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)),
Expand Down Expand Up @@ -1853,6 +1856,7 @@ mod tests {
"toolchains.instantiateLaunch",
"run.decodeStart",
"debug.decodeBackendConfiguration",
"languages.matchFirstLine",
"outputLinks.match",
"outputLinks.decodeResolution",
"outputStyle.decode",
Expand Down
3 changes: 3 additions & 0 deletions rust/crates/core/src/runtime/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,9 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon
parsed.payload,
crate::build::run_decode_start_command::<Manifest>,
),
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)
}
Expand Down
32 changes: 32 additions & 0 deletions rust/crates/core/src/runtime/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand Down
178 changes: 178 additions & 0 deletions rust/crates/core/src/tests/plugin_editor_resources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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<Value>| {
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());
}
27 changes: 22 additions & 5 deletions rust/crates/plugin-grammar/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,9 +152,17 @@ fn grammar_error(field: impl Into<String>, message: impl Into<String>) -> 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<String> {
/// 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<String>,
}

/// Validates a TextMate grammar and returns the metadata for editor registration.
pub fn decode_textmate(text: &str) -> Validation<TextmateMetadata> {
if text.len() > MAX_GRAMMAR_BYTES {
return Err(grammar_error(
"grammar",
Expand All @@ -163,7 +171,7 @@ pub fn decode_textmate(text: &str) -> Validation<String> {
}
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.",
Expand Down Expand Up @@ -197,7 +205,16 @@ pub fn decode_textmate(text: &str) -> Validation<String> {
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`].
Expand Down
1 change: 1 addition & 0 deletions rust/crates/plugin-manifest/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading
Loading