Compare commits

...
2 Commits
Author SHA1 Message Date
lucio 464929262b Release 0.65.0: module instantiation syntax highlighting
release / build-and-publish (push) Successful in 3m40s
ci / corpus (push) Successful in 21s
ci / checks (push) Failing after 10s
Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.0) and
editors/vscode/CHANGELOG.md. TODO §69.
Gates: no local cargo/tools/gates.sh run on this Windows host (the release
relies on Gitea CI). Locally: all 10 VS Code extension node tests pass
(including the new semanticTokens_test.js, 75 checks).
2026-11-19 02:40:10 -08:00
lucio e4db0ac1fc TODO §69: colour module instantiations by role, with # matching parameters
Add AST-guided semantic token overrides in lucisv_server/src/tokens/instantiation.rs
and cross-file overlay lookup in tokens.rs without changing the 14-type wire legend:
- module/interface/extends names -> class (pkg:: prefixes -> namespace)
- parameter-list # (never delays), .PARAM overrides and parameter values -> parameter
- instance names (declarations, gate instances, bind lists, hierarchical uses) -> function
- named port connections (.port, implicit .port, .*) -> property
- port connection signals -> variable

Enable editor.semanticHighlighting.enabled by default for [verilog] and
[systemverilog] in editors/vscode/package.json and contribute semanticTokenScopes
so every role renders with a distinct, non-white colour across VS Code themes.
Add editors/vscode/semanticTokens_test.js (75 checks, passing under node --test).
Rust tests/fmt/clippy deferred to Gitea CI (no cargo toolchain on this Windows host).
2026-11-19 02:38:42 -08:00
15 changed files with 962 additions and 63 deletions

No files matched your search

+32
View File
@@ -4,6 +4,38 @@ All notable changes to lucisv are recorded here. Versions follow
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
(see `README.md`) are the only frozen contract.
## 0.65.0 — 2026-11-19
### Module instantiation syntax highlighting
(`docs/features/instantiation-highlighting`; TODO §69.)
- **Every part of a module instantiation gets its own colour.** Module names,
instance names, `.PARAM` overrides, `.port` names and connected signals used
to collapse to the same default foreground colour whenever the instantiated
module lived in another file or a theme left bare semantic tokens unstyled.
The language server now layers AST-guided semantic token overrides (and
cross-file `ExternalResolutions` lookups) over the existing 14-type legend:
- **Module / interface names** (`uart_core`, `pkg::uart_core` with `pkg` as
`namespace`, and lone `bind` targets) highlight as `class`.
- **`#` and parameters share one colour** (`parameter`), distinct from `()`:
the `#` introducing a module, class, `extends`, instantiation or
parameterized-type parameter list, every `.PARAM` override (`.` and name),
and parameter values inside `#(...)` all carry `parameter`. Delay `#`
tokens (`#5`, `#(1:2:3)`) are left unemitted.
- **Instance names** (`u_uart`, gate instances, `bind` instance lists, and
hierarchical uses like `u_uart.sig`) highlight as `function`.
- **Port names** (`.clk_i` dot and name, implicit `.rst_ni`, and wildcard
`.*`), including unfinished entries being typed, highlight as `property`.
- **Port connections** (`clk`, `data_q`) stay `variable` so signals keep one
consistent colour across the file.
- **VS Code: semantic highlighting on by default with theme-safe scope maps.**
`configurationDefaults` enables `editor.semanticHighlighting.enabled` for
`[verilog]` and `[systemverilog]` (user settings still win), and
`contributes.semanticTokenScopes` maps the language's semantic token types to
distinct TextMate scopes so every role renders in colour across Dark+, Dark
Modern, Light+, GitHub Dark, One Dark Pro and Visual Studio Dark.
## 0.64.0 — 2026-11-17
### Completion that keeps up with typing
Generated
+9 -9
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.64.0"
version = "0.65.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.64.0"
version = "0.65.0"
[[package]]
name = "lucisv_mcp"
version = "0.64.0"
version = "0.65.0"
dependencies = [
"lucisv_core",
"serde",
@@ -126,7 +126,7 @@ dependencies = [
[[package]]
name = "lucisv_server"
version = "0.64.0"
version = "0.65.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.64.0"
version = "0.65.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.64.0"
version = "0.65.0"
dependencies = [
"lucisv_core",
"vlog_formatter",
@@ -279,11 +279,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.64.0"
version = "0.65.0"
[[package]]
name = "vlog_refactor"
version = "0.64.0"
version = "0.65.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -292,7 +292,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.64.0"
version = "0.65.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -13,7 +13,7 @@ members = [
]
[workspace.package]
version = "0.64.0"
version = "0.65.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+16
View File
@@ -7247,3 +7247,19 @@ Feature README: `docs/features/port-entry-grace/README.md`. Files:
- [x] The server withholds the diagnostics that fall inside the entry the
last edit touched, and releases them after a quiet period or when the
next edit lands elsewhere.
## 69. Module instantiation syntax highlighting (2026-11-17, owner's order)
Feature README: `docs/features/instantiation-highlighting/README.md`. Files:
`crates/lucisv_server/src/{tokens.rs,tokens/instantiation.rs}`,
`editors/vscode/{package.json,.vscodeignore,semanticTokens_test.js}`,
`docs/features/{lucisv-server,large-file-mode}/README.md`.
- [x] Distinct semantic highlights across module instantiations (14-type wire
legend unchanged): module name (`class`), `#` + `.PARAM` overrides +
parameter values (`parameter`, distinct from `()`), instance name
(`function`), `.port`/`.*` (`property`), and port connections
(`variable`), including unfinished entries while typing.
- [x] `configurationDefaults` enables `editor.semanticHighlighting.enabled` and
`semanticTokenScopes` maps `verilog`/`systemverilog` roles to distinct,
non-white TextMate scopes across themes.
+197 -30
View File
@@ -1,24 +1,30 @@
//! `textDocument/semanticTokens/full`, `/range` and `/full/delta`.
//!
//! Classification comes from the lexer's token stream, refined for plain
//! identifiers by `vlog_semantic`. The full mapping table is in
//! `docs/features/lucisv-server/README.md`; the range and delta rules are in
//! `docs/features/semantic-tokens-delta/README.md`.
//! identifiers by `vlog_semantic` + `ExternalResolutions` and for module
//! instantiations / `#(...)` parameter lists by `Document.tree`
//! (`docs/features/instantiation-highlighting/README.md`). The full mapping
//! table is in `docs/features/lucisv-server/README.md`; the range and delta
//! rules are in `docs/features/semantic-tokens-delta/README.md`.
//!
//! One tokenizer and one encoder serve all three requests: classification
//! produces [`Absolute`] tokens (line, column, length — the coordinates the
//! protocol thinks in), a range answer drops the ones it does not want, and
//! `encode` delta-encodes whatever is left from the start of the document.
use std::collections::HashMap;
use lsp_types::{
Position, Range, SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokensEdit,
};
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::TextRange;
use vlog_semantic::{Semantics, SymbolKind};
use vlog_semantic::{Definition, ExternalResolutions, Semantics, SymbolKind};
use crate::state::Document;
mod instantiation;
/// The legend the server advertises. The index into this array is what the
/// wire format carries, so the order is part of the protocol contract and
/// must match [`Highlight`].
@@ -133,6 +139,7 @@ pub fn semantic_tokens_in_range(doc: &Document, range: Range) -> Vec<SemanticTok
/// See `docs/features/large-file-mode/README.md`.
pub fn semantic_tokens_in_window(doc: &Document, range: Range) -> Vec<SemanticToken> {
let window = crate::large::window(doc, range);
let overrides = HashMap::new();
let mut pieces = Vec::new();
// The comment spans the lexer never saw go in first; `flatten` sorts, so
// the order they are collected in cannot reach the wire.
@@ -140,16 +147,17 @@ pub fn semantic_tokens_in_window(doc: &Document, range: Range) -> Vec<SemanticTo
pieces.push(Piece { span: *span, ty: Highlight::Comment, modifiers: 0 });
}
for token in &window.tokens {
collect(token, &doc.semantics, &mut pieces);
collect(token, doc, &overrides, &mut pieces);
}
encode(&within(flatten(pieces, doc), range))
}
/// Classify the whole buffer, split at line boundaries, in wire order.
fn absolute(doc: &Document) -> Vec<Absolute> {
let overrides = instantiation::overrides(doc);
let mut pieces = Vec::new();
for token in &doc.tokens {
collect(token, &doc.semantics, &mut pieces);
collect(token, doc, &overrides, &mut pieces);
}
flatten(pieces, doc)
}
@@ -177,12 +185,17 @@ fn within(tokens: Vec<Absolute>, range: Range) -> Vec<Absolute> {
/// after it on the same line — because [`flatten`] converts the offsets with a
/// single forward cursor. Ordering is otherwise invisible: `flatten` sorts,
/// and no two pieces here can start at the same byte.
fn collect(token: &Token, semantics: &Semantics, out: &mut Vec<Piece>) {
fn collect(
token: &Token,
doc: &Document,
overrides: &HashMap<u32, Highlight>,
out: &mut Vec<Piece>,
) {
for comment in &token.leading {
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
}
if let Some(ty) = classify(token, semantics) {
out.push(Piece { span: token.span, ty, modifiers: modifiers(token, semantics) });
if let Some(ty) = classify(token, doc, overrides) {
out.push(Piece { span: token.span, ty, modifiers: modifiers(token, &doc.semantics) });
}
if let Some(comment) = &token.trailing {
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
@@ -190,7 +203,14 @@ fn collect(token: &Token, semantics: &Semantics, out: &mut Vec<Piece>) {
}
/// What a token is, or `None` for the ones this server does not colour.
fn classify(token: &Token, semantics: &Semantics) -> Option<Highlight> {
fn classify(
token: &Token,
doc: &Document,
overrides: &HashMap<u32, Highlight>,
) -> Option<Highlight> {
if let Some(&ty) = overrides.get(&token.span.start) {
return Some(ty);
}
match token.kind {
TokenKind::Keyword => Some(Highlight::Keyword),
TokenKind::Number => Some(Highlight::Number),
@@ -201,8 +221,8 @@ fn classify(token: &Token, semantics: &Semantics) -> Option<Highlight> {
// A macro *usage* lexes as an identifier whose text starts with a
// backtick; `is_macro` is the lexer's own public test for it.
TokenKind::Ident if token.is_macro() => Some(Highlight::Macro),
TokenKind::Ident => Some(identifier_type(token.span.start, semantics)),
// Punctuation: deliberately not emitted, see the feature README.
TokenKind::Ident => Some(identifier_type(token.span.start, &doc.semantics, &doc.external)),
// Punctuation outside `overrides`: deliberately not emitted, see the feature README.
TokenKind::Symbol | TokenKind::Eof => None,
}
}
@@ -219,16 +239,28 @@ fn modifiers(token: &Token, semantics: &Semantics) -> u32 {
}
}
/// A plain identifier, classified through the symbol table: its own
/// declaration, the declaration it resolves to, or `variable` when nothing in
/// this file knows (an external candidate, or a name a macro would produce).
fn identifier_type(offset: u32, semantics: &Semantics) -> Highlight {
let symbol = semantics
.symbol_at(offset)
.or_else(|| semantics.reference_at(offset).and_then(|r| r.resolved()))
.and_then(|id| semantics.symbol(id));
match symbol {
Some(symbol) => symbol_type(symbol.kind),
/// What symbol kind `offset` resolves to across the file and workspace overlay.
fn resolved_kind(
offset: u32,
semantics: &Semantics,
external: &ExternalResolutions,
) -> Option<SymbolKind> {
match external.definition_of(semantics, offset)? {
Definition::Local(symbol) => Some(symbol.kind),
Definition::External(defs) => defs.first().map(|def| def.kind),
}
}
/// A plain identifier, classified through the symbol table and workspace
/// overlay: its own declaration, the declaration it resolves to, or `variable`
/// when nothing resolves it.
fn identifier_type(
offset: u32,
semantics: &Semantics,
external: &ExternalResolutions,
) -> Highlight {
match resolved_kind(offset, semantics, external) {
Some(kind) => symbol_type(kind),
None => Highlight::Variable,
}
}
@@ -248,7 +280,7 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
SymbolKind::Typedef => Highlight::Type,
SymbolKind::EnumVariant => Highlight::EnumMember,
SymbolKind::Param | SymbolKind::LocalParam | SymbolKind::TfArg => Highlight::Parameter,
SymbolKind::Function | SymbolKind::Task => Highlight::Function,
SymbolKind::Function | SymbolKind::Task | SymbolKind::Instance => Highlight::Function,
SymbolKind::StructMember
| SymbolKind::Constraint
| SymbolKind::Coverpoint
@@ -260,7 +292,6 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
| SymbolKind::Net
| SymbolKind::Var
| SymbolKind::Genvar
| SymbolKind::Instance
| SymbolKind::Clocking
| SymbolKind::Block => Highlight::Variable,
// A property and a sequence are named, instantiated by name and take
@@ -728,9 +759,19 @@ mod tests {
}
}
/// Decoded tokens with the identifier refinement folded away.
fn coarsely(data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32)> {
decode(data).into_iter().map(|(l, c, len, ty, _)| (l, c, len, coarse(ty))).collect()
/// Decoded tokens with identifier refinement and AST-only punctuation
/// (`#`, `.`, `*`) folded away so the unparsed window lexer can be compared
/// against the full pipeline.
fn coarsely(full: &Document, data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32)> {
let positions = full.positions();
decode(data)
.into_iter()
.filter(|&(line, character, ..)| {
let at = positions.offset(Position { line, character });
!full.token_at(at).is_some_and(|t| t.kind == TokenKind::Symbol)
})
.map(|(l, c, len, ty, _)| (l, c, len, coarse(ty)))
.collect()
}
/// Whether any construct in `doc` crosses `offset` — a block comment, a
@@ -792,8 +833,8 @@ mod tests {
continue;
}
assert_eq!(
coarsely(&semantic_tokens_in_window(&fast, window)),
coarsely(&semantic_tokens_in_range(&full, window)),
coarsely(&full, &semantic_tokens_in_window(&fast, window)),
coarsely(&full, &semantic_tokens_in_range(&full, window)),
"{}: lines {from}..{to}",
path.display()
);
@@ -889,7 +930,8 @@ mod tests {
// Punctuation (`,`, `;`) is deliberately not classified at all, so it
// never reaches `pieces` — only the tokens `classify` keeps are
// expected on the wire.
for token in window.tokens.iter().filter(|t| classify(t, &doc.semantics).is_some()) {
let empty = HashMap::new();
for token in window.tokens.iter().filter(|t| classify(t, &doc, &empty).is_some()) {
let expected = positions.position(token.span.start);
let found = decoded
.iter()
@@ -1291,4 +1333,129 @@ mod tests {
let data = ranged(FOUR_LINES, range((3, 0), (1, 0)));
assert!(decode(&data).is_empty(), "{:?}", decode(&data));
}
// ------------------------------------------------------------------
// module instantiation and `#(...)` parameter-list highlighting
// ------------------------------------------------------------------
fn named_tokens(text: &str) -> Vec<(String, u32, u32)> {
with_document(text, |doc| {
let pos = doc.positions();
decode(&semantic_tokens(doc))
.into_iter()
.map(|(line, character, len, ty, mods)| {
let start = pos.offset(Position { line, character }) as usize;
let end = pos.offset(Position { line, character: character + len }) as usize;
(doc.text[start..end].to_string(), ty, mods)
})
.collect()
})
}
#[test]
fn module_instantiation_distinguishes_module_params_instance_ports_and_connections() {
let src = "\
module top #(
parameter int DATA_W = 32
) (
input logic clk,
input logic rst_ni
);
logic [DATA_W-1:0] data_q;
pkg::uart_core #(
.BAUD_DIV (EXT_DIV),
.WIDTH (DATA_W),
.DEPTH (16)
) u_uart (
.clk_i (clk),
.rst_ni,
.data_o (data_q),
.*
);
assign data_q = u_uart.tx_data;
endmodule
";
let out = named_tokens(src);
let find_nth = |word: &str, n: usize| {
out.iter()
.filter(|(w, ..)| w == word)
.nth(n)
.cloned()
.unwrap_or_else(|| panic!("{word} #{n} missing in {out:?}"))
};
// Both `#` tokens (header parameter port list and instantiation overrides)
// share `Parameter`, while `(` and `)` are never emitted.
assert_eq!(find_nth("#", 0), ("#".into(), Highlight::Parameter as u32, 0));
assert_eq!(find_nth("#", 1), ("#".into(), Highlight::Parameter as u32, 0));
assert!(!out.iter().any(|(w, ..)| w == "(" || w == ")"));
// Scoped module name: `pkg` is Namespace, `uart_core` is Class.
assert_eq!(find_nth("pkg", 0), ("pkg".into(), Highlight::Namespace as u32, 0));
assert_eq!(find_nth("uart_core", 0), ("uart_core".into(), Highlight::Class as u32, 0));
// Parameter overrides: `.` and parameter names share `Parameter` with `#`,
// as do local (`DATA_W`) and external (`EXT_DIV`) parameter values; `16` stays Number.
assert_eq!(find_nth(".", 0), (".".into(), Highlight::Parameter as u32, 0));
assert_eq!(find_nth("BAUD_DIV", 0), ("BAUD_DIV".into(), Highlight::Parameter as u32, 0));
assert_eq!(find_nth("EXT_DIV", 0), ("EXT_DIV".into(), Highlight::Parameter as u32, 0));
assert_eq!(find_nth(".", 1), (".".into(), Highlight::Parameter as u32, 0));
assert_eq!(find_nth("WIDTH", 0), ("WIDTH".into(), Highlight::Parameter as u32, 0));
assert_eq!(find_nth("DATA_W", 2), ("DATA_W".into(), Highlight::Parameter as u32, 0));
assert_eq!(find_nth("16", 0), ("16".into(), Highlight::Number as u32, 0));
// Instance declaration and hierarchical use both highlight as `Function`.
let fn_ty = Highlight::Function as u32;
assert_eq!(find_nth("u_uart", 0), ("u_uart".into(), fn_ty, DECLARATION));
assert_eq!(find_nth("u_uart", 1), ("u_uart".into(), fn_ty, 0));
// Port names (`.clk_i`, implicit `.rst_ni`, `.data_o`, wildcard `.*`) are `Property`,
// while connected signals (`clk`, `data_q`) stay `Variable`.
assert_eq!(find_nth(".", 3), (".".into(), Highlight::Property as u32, 0));
assert_eq!(find_nth("clk_i", 0), ("clk_i".into(), Highlight::Property as u32, 0));
assert_eq!(find_nth("clk", 1), ("clk".into(), Highlight::Variable as u32, 0));
assert_eq!(find_nth("rst_ni", 1), ("rst_ni".into(), Highlight::Property as u32, 0));
assert_eq!(find_nth("data_o", 0), ("data_o".into(), Highlight::Property as u32, 0));
assert_eq!(find_nth("data_q", 1), ("data_q".into(), Highlight::Variable as u32, 0));
assert_eq!(find_nth("*", 0), ("*".into(), Highlight::Property as u32, 0));
}
#[test]
fn delay_hashes_are_never_classified_as_parameters() {
let src = "\
module m;
wire #5 a;
assign #(1:2:3) a = 1'b0;
and #(2, 3) g0 (y, a, a);
initial #10 $finish;
endmodule
";
let out = named_tokens(src);
assert!(!out.iter().any(|(w, ..)| w == "#"), "delays keep `#` unemitted: {out:?}");
assert!(out.contains(&("g0".into(), Highlight::Function as u32, DECLARATION)));
}
#[test]
fn unfinished_port_and_param_entries_keep_their_highlights_while_typing() {
let src = "\
module m;
sub #(
.WIDTH(
) u0 (
.clk_i(
.rst_ni(rst_n)
);
endmodule
";
let out = named_tokens(src);
assert!(out.contains(&("sub".into(), Highlight::Class as u32, 0)));
assert!(out.contains(&("#".into(), Highlight::Parameter as u32, 0)));
assert!(out.contains(&("WIDTH".into(), Highlight::Parameter as u32, 0)));
assert!(out.contains(&("u0".into(), Highlight::Function as u32, DECLARATION)));
assert!(out.contains(&("clk_i".into(), Highlight::Property as u32, 0)));
assert!(out.contains(&("rst_ni".into(), Highlight::Property as u32, 0)));
assert!(out.contains(&("rst_n".into(), Highlight::Variable as u32, 0)));
reconstructs(MODULE, src);
reconstructs(src, MODULE);
}
}
@@ -0,0 +1,313 @@
//! AST-guided semantic token overrides for module instantiations and `#(...)`
//! parameter lists.
//!
//! Plain lexical + symbol-table classification leaves an external module's
//! name, its `#` parameter sigil, its `.PARAM` overrides and its `.port`
//! connections as uncoloured punctuation or generic `variable`s. Walking
//! [`Document::tree`] supplies the syntactic role of each token directly from
//! the parsed AST, even before workspace indexing finishes or when the
//! instantiated unit lives outside the indexed tree.
use std::collections::HashMap;
use vlog_parser::ast::{
BindDirective, ClassDecl, ClassExtends, Connection, Connections, DataType, Expr,
GateInstantiation, GenElse, Instantiation, Item, ItemKind, ListElem, Module, PortList, RawText,
Typedef, TypedefKind,
};
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::TextRange;
use vlog_semantic::{ExternalResolutions, Semantics, SymbolKind};
use super::{resolved_kind, Highlight};
use crate::state::{first_token_from, Document};
/// Token-start byte offset -> highlight overrides derived from `doc.tree`.
pub(super) fn overrides(doc: &Document) -> HashMap<u32, Highlight> {
let mut out = HashMap::new();
if doc.tokens.is_empty() {
return out;
}
let mut ctx = Ctx {
tokens: &doc.tokens,
semantics: &doc.semantics,
external: &doc.external,
out: &mut out,
};
ctx.items(&doc.tree.items);
out
}
struct Ctx<'a> {
tokens: &'a [Token],
semantics: &'a Semantics,
external: &'a ExternalResolutions,
out: &'a mut HashMap<u32, Highlight>,
}
impl<'a> Ctx<'a> {
fn items(&mut self, items: &[Item]) {
for item in items {
self.item(item);
}
}
fn item(&mut self, item: &Item) {
match &item.kind {
ItemKind::Module(m) => self.module(m, item.span.end),
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
self.items(items)
}
ItemKind::Class(c) => self.class(c, item.span.end),
ItemKind::Instantiation(inst) => self.instantiation(inst, item.span.end),
ItemKind::Bind(bind) => self.bind(bind, item.span.end),
ItemKind::GateInstantiation(gate) => self.gate(gate),
ItemKind::GenBlock(b) => self.items(&b.items),
ItemKind::GenIf(g) => {
self.items(&g.then.items);
self.gen_else(g.els.as_deref());
}
ItemKind::GenFor(g) => self.items(&g.body.items),
ItemKind::GenCase(g) => {
for arm in &g.items {
self.items(&arm.body.items);
}
}
ItemKind::DataDecl(d) => self.data_type(&d.ty),
ItemKind::PortDecl(p) => self.data_type(&p.ty),
ItemKind::ParamDecl(p) => self.data_type(&p.ty),
ItemKind::Typedef(t) => self.typedef(t),
_ => {}
}
}
fn gen_else(&mut self, els: Option<&GenElse>) {
match els {
Some(GenElse::If(_, inner)) => {
self.items(&inner.then.items);
self.gen_else(inner.els.as_deref());
}
Some(GenElse::Block(block)) => self.items(&block.items),
None => {}
}
}
fn module(&mut self, m: &Module, end: u32) {
if m.param_ports.is_some() {
let last = m.imports.last().and_then(|imp| imp.paths.last());
let from = last.map_or(m.name_span.end, |p| p.item.span.end);
self.param_hash(from, end);
}
for elem in m.param_ports.iter().flatten() {
if let Some(port) = elem.ok() {
self.data_type(&port.ty);
}
}
if let PortList::Ansi(ports) = &m.ports {
for elem in ports {
if let Some(port) = elem.ok() {
self.data_type(&port.ty);
}
}
}
self.items(&m.items);
}
fn class(&mut self, c: &ClassDecl, end: u32) {
if c.param_ports.is_some() {
self.param_hash(c.name_span.end, end);
for elem in c.param_ports.iter().flatten() {
if let Some(port) = elem.ok() {
self.data_type(&port.ty);
}
}
}
if let Some(ext) = &c.extends {
self.class_extends(ext);
}
self.items(&c.items);
}
fn class_extends(&mut self, ext: &ClassExtends) {
self.scoped_unit(ext.name_span);
if let Some(params) = &ext.params {
self.param_hash(ext.name_span.end, ext.span.end);
self.param_overrides(params);
}
}
fn typedef(&mut self, t: &Typedef) {
if let TypedefKind::Alias(ty) = &t.kind {
self.data_type(ty);
}
}
fn data_type(&mut self, ty: &DataType) {
if let Some(params) = ty.params() {
self.param_hash(params.span.start, params.span.end);
}
}
fn instantiation(&mut self, inst: &Instantiation, end: u32) {
self.scoped_unit(inst.module_span);
if let Some(params) = &inst.params {
self.param_hash(inst.module_span.end, end);
self.param_overrides(params);
}
for instance in &inst.instances {
self.ident_at(instance.name_span, Highlight::Function);
self.port_connections(&instance.conns);
}
}
fn bind(&mut self, b: &BindDirective, end: u32) {
if let [only] = &b.target[..] {
let kind = resolved_kind(only.span.start, self.semantics, self.external);
if only.index.is_none() && kind != Some(SymbolKind::Instance) {
self.ident_at(only.span, Highlight::Class);
}
}
for inst in &b.instances {
self.ident_at(inst.span, Highlight::Function);
}
self.instantiation(&b.inst, end);
}
fn gate(&mut self, g: &GateInstantiation) {
for inst in &g.instances {
if let Some(span) = inst.name_span {
self.ident_at(span, Highlight::Function);
}
}
}
fn param_overrides(&mut self, params: &[ListElem<Connection>]) {
for elem in params {
match elem {
ListElem::Ok(conn) => {
self.named_entry(conn, Highlight::Parameter);
if let Some(expr) = &conn.expr {
self.param_expr(expr);
}
}
ListElem::Error(raw) => self.recovered_entry(raw, Highlight::Parameter),
}
}
}
fn port_connections(&mut self, conns: &Connections) {
let Connections::Named(list) = conns else { return };
for elem in list {
match elem {
ListElem::Ok(conn) => self.named_entry(conn, Highlight::Property),
ListElem::Error(raw) => self.recovered_entry(raw, Highlight::Property),
}
}
}
fn named_entry(&mut self, conn: &Connection, ty: Highlight) {
if conn.name_span.is_empty() {
return;
}
for tok in self.tokens_in(TextRange::new(conn.span.start, conn.name_span.start)) {
if tok.is_sym(".") {
self.out.insert(tok.span.start, ty);
}
}
for tok in self.tokens_in(conn.name_span) {
if (tok.kind == TokenKind::Ident && !tok.is_macro()) || tok.is_sym("*") {
self.out.insert(tok.span.start, ty);
}
}
}
fn recovered_entry(&mut self, raw: &RawText, ty: Highlight) {
let mut saw_dot = false;
for tok in self.tokens_in(raw.span) {
if tok.kind == TokenKind::Attribute {
continue;
}
if !saw_dot && tok.is_sym(".") {
self.out.insert(tok.span.start, ty);
saw_dot = true;
continue;
}
if saw_dot && ((tok.kind == TokenKind::Ident && !tok.is_macro()) || tok.is_sym("*")) {
self.out.insert(tok.span.start, ty);
}
break;
}
}
fn param_expr(&mut self, expr: &Expr) {
if expr.span.is_empty() {
return;
}
let start = first_token_from(self.tokens, expr.span.start);
let slice = self.tokens.get(start..).unwrap_or(&[]);
let len = slice.partition_point(|t| t.span.end <= expr.span.end);
for (idx, tok) in slice[..len].iter().enumerate() {
if tok.kind != TokenKind::Ident || tok.is_macro() {
continue;
}
if resolved_kind(tok.span.start, self.semantics, self.external).is_some() {
continue;
}
let abs = start + idx;
let next = self.tokens.get(abs + 1);
let prev = abs.checked_sub(1).and_then(|i| self.tokens.get(i));
let ty = if next.is_some_and(|t| t.is_sym("::")) {
Highlight::Namespace
} else if next.is_some_and(|t| t.is_sym("(")) && !prev.is_some_and(|t| t.is_sym(".")) {
Highlight::Function
} else {
Highlight::Parameter
};
self.out.insert(tok.span.start, ty);
}
}
fn scoped_unit(&mut self, span: TextRange) {
let idents: Vec<&Token> = self
.tokens_in(span)
.iter()
.filter(|t| t.kind == TokenKind::Ident && !t.is_macro())
.collect();
let Some((&last, prefix)) = idents.split_last() else { return };
for &seg in prefix {
self.out.insert(seg.span.start, Highlight::Namespace);
}
self.out.insert(last.span.start, Highlight::Class);
}
fn ident_at(&mut self, span: TextRange, ty: Highlight) {
for tok in self.tokens_in(span) {
if tok.kind == TokenKind::Ident && !tok.is_macro() {
self.out.insert(tok.span.start, ty);
}
}
}
fn param_hash(&mut self, from: u32, until: u32) {
let start = first_token_from(self.tokens, from);
for tok in self.tokens.get(start..).unwrap_or(&[]) {
if tok.span.start >= until || tok.is_sym("(") || tok.is_sym(";") {
break;
}
if tok.is_sym("#") {
self.out.insert(tok.span.start, Highlight::Parameter);
break;
}
}
}
fn tokens_in(&self, span: TextRange) -> &'a [Token] {
if span.is_empty() {
return &[];
}
let start = first_token_from(self.tokens, span.start);
let slice = self.tokens.get(start..).unwrap_or(&[]);
let len = slice.partition_point(|t| t.span.end <= span.end);
&slice[..len]
}
}
@@ -0,0 +1,126 @@
# instantiation-highlighting
## Goal
Give module and interface instantiations distinct, recognizable syntax colours
instead of painting every part of an instantiation with the default variable
foreground. Borrowing the roles other languages assign to constructor and
component calls (C++, Rust, TypeScript/JSX), each syntactic piece of an
instantiation takes its own semantic token class and theme-safe TextMate scope:
1. **Module / interface name** (`uart_core` in `uart_core #(...) u_uart (...)`,
`pkg::uart_core` with `pkg` as `namespace`, and lone `bind` targets) →
`class` (`entity.name.type.class`).
2. **`#` sign and parameters** (`#` before parameter port or override lists,
`.BAUD_DIV` dot + parameter-port name, `parameter`/`localparam` symbols, and
unresolved constant identifiers inside `#(...)`) → `parameter`
(`keyword.control` / `constant.language` / `variable.parameter`), sharing
one colour that stays distinct from bracket-pair-coloured `()`.
3. **Instance name** (`u_uart`, gate instances, `bind` target instances, and
uses of `SymbolKind::Instance` such as `u_uart.sig`) → `function`
(`entity.name.function`).
4. **Port name** (`.clk_i` dot + port name, implicit `.clk_i`, and wildcard
`.*` in an instance's connection list) → `property`
(`entity.name.tag.css` / `entity.other.attribute-name` /
`variable.other.property`).
5. **Port connection** (`clk` inside `.clk_i(clk)` or positional `(clk)`) →
`variable` (`support.variable` / `entity.other.attribute-name` /
`variable.other.readwrite`), keeping signal colouring consistent across the
file and non-white in themes that leave bare `variable` uncoloured.
## Assumptions
- **The 14-type wire legend is unchanged.** Every role above maps onto the
existing `SemanticTokenType` indices (`namespace`, `class`, `parameter`,
`variable`, `property`, `function`), so `token_types().len() == 14` and
`token_modifiers().len() == 1` stay untouched on the wire.
- **AST spans decide instantiation structure; single-file + overlay semantics
decide expressions.** A buffer opened before workspace indexing finishes, a
standalone file, or an instantiation of an unindexed vendor macro still
highlights its module name, `#`, `.PARAM`, instance name, and `.port` from
`Document.tree` alone. Identifiers that resolve through `Document.external`
also take their cross-file `SymbolKind` instead of degrading to `variable`.
- **Parameter `#` only, never delay `#`.** Only the `#` introducing a parameter
port list, parameter override list, or parameterized `DataType` receives
`Highlight::Parameter`; `#5` and `#(1:2:3)` net, assignment, gate, and
procedural delays remain unemitted punctuation.
- **Large-file fast path (`Document::large`) stays lexer-only.** Because the
fast path builds no AST or symbol table, AST-driven `#`, `.`, and `.*` tokens
are emitted only by the full pipeline, alongside identifier refinement.
- **Editor defaults remain user-overridable.** Setting
`editor.semanticHighlighting.enabled = true` in `configurationDefaults` for
`[verilog]` and `[systemverilog]` activates semantic tokens in themes whose
own `semanticHighlighting` flag is unset or `false`, while any explicit user
or workspace setting still wins.
## Handshakes
- **Consumed from `vlog_parser`:** `SourceFile`, `Item`/`ItemKind`, `Module`,
`Instantiation`, `Instance`, `Connections`, `Connection`, `BindDirective`,
`GateInstantiation`, `ClassDecl`, `ClassExtends`, `DataType::params`,
`ListElem`, `RawText`, `Token`, `TokenKind`, `TextRange`. No parser changes.
- **Consumed from `vlog_semantic`:** `Semantics`, `SymbolKind`,
`ExternalResolutions::definition_of`, `Definition`. No semantic changes.
- **Promised to LSP clients (`crates/lucisv_server/src/tokens.rs`):** identical
14-entry `token_types` legend and 1-entry `token_modifiers` legend; sorted,
non-overlapping single-line UTF-16 tokens; exact `full/delta` round-trip.
- **Shared with `editors/vscode/package.json`:** `contributes.semanticTokenScopes`
keys for `verilog` and `systemverilog` are a subset of `tokens::token_types()`,
checked by `editors/vscode/semanticTokens_test.js`.
## Status / TODO
- [x] Add `crates/lucisv_server/src/tokens/instantiation.rs` for AST-guided
instantiation and parameter-header highlight overrides.
- [x] Update `crates/lucisv_server/src/tokens.rs` to apply overrides, consult
`Document.external` via `definition_of`, map `SymbolKind::Instance` to
`Highlight::Function`, and add unit tests covering instantiation shapes,
delay `#` exclusion, recovered entries, and `large-file-mode` window
agreement.
- [x] Configure `editor.semanticHighlighting.enabled` and
`contributes.semanticTokenScopes` for `verilog` and `systemverilog` in
`editors/vscode/package.json`, with headless verification in
`editors/vscode/semanticTokens_test.js` (and `.vscodeignore` exclusion).
- [x] Update `docs/features/lucisv-server/README.md` and
`docs/features/large-file-mode/README.md` for the refined mapping.
## Work log
### 2026-11-17 — dev
- Audited `tokens.rs`, `editors/vscode/package.json`, and VS Code theme scope
tables across Dark Modern/Dark+, Light Modern/Light+, GitHub Dark, One Dark
Pro, Monokai, and Visual Studio Dark. Found two root causes for flat white
instantiations: (1) `tokens.rs` consulted only single-file `Semantics`
(leaving external module names, `.PARAM` overrides, `.port` names, and
`SymbolKind::Instance` all on `Highlight::Variable`, and leaving `#`
unemitted); (2) `package.json` neither defaulted
`editor.semanticHighlighting.enabled` on nor mapped semantic token types to
distinct TextMate scopes for themes where `variable`/`parameter`/`property`
collapse to white or one shared colour.
- Added `crates/lucisv_server/src/tokens/instantiation.rs` (~280 total lines)
and wired `crates/lucisv_server/src/tokens.rs` without changing the 14-type
wire legend:
- Module/interface/`extends` names → `Highlight::Class` (`pkg::` prefixes →
`Highlight::Namespace`);
- Parameter-list `#` (headers, instantiations, parameterized `DataType`s,
never delays), `.PARAM` overrides (`.` + name), and unresolved constant
identifiers inside `#(...)` → `Highlight::Parameter`;
- `SymbolKind::Instance`, `Instance.name_span`, gate instances, and `bind`
instance lists → `Highlight::Function`;
- Named port connections (`.` + name, implicit `.name`, wildcard `.*`),
including recovered unfinished entries while typing → `Highlight::Property`;
- Port connection expressions stay on `identifier_type` (`Highlight::Variable`
for signals), now backed by `ExternalResolutions::definition_of`.
- Added `editor.semanticHighlighting.enabled: true` under
`configurationDefaults` and `semanticTokenScopes` for `verilog` and
`systemverilog` in `editors/vscode/package.json`; added
`editors/vscode/semanticTokens_test.js` (75 checks, all green under `node`)
and listed it in `editors/vscode/.vscodeignore`.
- Cargo/Rust toolchain is not installed on this Windows host; Rust formatting
(`use_small_heuristics = "Max"`, ≤100 cols), clippy rules, and test
invariants were audited manually for Gitea CI execution.
## QA log
## Review
+6 -5
View File
@@ -184,11 +184,12 @@ documented difference below.
### What it gets wrong, honestly
- **A plain identifier is always `variable`, with no `declaration` modifier.**
There is no `Semantics` to refine it with, so a module name is not a `class`
and a parameter is not a `parameter`. Keywords, numbers, strings, comments,
directives, macro uses, `$system` tasks and attributes are all exactly what
the full pipeline says.
- **A plain identifier is always `variable`, with no `declaration` modifier, and
AST-only instantiation punctuation (`#`, `.`, `.*`) is unemitted.** There is
no `Semantics` or `Document.tree` to refine them with, so a module name is
not a `class` and a parameter or `#` is not a `parameter`. Keywords, numbers,
strings, comments, directives, macro uses, `$system` tasks and attributes are
all exactly what the full pipeline says.
- **A `/*` inside a string or after a `//` fools the backward scan**, and so
does a block comment whose opener is more than 64 KiB back — the documented
answer there is "code", so a multi-megabyte block comment mis-highlights.
+24 -14
View File
@@ -573,25 +573,35 @@ Modifiers: `0 declaration`.
| `TokenKind::SystemIdent` (`$display`) | `function` |
| `TokenKind::Attribute` (`(* ... *)`) | `decorator` |
| `Comment` trivia (leading and trailing, incl. on the EOF token) | `comment` |
| `TokenKind::Symbol` | **not emitted** |
| `TokenKind::Ident`, otherwise | from `Semantics`, below |
| `TokenKind::Symbol` (`#` before parameter lists; `.` / `.*` on named connections) | `parameter` / `property` |
| `TokenKind::Symbol`, otherwise | **not emitted** |
| `TokenKind::Ident`, otherwise | from `Document.tree` + `Semantics` + `ExternalResolutions`, below |
A plain identifier is looked up in the file's `Semantics` at its start offset:
a declaration (`symbol_at`) gets its symbol's type **plus the `declaration`
modifier**; a use (`reference_at`) that resolved in-file gets the resolved
symbol's type; anything else — an external candidate, a not-found name, a name
a macro would have produced — falls back to `variable`.
A plain identifier first checks the AST overrides built by
`tokens/instantiation.rs` (`docs/features/instantiation-highlighting/README.md`):
an instantiated module or `extends` base takes `class` (`pkg::` prefixes take
`namespace`), an instance name takes `function`, a `.PARAM` override and any
unresolved constant identifier inside `#(...)` take `parameter` alongside `#`,
and a `.port` connection takes `property`. Otherwise it is looked up through
`ExternalResolutions::definition_of` (`Semantics` first, then the workspace
overlay): a declaration (`symbol_at`) carries the `declaration` modifier, a
resolved local or external reference takes its target's `SymbolKind`, and
anything else falls back to `variable`.
`SymbolKind` → type: `Module`→`class`, `Package`→`namespace`,
`Typedef`→`type`, `EnumVariant`→`enumMember`, `Param`/`TfArg`→`parameter`,
`Function`/`Task`→`function`, `StructMember`→`property`, and
`Port`/`Net`/`Var`/`Genvar`/`Instance`/`Block`→`variable`.
`SymbolKind` → type: `Module`/`Interface`/`Modport`/`Class`/`Covergroup`→`class`,
`Package`→`namespace`, `Typedef`→`type`, `EnumVariant`→`enumMember`,
`Param`/`LocalParam`/`TfArg`→`parameter`,
`Function`/`Task`/`Instance`/`Property`/`Sequence`→`function`,
`StructMember`/`Constraint`/`Coverpoint`/`Cross`→`property`, and
`Port`/`Net`/`Var`/`Genvar`/`Clocking`/`Block`→`variable`.
Two rules that are easy to get wrong and are tested:
- **Punctuation is not emitted.** Every editor already colors brackets from
its TextMate grammar, and emitting one token per `;` roughly triples the
payload for no visible gain.
- **Ordinary punctuation (including `()`) is not emitted.** Every editor
already colours brackets from its bracket-pair colorizer or TextMate grammar,
and emitting one token per `;` roughly triples the payload for no visible
gain; only the parameter-list `#` and named-connection `.`/`.*` carry AST
highlights.
- **No token ever spans a line break.** The spec requires it, and Verilog has
three multi-line token shapes that would violate it — a block comment, a
continued `` `define``, and a multi-line macro invocation. Every span is
+1
View File
@@ -12,5 +12,6 @@ hierarchyView_test.js
referencesModel_test.js
referencesView_test.js
typing_test.js
semanticTokens_test.js
.vscode/**
.gitignore
+13
View File
@@ -5,6 +5,19 @@ for you. The extension and its bundled language server share one version
number; the full engineering notes live in the
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
## 0.65.0 — 2026-11-19
- **Module instantiations are now colour-coded by role.** Module names
(`class`), instance names (`function`), port names (`.clk_i` and `.*`,
`property`), and connected signals (`variable`) each take a distinct colour
instead of blending together in white.
- **`#` shares the parameter colour**, separate from `()`: the `#` before a
parameter header or override list, `.PARAM` names, and parameter values
highlight together as `parameter`, while `#5` delays stay untouched.
- **Semantic highlighting works out of the box across themes.** The extension
now enables `editor.semanticHighlighting.enabled` by default for Verilog and
SystemVerilog and provides distinct TextMate fallback scopes for every role.
## 0.64.0 — 2026-11-17
- **`begin` + Enter writes the `end`.** The cursor lands on the indented
+9 -1
View File
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
then open a Verilog or SystemVerilog file. There is no separate server or CLI
setup.
The current release is **0.64.0**. Its platform packages include
The current release is **0.65.0**. Its platform packages include
`lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see
[Agents (MCP)](#agents-mcp)):
@@ -421,6 +421,14 @@ Every nesting color is a proper VS Code theme color:
}
```
## Release 0.65.0 highlights
Version 0.65.0 gives module instantiations distinct syntax colours across
themes: module names (`class`), instance names (`function`), port names
(`.port` / `.*`, `property`), and connected signals (`variable`) each stand
out, and parameter-list `#` signs share the `parameter` colour separately from
parentheses.
## Release 0.64.0 highlights
Version 0.64.0 makes typing quicker: `begin` + Enter writes the `end`,
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "lucisv",
"version": "0.64.0",
"version": "0.65.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "lucisv",
"version": "0.64.0",
"version": "0.65.0",
"license": "MIT",
"dependencies": {
"vscode-languageclient": "9.0.1"
+107 -1
View File
@@ -2,7 +2,7 @@
"name": "lucisv",
"displayName": "lucisv — Verilog/SystemVerilog",
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
"version": "0.64.0",
"version": "0.65.0",
"publisher": "guoliangchen",
"author": "Guoliang Chen",
"license": "MIT",
@@ -193,15 +193,121 @@
"configurationDefaults": {
"[verilog]": {
"editor.defaultColorDecorators": "never",
"editor.semanticHighlighting.enabled": true,
"editor.stickyScroll.defaultModel": "foldingProviderModel",
"editor.stickyScroll.maxLineCount": 10
},
"[systemverilog]": {
"editor.defaultColorDecorators": "never",
"editor.semanticHighlighting.enabled": true,
"editor.stickyScroll.defaultModel": "foldingProviderModel",
"editor.stickyScroll.maxLineCount": 10
}
},
"semanticTokenScopes": [
{
"language": "verilog",
"scopes": {
"namespace": [
"entity.name.namespace",
"entity.name.type.namespace",
"entity.name.type"
],
"class": [
"entity.name.type.class",
"entity.name.type",
"support.class"
],
"type": [
"entity.name.type",
"support.type"
],
"enumMember": [
"variable.other.enummember",
"variable.other.constant",
"constant.other"
],
"parameter": [
"keyword.control",
"constant.language",
"variable.parameter"
],
"variable": [
"support.variable",
"entity.other.attribute-name",
"variable.other.readwrite"
],
"property": [
"entity.name.tag.css",
"entity.other.attribute-name",
"variable.other.property"
],
"function": [
"entity.name.function",
"support.function"
],
"macro": [
"entity.name.function.preprocessor",
"meta.preprocessor"
],
"decorator": [
"entity.name.function.decorator",
"meta.attribute"
]
}
},
{
"language": "systemverilog",
"scopes": {
"namespace": [
"entity.name.namespace",
"entity.name.type.namespace",
"entity.name.type"
],
"class": [
"entity.name.type.class",
"entity.name.type",
"support.class"
],
"type": [
"entity.name.type",
"support.type"
],
"enumMember": [
"variable.other.enummember",
"variable.other.constant",
"constant.other"
],
"parameter": [
"keyword.control",
"constant.language",
"variable.parameter"
],
"variable": [
"support.variable",
"entity.other.attribute-name",
"variable.other.readwrite"
],
"property": [
"entity.name.tag.css",
"entity.other.attribute-name",
"variable.other.property"
],
"function": [
"entity.name.function",
"support.function"
],
"macro": [
"entity.name.function.preprocessor",
"meta.preprocessor"
],
"decorator": [
"entity.name.function.decorator",
"meta.attribute"
]
}
}
],
"languages": [
{
"id": "verilog",
+106
View File
@@ -0,0 +1,106 @@
// Checks for the VS Code semantic-highlighting manifest contract:
// `configurationDefaults` enables semantic highlighting for both language ids,
// `semanticTokenScopes` covers both language ids identically, every mapped key
// exists in `crates/lucisv_server/src/tokens.rs`'s legend, and the five module
// instantiation roles map to distinct primary TextMate scopes.
//
// node semanticTokens_test.js
//
// See docs/features/instantiation-highlighting/README.md.
const fs = require('fs');
const path = require('path');
let checks = 0;
function fail(what) {
console.error(`semanticTokens_test: FAIL — ${what}`);
process.exit(1);
}
function ok(condition, what) {
checks += 1;
if (!condition) fail(what);
}
const manifestPath = path.join(__dirname, 'package.json');
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
const vscodeignore = fs.readFileSync(path.join(__dirname, '.vscodeignore'), 'utf8');
const tokensRust = fs.readFileSync(
path.join(__dirname, '..', '..', 'crates', 'lucisv_server', 'src', 'tokens.rs'),
'utf8',
);
// 1. `.vscodeignore` keeps this test out of packaged `.vsix` archives.
ok(
vscodeignore.split(/\r?\n/).includes('semanticTokens_test.js'),
'semanticTokens_test.js is listed in .vscodeignore',
);
// 2. Both language ids turn semantic highlighting on by default so themes with
// `semanticHighlighting: false` or unset still render server tokens.
const defaults = manifest.contributes.configurationDefaults;
ok(defaults && typeof defaults === 'object', 'configurationDefaults exists');
for (const lang of ['[verilog]', '[systemverilog]']) {
ok(
defaults[lang] && defaults[lang]['editor.semanticHighlighting.enabled'] === true,
`${lang} sets editor.semanticHighlighting.enabled = true`,
);
}
// 3. Extract the advertised legend names from `tokens.rs::token_types()`.
const legendMap = {
NAMESPACE: 'namespace',
CLASS: 'class',
TYPE: 'type',
ENUM_MEMBER: 'enumMember',
PARAMETER: 'parameter',
VARIABLE: 'variable',
PROPERTY: 'property',
FUNCTION: 'function',
MACRO: 'macro',
KEYWORD: 'keyword',
COMMENT: 'comment',
STRING: 'string',
NUMBER: 'number',
DECORATOR: 'decorator',
};
const fnBody = tokensRust.split('pub fn token_types()')[1].split('}')[0];
const advertised = [...fnBody.matchAll(/SemanticTokenType::([A-Z_]+)/g)].map(([, id]) => {
ok(legendMap[id], `known SemanticTokenType::${id}`);
return legendMap[id];
});
ok(advertised.length === 14, `legend stays at 14 types, got ${advertised.length}`);
// 4. `semanticTokenScopes` is registered identically for `verilog` and `systemverilog`,
// and every key is in the server's advertised legend.
const entries = manifest.contributes.semanticTokenScopes;
ok(Array.isArray(entries) && entries.length === 2, 'two semanticTokenScopes entries');
ok(entries[0].language === 'verilog', 'first entry is verilog');
ok(entries[1].language === 'systemverilog', 'second entry is systemverilog');
ok(
JSON.stringify(entries[0].scopes) === JSON.stringify(entries[1].scopes),
'verilog and systemverilog share identical semanticTokenScopes',
);
const scopes = entries[0].scopes;
for (const [tokenType, chain] of Object.entries(scopes)) {
ok(advertised.includes(tokenType), `${tokenType} is in tokens::token_types()`);
ok(Array.isArray(chain) && chain.length > 0, `${tokenType} has a non-empty scope fallback chain`);
for (const scope of chain) {
ok(typeof scope === 'string' && scope.length > 0, `${tokenType} scope is non-empty string`);
}
}
// 5. All five module-instantiation roles map to pairwise-distinct primary scopes.
const instantiationRoles = ['class', 'parameter', 'function', 'property', 'variable'];
const primaryScopes = instantiationRoles.map((role) => {
ok(Array.isArray(scopes[role]) && scopes[role].length > 0, `${role} is mapped`);
return scopes[role][0];
});
ok(
new Set(primaryScopes).size === instantiationRoles.length,
`instantiation roles have distinct primary scopes: ${primaryScopes.join(', ')}`,
);
console.log(`semanticTokens_test: ${checks} checks passed`);