From e4db0ac1fc396df05cba68858dc04b0733a08ac6 Mon Sep 17 00:00:00 2001 From: Lucio Chen Date: Thu, 19 Nov 2026 02:38:42 -0800 Subject: [PATCH] =?UTF-8?q?TODO=20=C2=A769:=20colour=20module=20instantiat?= =?UTF-8?q?ions=20by=20role,=20with=20#=20matching=20parameters?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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). --- TODO.md | 16 + crates/lucisv_server/src/tokens.rs | 227 +++++++++++-- .../lucisv_server/src/tokens/instantiation.rs | 313 ++++++++++++++++++ .../instantiation-highlighting/README.md | 126 +++++++ docs/features/large-file-mode/README.md | 11 +- docs/features/lucisv-server/README.md | 38 ++- editors/vscode/.vscodeignore | 1 + editors/vscode/package.json | 106 ++++++ editors/vscode/semanticTokens_test.js | 106 ++++++ 9 files changed, 895 insertions(+), 49 deletions(-) create mode 100644 crates/lucisv_server/src/tokens/instantiation.rs create mode 100644 docs/features/instantiation-highlighting/README.md create mode 100644 editors/vscode/semanticTokens_test.js diff --git a/TODO.md b/TODO.md index 22f6620..9825e95 100644 --- a/TODO.md +++ b/TODO.md @@ -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. diff --git a/crates/lucisv_server/src/tokens.rs b/crates/lucisv_server/src/tokens.rs index 9554aad..70c5912 100644 --- a/crates/lucisv_server/src/tokens.rs +++ b/crates/lucisv_server/src/tokens.rs @@ -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 Vec { 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 Vec { + 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, range: Range) -> Vec { /// 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) { +fn collect( + token: &Token, + doc: &Document, + overrides: &HashMap, + out: &mut Vec, +) { 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) { } /// What a token is, or `None` for the ones this server does not colour. -fn classify(token: &Token, semantics: &Semantics) -> Option { +fn classify( + token: &Token, + doc: &Document, + overrides: &HashMap, +) -> Option { + 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 { // 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 { + 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); + } } diff --git a/crates/lucisv_server/src/tokens/instantiation.rs b/crates/lucisv_server/src/tokens/instantiation.rs new file mode 100644 index 0000000..42572ce --- /dev/null +++ b/crates/lucisv_server/src/tokens/instantiation.rs @@ -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 { + 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, +} + +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]) { + 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] + } +} diff --git a/docs/features/instantiation-highlighting/README.md b/docs/features/instantiation-highlighting/README.md new file mode 100644 index 0000000..9510502 --- /dev/null +++ b/docs/features/instantiation-highlighting/README.md @@ -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 diff --git a/docs/features/large-file-mode/README.md b/docs/features/large-file-mode/README.md index 63b5fdc..2b02a42 100644 --- a/docs/features/large-file-mode/README.md +++ b/docs/features/large-file-mode/README.md @@ -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. diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index f1c5cb7..2eab981 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -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 diff --git a/editors/vscode/.vscodeignore b/editors/vscode/.vscodeignore index f6f9b1e..8d596bc 100644 --- a/editors/vscode/.vscodeignore +++ b/editors/vscode/.vscodeignore @@ -12,5 +12,6 @@ hierarchyView_test.js referencesModel_test.js referencesView_test.js typing_test.js +semanticTokens_test.js .vscode/** .gitignore diff --git a/editors/vscode/package.json b/editors/vscode/package.json index a8e4c02..896a52c 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -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", diff --git a/editors/vscode/semanticTokens_test.js b/editors/vscode/semanticTokens_test.js new file mode 100644 index 0000000..37a3204 --- /dev/null +++ b/editors/vscode/semanticTokens_test.js @@ -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`);