Skip to content

Commit 4d45d66

Browse files
committed
feat(languages): read first-line hints from TextMate grammars
1 parent 871f12a commit 4d45d66

17 files changed

Lines changed: 151 additions & 160 deletions

File tree

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

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5186,15 +5186,17 @@ 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
51885188
declarations and performs no I/O. See the [first-line pattern
5189-
contract](../../shared/plugins/contract/v1/README.md#first-line-matching-languages-1).
5189+
contract](../../shared/plugins/contract/v1/README.md#first-line-matching).
51905190

51915191
`plugins.declarative.decodeGrammar` accepts `{ manifest, languageID, grammar }`,
51925192
where `grammar` is the text the host read from the language's `grammar.path`
51935193
inside the installed package, and returns `language: { id, fileExtensions,
5194-
fileNames, grammar: { kind, scopeName, source }, configuration }`. `kind` is
5195-
`textmate`; `source` is the validated original JSON text, byte for byte, which
5196-
the editor's TextMate engine parses and registers under `scopeName`, the
5197-
grammar's own scope. Hosts run plugin grammars only off the editor UI thread,
5194+
fileNames, grammar: { kind, scopeName, source, firstLineMatch? }, configuration }`.
5195+
The editor registers the validated `textmate` JSON `source` byte for byte under
5196+
`scopeName`.
5197+
When present, `firstLineMatch` holds validated optional root-level metadata
5198+
for `languages.matchFirstLine`. Unsupported or malformed hints are omitted.
5199+
Hosts run plugin grammars only off the editor UI thread,
51985200
with bounded backtracking and a time budget per line. A grammar Core
51995201
refuses is `plugin.grammar.invalid` with the failing `field`; a language
52005202
without static editor resources is `plugin.grammar.unavailable`. Configuration-only

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

Lines changed: 45 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ 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");
1820

1921
fn manifest(source: &str) -> Value {
2022
serde_json::from_str(source).expect("fixture manifest is JSON")
@@ -381,72 +383,62 @@ fn configuration_only_contribution_decodes_without_grammar() {
381383
}
382384

383385
#[test]
384-
fn first_line_only_language_requires_a_compatible_manifest_and_host() {
385-
let mut plugin = manifest(contract_file!("fixtures/languages/first-line.plugin.json"));
386-
plugin["languages"][0]
387-
.as_object_mut()
388-
.unwrap()
389-
.remove("configuration");
390-
let validate = |plugin: &Value, versions: &[u32]| {
391-
validate_command(json!({ "manifest": plugin, "hostCapabilities": {"languages": versions} }))
392-
.unwrap()
393-
};
394-
let outcome = validate(&plugin, &[0, 1]);
386+
fn first_line_grammar_uses_the_existing_language_capability() {
387+
let plugin = manifest(FIRST_LINE_PLUGIN);
388+
let admission = validate_command(json!({
389+
"manifest": plugin,
390+
"hostCapabilities": { "languages": [0] },
391+
}))
392+
.unwrap();
393+
assert_eq!(admission["status"], "ok", "{admission}");
394+
let outcome = decode_grammar_command(json!({
395+
"manifest": admission["plugin"],
396+
"languageID": "sample",
397+
"grammar": SAMPLE_GRAMMAR,
398+
}))
399+
.unwrap();
395400
assert_eq!(outcome["status"], "ok", "{outcome}");
401+
let language = &outcome["language"];
402+
assert_eq!(language["fileExtensions"], json!(["sample"]));
403+
assert_eq!(language["configuration"]["lineComment"], "//");
404+
assert_eq!(language["grammar"]["scopeName"], "source.sample");
405+
assert_eq!(language["grammar"]["source"], SAMPLE_GRAMMAR);
396406
assert_eq!(
397-
outcome["plugin"]["languages"][0]["firstLineMatch"],
398-
plugin["languages"][0]["firstLineMatch"]
399-
);
400-
401-
let unsupported = validate(&plugin, &[0]);
402-
assert_eq!(unsupported["status"], "rejected");
403-
assert_eq!(unsupported["error"]["field"], "requires.languages");
404-
let mut downgraded = plugin;
405-
downgraded["requires"]["languages"] = json!(0);
406-
let invalid = validate(&downgraded, &[0, 1]);
407-
assert_eq!(
408-
invalid["error"]["code"], "plugin.manifest.invalid",
409-
"{invalid}"
407+
language["grammar"]["firstLineMatch"],
408+
manifest(SAMPLE_GRAMMAR)["firstLineMatch"]
410409
);
411-
assert_eq!(invalid["error"]["field"], "requires.languages");
412-
413-
let legacy = validate(&manifest(GRAMMAR_PLUGIN), &[0, 1]);
414-
assert_eq!(legacy["status"], "ok", "{legacy}");
415-
assert!(legacy["plugin"]["languages"][0]
416-
.get("firstLineMatch")
417-
.is_none());
418410
}
419411

420412
#[test]
421-
fn first_line_languages_reject_invalid_and_unbounded_patterns_at_installation() {
422-
let mut plugin = manifest(contract_file!("fixtures/languages/first-line.plugin.json"));
413+
fn unsupported_first_line_metadata_keeps_its_grammar() {
423414
for pattern in [
424-
"".into(),
425-
"a*".into(),
426-
"[".into(),
427-
"(a)\\1".into(),
428-
"a{10000000}".into(),
429-
"é".repeat(257),
415+
Value::Null,
416+
json!(42),
417+
json!(""),
418+
json!("a*"),
419+
json!("["),
420+
json!(r"(a)\1"),
421+
json!("a{10000000}"),
422+
json!("é".repeat(257)),
430423
] {
431-
plugin["languages"][0]["firstLineMatch"] = json!(pattern);
432-
let outcome = validate_command(json!({"manifest": plugin})).unwrap();
433-
assert_eq!(
434-
outcome["error"]["field"], "languages[0].firstLineMatch",
435-
"{outcome}"
436-
);
424+
let mut grammar = grammar_with(json!([]));
425+
grammar["firstLineMatch"] = pattern;
426+
let source = grammar.to_string();
427+
let outcome = decode_grammar(&source);
428+
assert_eq!(outcome["status"], "ok", "{outcome}");
429+
let grammar = &outcome["language"]["grammar"];
430+
assert!(!grammar.as_object().unwrap().contains_key("firstLineMatch"));
431+
assert_eq!(grammar["scopeName"], "source.test");
432+
assert_eq!(grammar["source"], source);
437433
}
438-
plugin["languages"][0]["firstLineMatch"] = Value::Null;
439-
assert_eq!(
440-
validate_command(json!({"manifest": plugin})).unwrap()["status"],
441-
"rejected"
442-
);
443434
}
444435

445436
#[test]
446437
fn first_line_matching_keeps_registered_priority_and_never_reads_past_the_line() {
447-
let plugin = manifest(contract_file!("fixtures/languages/first-line.plugin.json"));
448-
let specific =
449-
json!({"languageID":"sample", "firstLineMatch": plugin["languages"][0]["firstLineMatch"]});
438+
let specific = json!({
439+
"languageID": "sample",
440+
"firstLineMatch": manifest(SAMPLE_GRAMMAR)["firstLineMatch"],
441+
});
450442
let generic = json!({"languageID":"other", "firstLineMatch": "#!"});
451443
let choose = |line: &str, candidates: &[Value]| {
452444
let response = lithe_plugin_manifest::match_first_line(

‎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/src/commands.rs‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -185,15 +185,22 @@ pub fn decode_grammar_command(payload: Value) -> Result<Value, CoreError> {
185185
.grammar
186186
.as_ref()
187187
.map(|grammar| match grammar.kind {
188-
// The editor's engine parses the original text; Core only
189-
// proves that it can and names the scope it registers.
190188
lithe_plugin_grammar::GrammarKind::Textmate => {
191-
lithe_plugin_grammar::decode_textmate(&payload.grammar).map(|scope_name| {
192-
json!({
189+
lithe_plugin_grammar::decode_textmate(&payload.grammar).map(|metadata| {
190+
let mut decoded = json!({
193191
"kind": grammar.kind,
194-
"scopeName": scope_name,
192+
"scopeName": metadata.scope_name,
195193
"source": payload.grammar,
196-
})
194+
});
195+
// The optional hint has a different regex dialect
196+
// from the original highlighting source.
197+
if let Some(pattern) = metadata
198+
.first_line_match
199+
.filter(|pattern| crate::first_line::supports_pattern(pattern))
200+
{
201+
decoded["firstLineMatch"] = json!(pattern);
202+
}
203+
decoded
197204
})
198205
}
199206
})

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

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,9 @@ impl LanguageDeclaration {
3434
self.file_extensions = normalized_extensions(&self.file_extensions);
3535
self.file_names = normalized_names(&self.file_names);
3636
self.project_file_names = normalized_names(&self.project_file_names);
37-
if let Some(pattern) = &self.first_line_match {
38-
first_line::validate_pattern(pattern, &format!("{field}.firstLineMatch"))?;
39-
}
4037
if self.file_extensions.is_empty()
4138
&& self.file_names.is_empty()
4239
&& self.project_file_names.is_empty()
43-
&& self.first_line_match.is_none()
4440
{
4541
return Err(invalid(
4642
field,

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

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
//! Bounded, data-only first-line language matching for documents with no path association.
22
3-
use super::{
4-
declarations::is_language_id, decode_payload, invalid, CoreError, ErrorCode, Validation,
5-
};
3+
use super::{declarations::is_language_id, decode_payload, CoreError, ErrorCode};
64
use regex::{Regex, RegexBuilder};
7-
use serde::{Deserialize, Deserializer};
5+
use serde::Deserialize;
86
use serde_json::{json, Value};
97
use std::collections::VecDeque;
108
use std::sync::{Arc, Mutex, OnceLock};
@@ -14,12 +12,7 @@ const MAX_FIRST_LINE_BYTES: usize = 1024;
1412
const MAX_CANDIDATES: usize = 64;
1513
const REGEX_SIZE_LIMIT: usize = 256 * 1024;
1614

17-
/// An omitted declaration is distinct from an explicitly invalid JSON null.
18-
pub(crate) fn present_pattern<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
19-
String::deserialize(d).map(Some)
20-
}
21-
22-
/// Use the same compiled program on manifest acceptance and on repeated document opens.
15+
/// Use the same compiled program in grammar decoding and on repeated document opens.
2316
/// The cache contains only declaration text and programs, never document content.
2417
fn compiled(source: &str) -> Result<Arc<Regex>, &'static str> {
2518
if source.is_empty() || source.len() > MAX_PATTERN_BYTES {
@@ -48,10 +41,9 @@ fn compiled(source: &str) -> Result<Arc<Regex>, &'static str> {
4841
Ok(regex)
4942
}
5043

51-
pub(crate) fn validate_pattern(source: &str, field: &str) -> Validation<()> {
52-
compiled(source)
53-
.map(|_| ())
54-
.map_err(|reason| invalid(field, reason))
44+
/// Whether a grammar hint uses the syntax and budget of the first-line matcher.
45+
pub(crate) fn supports_pattern(source: &str) -> bool {
46+
compiled(source).is_ok()
5547
}
5648

5749
#[derive(Deserialize)]

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

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -230,13 +230,6 @@ pub(crate) struct LanguageDeclaration {
230230
pub(crate) file_names: Vec<String>,
231231
#[serde(default)]
232232
pub(crate) project_file_names: Vec<String>,
233-
/// Optional prefix expression for unassociated extensionless documents (languages 1).
234-
#[serde(
235-
default,
236-
deserialize_with = "crate::first_line::present_pattern",
237-
skip_serializing_if = "Option::is_none"
238-
)]
239-
pub(crate) first_line_match: Option<String>,
240233
#[serde(default, skip_serializing_if = "Option::is_none")]
241234
pub(crate) dependencies: Option<DependencyDeclaration>,
242235
/// Syntax highlighting from a package file; see `lithe_plugin_grammar`.

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

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -141,22 +141,6 @@ impl DeclarativePluginManifest {
141141
"Command test discovery needs buildSystems 1.",
142142
));
143143
}
144-
if self
145-
.languages
146-
.iter()
147-
.any(|language| language.first_line_match.is_some())
148-
&& self
149-
.requires
150-
.get(capabilities::LANGUAGES)
151-
.copied()
152-
.unwrap_or(0)
153-
< 1
154-
{
155-
return Err(invalid(
156-
"requires.languages",
157-
"First-line language matching needs languages 1.",
158-
));
159-
}
160144
if self.tool_definitions.iter().any(|definition| {
161145
definition.get("category").is_some() || definition.get("audience").is_some()
162146
}) && self
@@ -270,11 +254,11 @@ impl DeclarativePluginManifest {
270254
// Console links alone are a complete plugin: Core matches them.
271255
&& self.output_link_matchers.is_empty()
272256
&& self.backend.is_none()
273-
// A static editor contribution can be the entire plugin.
257+
// A grammar alone is a complete highlighting plugin.
274258
&& !self
275259
.languages
276260
.iter()
277-
.any(|language| language.grammar.is_some() || language.configuration.is_some() || language.first_line_match.is_some())
261+
.any(|language| language.grammar.is_some() || language.configuration.is_some())
278262
{
279263
return Err(invalid(
280264
"languages",

‎rust/crates/plugin-model/src/capabilities.rs‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,7 @@ use std::collections::{BTreeMap, BTreeSet};
4242
pub const SUPPORTED_PLUGIN_API_VERSIONS: &[u32] = &[0];
4343

4444
/// `languages[]`: file types and project markers, a TextMate `grammar`, and an
45-
/// editing `configuration`; see `lithe_plugin_grammar`. Version 1 adds the
46-
/// optional `firstLineMatch` pattern for extensionless documents.
45+
/// editing `configuration`; see `lithe_plugin_grammar`.
4746
pub const LANGUAGES: &str = "languages";
4847
/// `languageServers[]`: the launch, `workspaceConfiguration`, and the session
4948
/// fields a plugin backend uses to talk to its own server (`requestMethods`,
@@ -136,7 +135,7 @@ pub const SUPPORTED_CAPABILITIES: &[(&str, &[u32])] = &[
136135
(EXECUTION_PROVIDERS, &[0]),
137136
(KEYMAP_IMPORT_PROVIDERS, &[0]),
138137
(LANGUAGE_SERVERS, &[0]),
139-
(LANGUAGES, &[0, 1]),
138+
(LANGUAGES, &[0]),
140139
(MANAGED_RUNTIMES, &[0, 1]),
141140
(OUTPUT_LINK_MATCHERS, &[0]),
142141
(PACKAGE_TRUST, &[0]),

0 commit comments

Comments
 (0)