Files
lucisv/crates/vfmt_server/tests/grammar.rs
T
lucioandClaude Fable 5 302b3ed443 Hover highlighting 0.4.1: ship a TextMate grammar
Hover cards fence their declaration snippets as systemverilog markdown,
but VS Code colors fences with a TextMate grammar and the extension
deliberately shipped none - so hovers rendered plain. One compact
lookaround-free grammar (comments, strings closing at end of line, based
and fill and real and time literals, directives then macro uses, system
tasks, all 181 keywords generated from vlog_parser::KEYWORDS with a
mutation-checked drift test) registered for both language ids. Buffers
also gain colors before the server starts; semantic tokens still win once
it does. Fence tags are pinned as a contract in hover and completion.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-24 20:15:47 -07:00

178 lines
7.3 KiB
Rust

//! The VS Code extension's TextMate grammar, checked against this workspace.
//!
//! The grammar exists so that fenced code in the server's markdown — hover
//! cards, completion documentation — renders highlighted: VS Code colours a
//! ```` ```systemverilog ```` block with the TextMate grammar registered for
//! that language id, and semantic tokens cannot reach markdown. Its keyword
//! list is *generated from* [`vlog_parser::KEYWORDS`], so the two can drift
//! apart the moment somebody adds a keyword and forgets the JSON. That is what
//! `the_grammars_keywords_are_exactly_the_lexers` is here to prevent.
//!
//! There is no regex engine in this workspace's dependency tree and adding one
//! for a test is not worth it, so `every_pattern_is_a_plain_regex` checks the
//! properties that actually matter instead of compiling: balanced groups and
//! classes, and no lookaround/backreference — i.e. every pattern stays inside
//! the subset every engine accepts, Oniguruma included. The patterns were also
//! hand-run against a sample buffer while the grammar was written; see
//! `docs/features/editor-packaging/README.md`.
use std::path::PathBuf;
use serde_json::Value;
/// The grammar, parsed. Located relative to this crate, so the test is
/// independent of the working directory `cargo test` was started from.
fn grammar() -> Value {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../editors/vscode/syntaxes/systemverilog.tmLanguage.json");
let text = std::fs::read_to_string(&path)
.unwrap_or_else(|e| panic!("reading {}: {e}", path.display()));
serde_json::from_str(&text).unwrap_or_else(|e| panic!("parsing {}: {e}", path.display()))
}
/// The extension manifest, parsed.
fn manifest() -> Value {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../editors/vscode/package.json");
let text = std::fs::read_to_string(&path)
.unwrap_or_else(|e| panic!("reading {}: {e}", path.display()));
serde_json::from_str(&text).unwrap_or_else(|e| panic!("parsing {}: {e}", path.display()))
}
/// Every `match`, `begin` and `end` string anywhere in the grammar.
fn patterns(node: &Value, path: &str, out: &mut Vec<(String, String)>) {
match node {
Value::Object(map) => {
for (key, value) in map {
match (key.as_str(), value.as_str()) {
("match" | "begin" | "end", Some(regex)) => {
out.push((format!("{path}.{key}"), regex.to_string()))
}
_ => patterns(value, &format!("{path}.{key}"), out),
}
}
}
Value::Array(items) => {
for (i, item) in items.iter().enumerate() {
patterns(item, &format!("{path}[{i}]"), out);
}
}
_ => {}
}
}
#[test]
fn the_grammars_keywords_are_exactly_the_lexers() {
let grammar = grammar();
let alternation = grammar["repository"]["keywords"]["match"]
.as_str()
.expect("repository.keywords.match is a string");
let inner = alternation
.strip_prefix("\\b(")
.and_then(|rest| rest.strip_suffix(")\\b"))
.unwrap_or_else(|| panic!("the keyword rule must be `\\b(a|b|…)\\b`, got {alternation}"));
let mut listed: Vec<&str> = inner.split('|').collect();
let mut expected: Vec<&str> = vlog_parser::KEYWORDS.to_vec();
listed.sort_unstable();
expected.sort_unstable();
let mut deduped = listed.clone();
deduped.dedup();
assert_eq!(listed, deduped, "a keyword is listed twice in the grammar");
// The two differences, named, because "assert_eq on 181 words" is not a
// useful failure message.
let missing: Vec<&&str> = expected.iter().filter(|w| !listed.contains(w)).collect();
let extra: Vec<&&str> = listed.iter().filter(|w| !expected.contains(w)).collect();
assert!(
missing.is_empty() && extra.is_empty(),
"editors/vscode/syntaxes/systemverilog.tmLanguage.json has drifted from \
vlog_parser::KEYWORDS — regenerate the alternation.\n missing: {missing:?}\n \
extra: {extra:?}"
);
assert_eq!(listed, expected);
}
#[test]
fn every_pattern_is_a_plain_regex() {
let grammar = grammar();
let mut found = Vec::new();
patterns(&grammar, "", &mut found);
assert!(found.len() >= 10, "the grammar lost its patterns: {found:?}");
for (where_, regex) in &found {
assert!(!regex.is_empty(), "{where_} is an empty pattern");
for construct in ["(?=", "(?!", "(?<", "(?>", "\\1", "\\k<", "\\G"] {
assert!(
!regex.contains(construct),
"{where_} uses `{construct}` — the grammar deliberately stays inside the \
regex subset every engine accepts; see this file's header"
);
}
assert!(balanced(regex), "{where_} has unbalanced `()` or `[]`: {regex}");
}
}
/// Whether a regex's groups and character classes are balanced, reading
/// backslash escapes and treating `(`/`)` inside a class as literal — the one
/// structural error that turns a grammar into "no highlighting at all".
fn balanced(regex: &str) -> bool {
let mut depth = 0i32;
let mut in_class = false;
let mut chars = regex.chars();
while let Some(ch) = chars.next() {
match ch {
'\\' => {
if chars.next().is_none() {
return false; // a trailing backslash escapes nothing
}
}
'[' if !in_class => in_class = true,
']' if in_class => in_class = false,
'(' if !in_class => depth += 1,
')' if !in_class => {
depth -= 1;
if depth < 0 {
return false;
}
}
_ => {}
}
}
depth == 0 && !in_class
}
#[test]
fn both_language_ids_are_registered_for_the_grammar() {
// The hover cards fence unconditionally as ```systemverilog, and VS Code
// resolves a fence's info string against the language registry — not
// against the document the hover came from. So a `.v` buffer's hover
// highlights only because `verilog` is registered here too.
let manifest = manifest();
let scope = grammar()["scopeName"].as_str().expect("scopeName").to_string();
let grammars = manifest["contributes"]["grammars"].as_array().expect("contributes.grammars");
let languages: Vec<&str> = grammars.iter().filter_map(|g| g["language"].as_str()).collect();
assert_eq!(languages, ["verilog", "systemverilog"]);
for entry in grammars {
assert_eq!(entry["scopeName"].as_str(), Some(scope.as_str()));
assert_eq!(
entry["path"].as_str(),
Some("./syntaxes/systemverilog.tmLanguage.json"),
"both entries must name the same file: VS Code only warns about a re-registered \
scope when the two locations differ"
);
}
// Every id the grammar claims is an id the extension actually declares.
let declared: Vec<&str> = manifest["contributes"]["languages"]
.as_array()
.expect("contributes.languages")
.iter()
.filter_map(|l| l["id"].as_str())
.collect();
for language in &languages {
assert!(declared.contains(language), "grammar registered for undeclared id {language}");
}
}