Macro expansion M14: hover shows the one-step expansion; v0.5.0
Hovering `NAME(args) now appends an expands-to section: the definition the card already chose (single_step is blind to lookup, so they cannot disagree) with parameters substituted by the call's arguments - one step, so nested macro names stay as written. Strings, `" markers and escaped identifiers are never substituted into; count mismatches, unnarrowed multiple candidates and paren-less function-like uses get no section rather than a guess; an empty argument takes the parameter's declared default. 2000-char cap with a note. Version 0.5.0 closes the M7-M14 navigation run with a CHANGELOG entry covering all eight. Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
36ddabac6c
commit
d26f08335b
17 files changed
+1264
-35
No files matched your search
+108
@@ -4,6 +4,114 @@ All notable changes to vfmt 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.5.0 — 2026-08-25
|
||||
|
||||
The navigation release. `0.3.0` taught vfmt to *change* a project and `0.4.0`
|
||||
to complete what you are typing; this one is about reading one you did not
|
||||
write — who instantiates this module, which file defines this macro, what does
|
||||
this ordered connection actually connect, and what does this macro call turn
|
||||
into.
|
||||
|
||||
### Cross-file references, highlights and folding
|
||||
|
||||
`textDocument/references` now answers **across files** for every symbol the
|
||||
workspace index holds — a module, a package, an exported member, a port — so
|
||||
the list finally matches what rename had been able to change since it shipped;
|
||||
a local `wire` still answers in-file, which is what keeps a signal named `n`
|
||||
off a workspace walk. The cursor on a name highlights its declaration and every
|
||||
use of it in the file (`textDocument/documentHighlight`), where before only a
|
||||
`begin`/`end` pair answered. And every matched scope pair the rainbow already
|
||||
computes is now a **folding range**, folded through the line before the closer
|
||||
so `end`/`endmodule` stays on screen, plus one region per multi-line block
|
||||
comment. Details:
|
||||
[references-nav](docs/features/references-nav/README.md).
|
||||
|
||||
### Inlay hints on ordered connections
|
||||
|
||||
An ordered connection list writes the values and leaves the names to your
|
||||
memory. `textDocument/inlayHint` now draws each port's name as ghost text
|
||||
before the expression it belongs to — `clk:`, `rst_n:`, `data:` — and does the
|
||||
same for a positional `#( ... )` parameter override, from the same
|
||||
instantiation plan the completion and signature help already read. Nothing is
|
||||
written into the buffer, and every uncertainty (a module the index does not
|
||||
hold, a name two files declare, a connection past the last port, a buffer that
|
||||
does not parse) draws *no* hint rather than a guess: a wrong port name in ghost
|
||||
text is worse than none. Details:
|
||||
[inlay-hints](docs/features/inlay-hints/README.md).
|
||||
|
||||
### The index keeps up with the disk
|
||||
|
||||
The server registers for `workspace/didChangeWatchedFiles` and rebuilds its
|
||||
index when files change outside the editor — a `git pull`, a branch checkout, a
|
||||
generator's output, or an edit to the `.f` filelist itself. Until now the index
|
||||
was rebuilt on save, so cross-file answers could quietly describe a tree that
|
||||
no longer existed. Details:
|
||||
[file-watching](docs/features/file-watching/README.md).
|
||||
|
||||
### `` `include`` is a real edge now
|
||||
|
||||
An `` `include`` line is clickable: `textDocument/documentLink` underlines the
|
||||
quoted path and `textDocument/definition` jumps to the file, resolved through
|
||||
the including file's own directory and then each `+incdir+` of the configured
|
||||
filelist in order (the `<angled>` form skips the first rung). The same graph
|
||||
makes hover on `` `NAME`` prefer the definition the hovered file actually
|
||||
*reaches* through its includes — the first thing vfmt has that can order two
|
||||
definitions of one macro name. Where the graph orders nothing, the honest
|
||||
all-candidates list from before still stands. Details:
|
||||
[include-nav](docs/features/include-nav/README.md).
|
||||
|
||||
### Module hierarchy
|
||||
|
||||
"Who instantiates this module?" and "what does this module instantiate?" are
|
||||
answered over LSP's call hierarchy, which is the same graph under different
|
||||
names: `textDocument/prepareCallHierarchy` picks the module under the cursor,
|
||||
`callHierarchy/incomingCalls` lists its instantiation sites and
|
||||
`callHierarchy/outgoingCalls` lists what it builds. Every editor draws the tree
|
||||
with its own hierarchy view, one hop per request, so a recursive design simply
|
||||
unrolls as far as you keep clicking. Details:
|
||||
[hierarchy](docs/features/hierarchy/README.md).
|
||||
|
||||
### The first semantic lint rules
|
||||
|
||||
Three rules written against the symbol table rather than the syntax tree —
|
||||
`unused-signal`, `undriven-net` and `multiply-driven` — the ones a syntax-only
|
||||
linter structurally cannot write, because each needs to know which declaration
|
||||
a name refers to. **All three are off by default** and are opted into with
|
||||
`--select`: they are diagnose-only, they see one file at a time (a signal
|
||||
driven by a cross-module connection is not yet visible to them), and a semantic
|
||||
rule that cries wolf costs an engineer a debugging session and their trust in
|
||||
the tool. A default `vfmt check` is byte-for-byte what it was, and pays nothing
|
||||
for the analysis it does not run. Details:
|
||||
[semantic-lints](docs/features/semantic-lints/README.md).
|
||||
|
||||
### `vfmt -f project.f`
|
||||
|
||||
The CLI gets the front door the language server got in `0.3.0`: `vfmt -f
|
||||
project.f` formats or checks exactly the files an EDA filelist names, nested
|
||||
`-f` and `$VAR` expansion included. The flag is repeatable and combines with
|
||||
positional paths; a path the filelist names is a named path, so `--exclude`
|
||||
and `.gitignore` do not filter it away. Details:
|
||||
[cli-filelist](docs/features/cli-filelist/README.md).
|
||||
|
||||
### Hover expands a macro call
|
||||
|
||||
Hovering a macro use still shows the definition — signature, body, and the file
|
||||
and line it came from — and now shows, under it, what *this* call expands to:
|
||||
the body with the call site's arguments substituted for the parameters. It is
|
||||
deliberately **one step**. A nested `` `INNER`` inside the body keeps its name,
|
||||
and the card says so; `` `"`` and ```` `` ```` pass through as written; string
|
||||
literals and escaped identifiers are not substituted into. An argument count
|
||||
that does not match the parameter list expands nothing at all rather than
|
||||
guessing, and where hover lists several candidate definitions there is no
|
||||
winner to expand. vfmt still does not preprocess — this is bookkeeping shown in
|
||||
a tooltip, and the formatter cannot see it. Details:
|
||||
[macro-expansion](docs/features/macro-expansion/README.md).
|
||||
|
||||
### Editors
|
||||
|
||||
No new settings. Everything above arrives through the server, and the VS Code
|
||||
extension needed only the capabilities it already forwards.
|
||||
|
||||
## 0.4.2 — 2026-08-24
|
||||
|
||||
`#200` is a **delay, not a colour**. VS Code 1.78+ ships a built-in
|
||||
|
||||
Generated
+8
-8
@@ -217,7 +217,7 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vfmt"
|
||||
version = "0.4.2"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
"vfmt_core",
|
||||
@@ -228,11 +228,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vfmt_core"
|
||||
version = "0.4.2"
|
||||
version = "0.5.0"
|
||||
|
||||
[[package]]
|
||||
name = "vfmt_server"
|
||||
version = "0.4.2"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.4.2"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.4.2"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -264,11 +264,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.4.2"
|
||||
version = "0.5.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.4.2"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -276,7 +276,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.4.2"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.4.2"
|
||||
version = "0.5.0"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
|
||||
@@ -590,9 +590,9 @@ parse, so it can never corrupt code.
|
||||
|
||||
`vfmt-server` is a language server: one binary, LSP over stdio, the same
|
||||
answers in every editor. It ships formatting, diagnostics as you type, semantic
|
||||
highlighting, hover (including `` `define`` expansion), go-to-definition,
|
||||
references and document/workspace symbols — the full list, and what is
|
||||
deliberately *not* advertised yet, is in
|
||||
highlighting, hover (including single-step `` `define`` expansion),
|
||||
go-to-definition, references and document/workspace symbols — the full list,
|
||||
and what is deliberately *not* advertised yet, is in
|
||||
`docs/features/vfmt-server/README.md`.
|
||||
|
||||
**The binary comes from the same build as the CLI**, and nothing downloads it
|
||||
@@ -611,7 +611,7 @@ registering the file types and starting the server:
|
||||
|
||||
```bash
|
||||
tools/release.sh # builds dist/vfmt-<version>.vsix
|
||||
code --install-extension dist/vfmt-0.4.2.vsix
|
||||
code --install-extension dist/vfmt-0.5.0.vsix
|
||||
```
|
||||
|
||||
Sideloading that `.vsix` is the supported install; the extension is not on any
|
||||
|
||||
@@ -621,7 +621,7 @@ section only tracks the milestones.
|
||||
multiply-driven: the first semantic lint rules on `vlog_semantic`.
|
||||
- [x] **M13 `cli-filelist`** — `vfmt -f files.f` on the command line,
|
||||
reusing M1's parser; format/lint exactly the project's files.
|
||||
- [ ] **M14 `macro-expansion`** — single-step macro expansion on hover
|
||||
- [x] **M14 `macro-expansion`** — single-step macro expansion on hover
|
||||
(the define-table README's promised follow-up); version 0.5.0 with a
|
||||
CHANGELOG entry covering M7–M14.
|
||||
- [ ] Backlog (extract module, inline, `.*` expansion, ANSI conversion,
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
//! Single-step macro expansion, for hover **display** only.
|
||||
//!
|
||||
//! One step means one thing: the definition's body with the call site's
|
||||
//! arguments substituted for the parameters. A nested `` `INNER`` inside the
|
||||
//! body stays exactly as written — expanding it too would be preprocessing,
|
||||
//! and TODO.md §7 says vfmt does not preprocess. So this module is the same
|
||||
//! kind of bookkeeping `vlog_parser::defines` is: it never touches the
|
||||
//! formatter, never rewrites the buffer, and its only consumer is the hover
|
||||
//! card. See `docs/features/macro-expansion/README.md` for the full rule
|
||||
//! table and the non-goals.
|
||||
|
||||
use vlog_parser::defines::Define;
|
||||
|
||||
/// How many characters of expansion a hover card shows before it stops.
|
||||
pub const CAP: usize = 2000;
|
||||
|
||||
/// A macro use expanded one step.
|
||||
pub struct Expansion {
|
||||
/// The expansion text: at most [`CAP`] characters, plus an ellipsis when
|
||||
/// it was cut.
|
||||
pub text: String,
|
||||
/// Whether the body was longer than [`CAP`] and had to be cut.
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// Expand one macro use against the definition a hover card is already
|
||||
/// showing, or `None` when there is nothing worth showing.
|
||||
///
|
||||
/// `call` is the whole macro-use token — `` `NAME`` or `` `NAME(a, b)`` — as
|
||||
/// the lexer kept it. `None` covers every case where an expansion would be a
|
||||
/// guess or a duplicate: an argument count that does not match the parameter
|
||||
/// list, a function-like macro used without one, a parameter that is not an
|
||||
/// identifier, and an object-like macro whose body holds no further macro use
|
||||
/// (its expansion *is* the body the card already prints).
|
||||
pub fn single_step(call: &str, define: &Define) -> Option<Expansion> {
|
||||
let text = match &define.params {
|
||||
None => object_like(&define.body)?,
|
||||
Some(params) => substituted(&define.body, params, &split_arguments(call)?)?,
|
||||
};
|
||||
Some(capped(text))
|
||||
}
|
||||
|
||||
/// Whether `text` still contains a macro use — a `` ` `` starting a name, and
|
||||
/// not the second backtick of a ```` `` ```` paste.
|
||||
///
|
||||
/// The hover card asks so it can say that one step stopped there.
|
||||
pub fn has_macro_use(text: &str) -> bool {
|
||||
let b = text.as_bytes();
|
||||
(0..b.len()).any(|i| {
|
||||
b[i] == b'`'
|
||||
&& (i == 0 || b[i - 1] != b'`')
|
||||
&& b.get(i + 1).is_some_and(|c| is_name_byte(*c))
|
||||
})
|
||||
}
|
||||
|
||||
/// An object-like macro expands to its body, which is worth a section of its
|
||||
/// own only when the body holds another macro use — otherwise it is the text
|
||||
/// the card already shows one paragraph higher.
|
||||
fn object_like(body: &str) -> Option<String> {
|
||||
if has_macro_use(body) {
|
||||
Some(body.to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The body with each parameter replaced by the argument written at the call
|
||||
/// site, or `None` when the two lists do not line up.
|
||||
fn substituted(body: &str, params: &[String], args: &[String]) -> Option<String> {
|
||||
if params.len() != args.len() {
|
||||
return None;
|
||||
}
|
||||
let mut values: Vec<(&str, &str)> = Vec::with_capacity(params.len());
|
||||
for (param, arg) in params.iter().zip(args) {
|
||||
let (name, default) = split_parameter(param)?;
|
||||
// An argument written empty asks for the default the parameter
|
||||
// declares (LRM 22.5.1); with no default it really is empty text.
|
||||
values.push((name, if arg.is_empty() { default } else { arg }));
|
||||
}
|
||||
Some(replace_names(body, &values))
|
||||
}
|
||||
|
||||
/// A parameter as the define table stores it (`"a"`, `"b = 8"`) split into its
|
||||
/// name and its default. `None` when the name is not a plain identifier, which
|
||||
/// is the one shape substitution could not do anything sensible with.
|
||||
fn split_parameter(param: &str) -> Option<(&str, &str)> {
|
||||
let (name, default) = match param.split_once('=') {
|
||||
Some((name, default)) => (name.trim(), default.trim()),
|
||||
None => (param.trim(), ""),
|
||||
};
|
||||
if name.is_empty() || !name.bytes().all(is_name_byte) {
|
||||
return None;
|
||||
}
|
||||
Some((name, default))
|
||||
}
|
||||
|
||||
/// Walk the body once, replacing whole names that are parameters.
|
||||
///
|
||||
/// Four things are copied through untouched rather than looked inside, and
|
||||
/// each is a deliberate rule (see the feature README): a string literal, a
|
||||
/// nested macro use `` `INNER`` (one step leaves the name as written), the
|
||||
/// `` `"`` and ```` `` ```` escapes, and an escaped identifier `\name`. After
|
||||
/// a ```` `` ```` paste the text is ordinary again, so `` a``b`` substitutes
|
||||
/// both halves.
|
||||
fn replace_names(body: &str, values: &[(&str, &str)]) -> String {
|
||||
let b = body.as_bytes();
|
||||
let mut out = String::with_capacity(body.len());
|
||||
let mut copied = 0;
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
match b[i] {
|
||||
b'"' => i = end_of_string(b, i),
|
||||
b'`' => i = end_of_backtick_escape(b, i),
|
||||
b'\\' => i = end_of_escaped_identifier(b, i),
|
||||
c if is_name_byte(c) => {
|
||||
let end = end_of_name(b, i);
|
||||
if let Some((_, value)) =
|
||||
values.iter().find(|(name, _)| body.get(i..end) == Some(name))
|
||||
{
|
||||
out.push_str(body.get(copied..i).unwrap_or(""));
|
||||
out.push_str(value);
|
||||
copied = end;
|
||||
}
|
||||
i = end;
|
||||
}
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
out.push_str(body.get(copied..).unwrap_or(""));
|
||||
out
|
||||
}
|
||||
|
||||
/// Split a macro call's `(...)` on its top-level commas, or `None` when the
|
||||
/// call carries no argument list at all.
|
||||
///
|
||||
/// The conventions are `vlog_parser::defines::read_params`' own, so a
|
||||
/// parameter list and an argument list are counted the same way: nesting is
|
||||
/// tracked through `()`, `[]` and `{}`, a string is opaque, and `` `NAME()``
|
||||
/// is zero arguments rather than one empty one. Comments are skipped so a
|
||||
/// comma or a bracket inside one cannot split an argument.
|
||||
fn split_arguments(call: &str) -> Option<Vec<String>> {
|
||||
let open = call.find('(')?;
|
||||
let b = call.as_bytes();
|
||||
let mut depth = 0usize;
|
||||
let mut piece_start = open + 1;
|
||||
let mut args: Vec<String> = Vec::new();
|
||||
let mut i = open;
|
||||
while i < b.len() {
|
||||
match b[i] {
|
||||
b'"' => {
|
||||
i = end_of_string(b, i);
|
||||
continue;
|
||||
}
|
||||
b'/' if b.get(i + 1) == Some(&b'/') => {
|
||||
i = end_of_line_comment(b, i);
|
||||
continue;
|
||||
}
|
||||
b'/' if b.get(i + 1) == Some(&b'*') => {
|
||||
i = end_of_block_comment(b, i);
|
||||
continue;
|
||||
}
|
||||
b'(' | b'[' | b'{' => depth += 1,
|
||||
b')' | b']' | b'}' => {
|
||||
depth = depth.saturating_sub(1);
|
||||
if depth == 0 {
|
||||
let piece = call.get(piece_start..i)?.trim();
|
||||
if !(args.is_empty() && piece.is_empty()) {
|
||||
args.push(piece.to_string());
|
||||
}
|
||||
return Some(args);
|
||||
}
|
||||
}
|
||||
b',' if depth == 1 => {
|
||||
args.push(call.get(piece_start..i)?.trim().to_string());
|
||||
piece_start = i + 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Cut an expansion down to [`CAP`] characters. A hover card that fills the
|
||||
/// screen is worse than one that says it stopped.
|
||||
fn capped(text: String) -> Expansion {
|
||||
match text.char_indices().nth(CAP) {
|
||||
None => Expansion { text, truncated: false },
|
||||
Some((cut, _)) => {
|
||||
let mut text = text.get(..cut).unwrap_or_default().to_string();
|
||||
text.push_str(" …");
|
||||
Expansion { text, truncated: true }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Just past the string literal starting at `start`, or the end of the text.
|
||||
fn end_of_string(b: &[u8], start: usize) -> usize {
|
||||
let mut i = start + 1;
|
||||
while i < b.len() {
|
||||
match b[i] {
|
||||
b'\\' => i += 2,
|
||||
b'"' => return i + 1,
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
b.len()
|
||||
}
|
||||
|
||||
/// Just past a `` ` ``-introduced run that substitution must not look inside:
|
||||
/// a nested macro name, or the `` `"``/```` `` ```` escapes (whose *following*
|
||||
/// text is ordinary again, so only the escape itself is skipped).
|
||||
fn end_of_backtick_escape(b: &[u8], start: usize) -> usize {
|
||||
let mut i = start + 1;
|
||||
if matches!(b.get(i), Some(b'`' | b'"' | b'\\')) {
|
||||
return i + 1;
|
||||
}
|
||||
while matches!(b.get(i), Some(&c) if is_name_byte(c)) {
|
||||
i += 1;
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
/// Just past an escaped identifier `\name`, which ends at whitespace
|
||||
/// (LRM 5.6.1). Its letters are not a name substitution may touch.
|
||||
fn end_of_escaped_identifier(b: &[u8], start: usize) -> usize {
|
||||
let mut i = start + 1;
|
||||
while matches!(b.get(i), Some(&c) if !c.is_ascii_whitespace()) {
|
||||
i += 1;
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
fn end_of_line_comment(b: &[u8], start: usize) -> usize {
|
||||
let mut i = start + 2;
|
||||
while i < b.len() && b[i] != b'\n' {
|
||||
i += 1;
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
fn end_of_block_comment(b: &[u8], start: usize) -> usize {
|
||||
let mut i = start + 2;
|
||||
while i < b.len() {
|
||||
if b[i] == b'*' && b.get(i + 1) == Some(&b'/') {
|
||||
return i + 2;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
b.len()
|
||||
}
|
||||
|
||||
fn end_of_name(b: &[u8], start: usize) -> usize {
|
||||
let mut i = start;
|
||||
while matches!(b.get(i), Some(&c) if is_name_byte(c)) {
|
||||
i += 1;
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
fn is_name_byte(c: u8) -> bool {
|
||||
c == b'_' || c == b'$' || c.is_ascii_alphanumeric()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_parser::defines::collect_defines;
|
||||
use vlog_parser::tokenize;
|
||||
|
||||
/// The single definition `text` writes, read the way the server reads it.
|
||||
fn define(text: &str) -> Define {
|
||||
let tokens = tokenize(text).expect("lexes");
|
||||
let table = collect_defines(&tokens);
|
||||
table.entries().first().expect("one define").clone()
|
||||
}
|
||||
|
||||
fn expand(text: &str, call: &str) -> Option<String> {
|
||||
single_step(call, &define(text)).map(|e| e.text)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_is_replaced_by_the_argument_at_the_call_site() {
|
||||
assert_eq!(
|
||||
expand("`define MAX(a, b) ((a) > (b) ? (a) : (b))\n", "`MAX(x, y+1)"),
|
||||
Some("((x) > (y+1) ? (x) : (y+1))".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_that_the_body_never_uses_is_simply_dropped() {
|
||||
assert_eq!(expand("`define FIRST(a, b) a\n", "`FIRST(1, 2)"), Some("1".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_only_contains_a_parameter_is_not_a_parameter() {
|
||||
// `ab` and `a_b` both hold an `a`; only the whole name substitutes.
|
||||
assert_eq!(
|
||||
expand("`define M(a) ab + a_b + a\n", "`M(z)"),
|
||||
Some("ab + a_b + z".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_argument_may_hold_commas_inside_nested_brackets_and_strings() {
|
||||
assert_eq!(
|
||||
expand("`define SHOW(a, b) $display(a, b)\n", "`SHOW(\"x, y\", f(1, {2, 3}))"),
|
||||
Some("$display(\"x, y\", f(1, {2, 3}))".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_few_or_too_many_arguments_expand_to_nothing() {
|
||||
assert_eq!(expand("`define M(a, b) a + b\n", "`M(1)"), None);
|
||||
assert_eq!(expand("`define M(a, b) a + b\n", "`M(1, 2, 3)"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_function_like_macro_used_without_an_argument_list_expands_to_nothing() {
|
||||
assert_eq!(expand("`define M(a) a\n", "`M"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_macro_name_is_left_as_written() {
|
||||
// The one rule that makes this "single step": `INNER is not expanded,
|
||||
// and its name is not mistaken for a parameter either.
|
||||
assert_eq!(
|
||||
expand("`define OUTER(x) `INNER(x) + x\n", "`OUTER(7)"),
|
||||
Some("`INNER(7) + 7".to_string())
|
||||
);
|
||||
assert_eq!(expand("`define OUTER(x) `x\n", "`OUTER(7)"), Some("`x".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_backtick_quote_escape_passes_through_and_still_substitutes() {
|
||||
assert_eq!(
|
||||
expand("`define STR(x) `\"x`\"\n", "`STR(hello)"),
|
||||
Some("`\"hello`\"".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_token_paste_pastes_both_halves() {
|
||||
assert_eq!(expand("`define CAT(a, b) a``b\n", "`CAT(u, v)"), Some("u``v".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_string_in_the_body_is_not_substituted_into() {
|
||||
assert_eq!(
|
||||
expand("`define M(x) $display(\"x is %d\", x)\n", "`M(7)"),
|
||||
Some("$display(\"x is %d\", 7)".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_identifier_in_the_body_is_not_substituted_into() {
|
||||
assert_eq!(expand("`define M(x) \\x + x\n", "`M(7)"), Some("\\x + 7".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_argument_takes_the_parameters_default() {
|
||||
assert_eq!(expand("`define M(a = 8) a\n", "`M()"), None, "zero arguments, one parameter");
|
||||
assert_eq!(expand("`define M(a, b = 8) a + b\n", "`M(1, )"), Some("1 + 8".to_string()));
|
||||
assert_eq!(expand("`define M(a, b) a + b\n", "`M(1, )"), Some("1 + ".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_like_macro_expands_only_when_its_body_holds_a_macro_use() {
|
||||
assert_eq!(expand("`define W 8\n", "`W"), None);
|
||||
assert_eq!(expand("`define W `BASE + 1\n", "`W"), Some("`BASE + 1".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_expansion_is_cut_at_the_cap() {
|
||||
let body = "z".repeat(CAP + 50);
|
||||
let expansion =
|
||||
single_step("`M(1)", &define(&format!("`define M(a) {body}\n"))).expect("expansion");
|
||||
assert!(expansion.truncated);
|
||||
assert_eq!(expansion.text.chars().count(), CAP + 2, "the cap plus ` …`");
|
||||
assert!(expansion.text.ends_with(" …"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_expansion_at_the_cap_is_not_cut() {
|
||||
let body = "z".repeat(CAP);
|
||||
let expansion =
|
||||
single_step("`M(1)", &define(&format!("`define M(a) {body}\n"))).expect("expansion");
|
||||
assert!(!expansion.truncated);
|
||||
assert_eq!(expansion.text, body);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_byte_body_survives_substitution_and_truncation() {
|
||||
assert_eq!(
|
||||
expand("`define M(x) \"λ\" + x\n", "`M(1)"),
|
||||
Some("\"λ\" + 1".to_string()),
|
||||
"no byte slicing through a multi-byte character"
|
||||
);
|
||||
let body = "λ".repeat(CAP + 10);
|
||||
let expansion =
|
||||
single_step("`M(1)", &define(&format!("`define M(a) {body}\n"))).expect("expansion");
|
||||
assert!(expansion.truncated && expansion.text.chars().count() == CAP + 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_real_corpus_macro_expands_the_way_the_rules_say() {
|
||||
// `prim_assert.sv`'s `ASSERT_ERROR`, trimmed to two of its continued
|
||||
// lines: an `` `ifdef`` inside the body (body text, per the LRM),
|
||||
// three nested macro uses, and the parameter used twice.
|
||||
let source = "\
|
||||
`define ASSERT_ERROR(__name) \\
|
||||
`ifdef UVM \\
|
||||
uvm_pkg::uvm_report_error(\"FAILED\", `PRIM_STRINGIFY(__name), \\
|
||||
`__FILE__, __name); \\
|
||||
`endif
|
||||
";
|
||||
let expansion = expand(source, "`ASSERT_ERROR(MyCheck)").expect("expansion");
|
||||
assert!(expansion.contains("`PRIM_STRINGIFY(MyCheck)"), "got {expansion}");
|
||||
assert!(expansion.contains("`__FILE__, MyCheck);"), "used twice: got {expansion}");
|
||||
assert!(expansion.starts_with("`ifdef UVM"), "the `ifdef is body text: got {expansion}");
|
||||
assert!(!expansion.contains("__name"), "every occurrence replaced: got {expansion}");
|
||||
assert!(has_macro_use(&expansion), "three names survive one step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn has_macro_use_ignores_a_token_paste_and_a_backtick_quote() {
|
||||
assert!(!has_macro_use("a``b"));
|
||||
assert!(!has_macro_use("`\"x`\""));
|
||||
assert!(has_macro_use("`INNER"));
|
||||
assert!(!has_macro_use("plain text"));
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,10 @@
|
||||
//! reference resolved in this file, a reference the workspace answered, and a
|
||||
//! declaration itself. The order and the rendering rules are in
|
||||
//! `docs/features/vfmt-server/README.md`.
|
||||
//!
|
||||
//! A macro card also shows what the hovered use expands to in one step, when
|
||||
//! that is more than the body it already prints — `crate::expand` and
|
||||
//! `docs/features/macro-expansion/README.md`.
|
||||
|
||||
use lsp_types::{Hover, HoverContents, MarkupContent, MarkupKind, Uri};
|
||||
use vlog_parser::defines::Define;
|
||||
@@ -11,6 +15,7 @@ use vlog_parser::token::Token;
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{Definition, FileId, Symbol};
|
||||
|
||||
use crate::expand::{self, Expansion};
|
||||
use crate::locate::{display_name, line_number};
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::symbols::kind_label;
|
||||
@@ -34,13 +39,18 @@ fn macro_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option<Hover> {
|
||||
let name = macro_name(token)?;
|
||||
|
||||
if let Some(define) = doc.defines.latest(name) {
|
||||
return Some(markdown(doc, define_text(name, define, None), token.span));
|
||||
return Some(markdown(doc, define_text(name, define, None, Some(&token.text)), token.span));
|
||||
}
|
||||
|
||||
let candidates = narrowed_to_the_include_graph(ws, doc, ws.index().find_define(name));
|
||||
if candidates.is_empty() {
|
||||
return Some(markdown(doc, format!("`` `{name} `` — no definition found"), token.span));
|
||||
}
|
||||
// The expansion follows the definition the card shows, so it is offered
|
||||
// only where the card shows exactly one: with several candidates listed,
|
||||
// expanding one of them would be picking a winner the lookup refused to
|
||||
// pick.
|
||||
let call = (candidates.len() == 1).then_some(token.text.as_str());
|
||||
let mut parts = Vec::with_capacity(candidates.len());
|
||||
for (file, define) in &candidates {
|
||||
let where_ =
|
||||
@@ -48,7 +58,7 @@ fn macro_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option<Hover> {
|
||||
Some(line) => format!("{}:{line}", display_name(path)),
|
||||
None => display_name(path),
|
||||
});
|
||||
parts.push(define_text(name, define, where_));
|
||||
parts.push(define_text(name, define, where_, call));
|
||||
}
|
||||
let joined = if parts.len() == 1 {
|
||||
parts.remove(0)
|
||||
@@ -109,8 +119,10 @@ fn macro_name(token: &Token) -> Option<&str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// One definition, rendered: its signature, its body, and where it came from.
|
||||
fn define_text(name: &str, define: &Define, origin: Option<String>) -> String {
|
||||
/// One definition, rendered: its signature, its body, where it came from, and
|
||||
/// — when `call` is the macro use under the cursor — what that use expands to
|
||||
/// in one step.
|
||||
fn define_text(name: &str, define: &Define, origin: Option<String>, call: Option<&str>) -> String {
|
||||
let signature = match &define.params {
|
||||
Some(params) => format!("`define {name}({})", params.join(", ")),
|
||||
None => format!("`define {name}"),
|
||||
@@ -126,6 +138,27 @@ fn define_text(name: &str, define: &Define, origin: Option<String>) -> String {
|
||||
out.push_str(&define.body);
|
||||
}
|
||||
out.push_str("\n```");
|
||||
if let Some(expansion) = call.and_then(|call| expand::single_step(call, define)) {
|
||||
out.push_str(&expansion_text(&expansion));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The "expands to" half of a macro hover card: this call's arguments
|
||||
/// substituted into the body, fenced exactly like the definition above it.
|
||||
///
|
||||
/// Two footnotes, both there so the card cannot be misread as a preprocessor's
|
||||
/// output: what a remaining macro use means, and where a long body stopped.
|
||||
fn expansion_text(expansion: &Expansion) -> String {
|
||||
let mut out = String::from("\n\n**expands to**\n\n```systemverilog\n");
|
||||
out.push_str(&expansion.text);
|
||||
out.push_str("\n```");
|
||||
if expand::has_macro_use(&expansion.text) {
|
||||
out.push_str("\n\n*one step: a nested macro use is left as written*");
|
||||
}
|
||||
if expansion.truncated {
|
||||
out.push_str(&format!("\n\n*truncated at {} characters*", expand::CAP));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -240,6 +273,115 @@ mod tests {
|
||||
assert!(body.contains("? (a) : (b)"), "got {body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hovering_a_call_shows_what_it_expands_to_in_one_step() {
|
||||
let text = "`define MAX(a, b) ((a) > (b) ? (a) : (b))\nmodule m;\n wire x = `MAX(p, q+1);\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let body = text_of(&hover(&ws, &uri, at(text, "`MAX(p")).expect("hover"));
|
||||
// The definition stays, and the expansion is added under it — same
|
||||
// fence tag, since that is what colours a hover card (0.4.1).
|
||||
assert!(body.contains("```systemverilog\n`define MAX(a, b) ((a) > (b) ? (a) : (b))\n```"));
|
||||
assert!(
|
||||
body.contains("**expands to**\n\n```systemverilog\n((p) > (q+1) ? (p) : (q+1))\n```"),
|
||||
"got {body}"
|
||||
);
|
||||
assert!(!body.contains("one step:"), "nothing left unexpanded here: got {body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_object_like_macro_gets_no_second_section() {
|
||||
// Its expansion *is* its body, which the card already shows.
|
||||
let text = "`define WIDTH 8\nmodule m;\n wire [`WIDTH-1:0] a;\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let body = text_of(&hover(&ws, &uri, at(text, "[`WIDTH") + 2).expect("hover"));
|
||||
assert!(!body.contains("expands to"), "got {body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_like_macro_that_calls_another_shows_where_one_step_stopped() {
|
||||
let text =
|
||||
"`define BASE 4\n`define W `BASE + 1\nmodule m;\n wire [`W-1:0] a;\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let body = text_of(&hover(&ws, &uri, at(text, "[`W-") + 1).expect("hover"));
|
||||
assert!(body.contains("**expands to**\n\n```systemverilog\n`BASE + 1\n```"), "got {body}");
|
||||
assert!(body.contains("*one step: a nested macro use is left as written*"), "got {body}");
|
||||
assert!(!body.contains("`define BASE 4"), "one step, not two: got {body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_whose_argument_count_is_wrong_keeps_todays_card_and_guesses_nothing() {
|
||||
let text = "`define MAX(a, b) ((a) > (b) ? (a) : (b))\nmodule m;\n wire x = `MAX(p);\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let body = text_of(&hover(&ws, &uri, at(text, "`MAX(p")).expect("hover"));
|
||||
assert!(body.contains("`define MAX(a, b)"), "the card is unchanged: got {body}");
|
||||
assert!(!body.contains("expands to"), "got {body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_argument_may_carry_commas_and_strings_of_its_own() {
|
||||
let text = "`define SHOW(a, b) $display(a, b)\nmodule m;\n initial `SHOW(\"x, y\", f(1, 2));\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let body = text_of(&hover(&ws, &uri, at(text, "`SHOW(\"")).expect("hover"));
|
||||
assert!(
|
||||
body.contains("```systemverilog\n$display(\"x, y\", f(1, 2))\n```"),
|
||||
"the commas inside the string and the call did not split it: got {body}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_body_is_truncated_with_a_note() {
|
||||
let filler = "z".repeat(crate::expand::CAP + 100);
|
||||
let text =
|
||||
format!("`define BIG(a) a + {filler}\nmodule m;\n wire x = `BIG(1);\nendmodule\n");
|
||||
let (ws, uri) = document(&text);
|
||||
let body = text_of(&hover(&ws, &uri, at(&text, "`BIG(1")).expect("hover"));
|
||||
assert!(
|
||||
body.contains(" …\n```"),
|
||||
"cut with an ellipsis: got {}",
|
||||
&body[..200.min(body.len())]
|
||||
);
|
||||
assert!(
|
||||
body.contains(&format!("*truncated at {} characters*", crate::expand::CAP)),
|
||||
"and says so"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_expansion_follows_the_definition_the_card_narrowed_to() {
|
||||
// M10's include narrowing picks `a.svh`; the expansion must be that
|
||||
// definition's, not the other file's.
|
||||
let text = "`include \"a.svh\"\nmodule top;\n wire x = `M(7);\nendmodule\n";
|
||||
let (dir, ws, uri) = included(
|
||||
"expandreach",
|
||||
&[
|
||||
("a.svh", "`define M(x) x + 1\n"),
|
||||
("b.svh", "`define M(x) x + 2\n"),
|
||||
("top.sv", text),
|
||||
],
|
||||
);
|
||||
let body = text_of(&hover(&ws, &uri, at(text, "`M(7")).expect("hover"));
|
||||
assert!(body.contains("a.svh:1"), "got {body}");
|
||||
assert!(body.contains("**expands to**\n\n```systemverilog\n7 + 1\n```"), "got {body}");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_candidate_definitions_expand_nothing() {
|
||||
let text = "module top;\n wire x = `M(7);\nendmodule\n";
|
||||
let (dir, ws, uri) = included(
|
||||
"expandambiguous",
|
||||
&[
|
||||
("a.svh", "`define M(x) x + 1\n"),
|
||||
("b.svh", "`define M(x) x + 2\n"),
|
||||
("top.sv", text),
|
||||
],
|
||||
);
|
||||
let body = text_of(&hover(&ws, &uri, at(text, "`M(7")).expect("hover"));
|
||||
assert!(body.contains("is defined 2 times"), "got {body}");
|
||||
assert!(!body.contains("expands to"), "no winner to expand: got {body}");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_undefined_macro_says_so_rather_than_returning_nothing() {
|
||||
let text = "module m;\n wire x = `NOPE;\nendmodule\n";
|
||||
|
||||
@@ -11,6 +11,7 @@ mod code_action;
|
||||
mod completion;
|
||||
mod convert;
|
||||
mod diagnostics;
|
||||
mod expand;
|
||||
mod folding;
|
||||
mod format;
|
||||
mod hierarchy;
|
||||
|
||||
@@ -2281,3 +2281,61 @@ endmodule
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// M14 (macro-expansion): a macro call hovered over the real wire, whose
|
||||
/// definition lives in an included file. The exact markdown a client receives
|
||||
/// is what this pins — a unit test can prove the string is built, only a round
|
||||
/// trip proves it survives serialization into `contents.value`.
|
||||
#[test]
|
||||
fn a_macro_call_hover_carries_its_single_step_expansion_over_the_wire() {
|
||||
let dir = temp_dir("expand");
|
||||
std::fs::write(dir.join("defs.svh"), "`define MAX(a, b) ((a) > (b) ? (a) : (b))\n")
|
||||
.expect("write");
|
||||
let top = dir.join("top.sv");
|
||||
let top_text = "\
|
||||
`include \"defs.svh\"
|
||||
module top;
|
||||
wire [7:0] w = `MAX(p, q + 1);
|
||||
endmodule
|
||||
";
|
||||
std::fs::write(&top, top_text).expect("write");
|
||||
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", top.display());
|
||||
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(top_text).expect("json")
|
||||
)),
|
||||
// The cursor inside `` `MAX`` on line 2.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":20}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
let response = messages
|
||||
.iter()
|
||||
.find(|m| m["id"] == 2)
|
||||
.unwrap_or_else(|| panic!("no hover response: {messages:#?}"));
|
||||
let hover = response["result"]["contents"]["value"].as_str().expect("hover markdown");
|
||||
|
||||
assert_eq!(
|
||||
hover,
|
||||
"defined in `defs.svh:1`\n\n\
|
||||
```systemverilog\n`define MAX(a, b) ((a) > (b) ? (a) : (b))\n```\n\n\
|
||||
**expands to**\n\n\
|
||||
```systemverilog\n((p) > (q + 1) ? (p) : (q + 1))\n```",
|
||||
"the whole card, byte for byte"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -13,6 +13,18 @@ bookkeeping, not expansion"). The table is also the substrate for the later
|
||||
single-step expansion display and for `` `WIDTH`` → "defined as 8 in
|
||||
defs.svh:12".
|
||||
|
||||
> **Both promises are kept, and neither needed a change here.** `` `WIDTH`` →
|
||||
> "defined as 8 in defs.svh:12" shipped with the server's hover card and was
|
||||
> narrowed to the include graph in M10 (`docs/features/include-nav/README.md`).
|
||||
> The **single-step expansion display** shipped in M14, 2026-08-25:
|
||||
> `crates/vfmt_server/src/expand.rs` substitutes a call site's arguments into
|
||||
> `Define::body` using `Define::params` exactly as recorded — defaults and all
|
||||
> — and adds an "expands to" section to the card. `defines.rs` is byte-identical
|
||||
> across that round: `params` "as written" and the LRM-literal body
|
||||
> normalization were the two decisions the consumer turned out to need, which
|
||||
> is the argument for both of them. Rules, non-goals and the reason a nested
|
||||
> `` `INNER`` is *not* expanded: `docs/features/macro-expansion/README.md`.
|
||||
|
||||
## Zero lexer changes, and why that worked
|
||||
|
||||
The task allowed touching `lexer.rs` if directive granularity made a post-lex
|
||||
@@ -187,6 +199,16 @@ above. Nothing depends on it yet, so it is free to change; the two things
|
||||
worth not changing casually are the body normalization rule (a hover string is
|
||||
user-visible) and "all definitions are kept".
|
||||
|
||||
> **No longer free to change (M14, 2026-08-25).** `vfmt_server`'s
|
||||
> `expand.rs` now reads `body` *and* `params` structurally: it splits a
|
||||
> parameter on its first `=` to get the name and the default, and it counts
|
||||
> `params` against the arguments at a call site, declining to expand on a
|
||||
> mismatch. So two things became contracts rather than conveniences —
|
||||
> parameters stored **as written** (`"b = 8"`, not `"b"`), and `` `define
|
||||
> NAME()`` recorded as `Some(vec![])` rather than one empty parameter, which
|
||||
> `expand.rs` mirrors so both sides count a zero-argument call the same way.
|
||||
> The body normalization rule is now user-visible twice per card.
|
||||
|
||||
**Requested of nobody.** No other module needs a change. In particular
|
||||
`parser.rs`, `format.rs` and `verify.rs` are untouched — CLAUDE.md hard
|
||||
invariant #4 does not apply to this round, because the safety net's
|
||||
@@ -227,6 +249,11 @@ and no AST node. The parameter-list scan tracks nesting with one `usize` that
|
||||
would be building for a consumer that does not exist.
|
||||
- [ ] **Not done:** stripping a `//` comment from a continuation line (see
|
||||
Assumptions), and cross-file `` `include`` following (workspace index).
|
||||
- [x] **Promised follow-up, delivered elsewhere (M14, 2026-08-25):**
|
||||
single-step expansion display on hover —
|
||||
`docs/features/macro-expansion/README.md`. It consumes this table
|
||||
unchanged; no file in this feature was edited for it. Cross-file
|
||||
`` `include`` following also landed, in M10's include graph.
|
||||
|
||||
## Work log
|
||||
|
||||
|
||||
@@ -0,0 +1,424 @@
|
||||
# macro-expansion
|
||||
|
||||
## Goal
|
||||
|
||||
Keep the promise `docs/features/define-table/README.md` made when it recorded
|
||||
the first `` `define``: *"The table is also the substrate for the later
|
||||
single-step expansion display."* Hovering a macro use has shown the definition
|
||||
verbatim since the server shipped, which answers "what is this macro" but not
|
||||
"what did **this call** just say" — for a function-like macro the reader still
|
||||
has to substitute the arguments in their head, which is exactly the step that
|
||||
goes wrong. TODO.md §8's M14 closes that: the hover card keeps its signature,
|
||||
body and origin, and gains an **expands to** section holding the body with the
|
||||
call site's arguments substituted for the parameters. One step, display only.
|
||||
The formatter still never expands anything (TODO.md §7), the buffer is never
|
||||
rewritten, and nothing outside `hover.rs` can see this text.
|
||||
|
||||
## One step means one step
|
||||
|
||||
The whole feature is parameter substitution and nothing else. A nested
|
||||
`` `INNER`` inside the body is **left as written** — not looked up, not
|
||||
expanded, not even checked for existence. Two reasons, and they are the reason
|
||||
this stays bookkeeping rather than becoming a preprocessor:
|
||||
|
||||
1. **Expanding the nest is preprocessing.** It needs a definition set, which
|
||||
needs the conditional-compilation state, which vfmt deliberately does not
|
||||
have (`define-table`'s Assumptions: `` `ifdef`` arms are both recorded and
|
||||
neither is evaluated). One honest step is worth more than a cascade built on
|
||||
a guess about which arm is live.
|
||||
2. **It terminates by construction.** No recursion, no depth counter, no cycle
|
||||
check — `` `define A `A `` is one substitution pass over one body, so the
|
||||
recursion budget in `docs/features/recursion-limit/README.md` is not charged
|
||||
at all.
|
||||
|
||||
When the rendered expansion still contains a macro use, the card says so under
|
||||
the fence (*"one step: a nested macro use is left as written"*), so the text is
|
||||
never mistaken for a preprocessor's output.
|
||||
|
||||
## The substitution rules (exact)
|
||||
|
||||
Given the definition's `body` (as `vlog_parser::defines` normalized it — one
|
||||
logical line, continuations already joined) and the arguments split out of the
|
||||
hovered call token, `expand::replace_names` walks the body **once** and
|
||||
replaces every whole name that is a parameter. What it does *not* look inside
|
||||
is the interesting half:
|
||||
|
||||
| In the body | Treatment | Why |
|
||||
|---|---|---|
|
||||
| `a` (a whole name that is a parameter) | replaced by the argument as written | the feature |
|
||||
| `ab`, `a_b` when `a` is the parameter | untouched | substitution is by whole name, never by substring |
|
||||
| `"a is %d"` (a plain string literal) | copied through, never substituted into | a preprocessor does not substitute inside a string literal (LRM 22.5.1) |
|
||||
| `` `"a`" `` | the `` `"`` markers are copied verbatim, the name **between** them still substitutes | one step shows the substitution; turning `` `"x`"`` into `"x"` is stringification *semantics*, and that is a non-goal (below) |
|
||||
| `` a``b `` | both halves substitute, the ```` `` ```` is copied verbatim | after a token paste the text is ordinary again; performing the paste is the preprocessor's job, not this card's |
|
||||
| `` `INNER`` / `` `INNER(a)`` | the whole `` `NAME`` is skipped, so it is neither expanded nor mistaken for a parameter | single step; and `` `x`` is a macro use even when a parameter happens to be called `x` |
|
||||
| `\odd$name` (an escaped identifier) | skipped to the next whitespace (LRM 5.6.1) | its letters are not a name a substitution may touch |
|
||||
|
||||
Arguments are split out of the macro-use **token text** — the lexer already
|
||||
keeps `` `NAME(...)`` as one token, argument list included — on top-level
|
||||
commas, with `()`, `[]` and `{}` nesting tracked, strings opaque, and `//`
|
||||
and `/* */` comments skipped so a comma inside one cannot split an argument.
|
||||
The conventions are deliberately `defines.rs::read_params`' own, so a
|
||||
parameter list and an argument list are counted the same way: **`` `NAME()``
|
||||
is zero arguments**, not one empty one. Each argument is trimmed at both ends
|
||||
and otherwise substituted byte for byte, newlines included (a call written
|
||||
across several lines expands across several lines, inside the fence).
|
||||
|
||||
Three shapes produce **no expansion section at all**, and the card is exactly
|
||||
what it was before this feature:
|
||||
|
||||
- **An argument count that does not match the parameter list** — too few or
|
||||
too many. Never guess: a card that silently drops or invents an argument is
|
||||
worse than one that only shows the definition.
|
||||
- **A function-like macro used without an argument list** (`` `MAX`` where
|
||||
`MAX` takes two parameters). Legal to write, nothing to substitute.
|
||||
- **A parameter that is not a plain identifier.** `defines.rs` records a
|
||||
malformed parameter list as written rather than rejecting it, so this module
|
||||
has to decline it rather than substitute nonsense.
|
||||
|
||||
One convenience, because it is what the source says rather than a guess: an
|
||||
argument written **empty** (`` `M(1, )``) takes the default the parameter
|
||||
declares (`` `define M(a, b = 8)`` → `1 + 8`), per LRM 22.5.1. With no
|
||||
default declared, an empty argument substitutes empty text. A call that omits
|
||||
a defaulted argument *entirely* is still a count mismatch and expands nothing.
|
||||
|
||||
## Object-like macros: only when there is something new to show
|
||||
|
||||
An object-like macro has no parameters, so its one-step expansion **is** its
|
||||
body — the text the card already prints one paragraph higher. Printing it
|
||||
twice is noise, so the section appears only when the body itself contains a
|
||||
macro use. There it earns its place: the card shows `` `BASE + 1`` under
|
||||
"expands to" *with the one-step footnote*, which is how the reader learns that
|
||||
`` `BASE`` was deliberately not resolved rather than accidentally missed.
|
||||
|
||||
## Which definition gets expanded
|
||||
|
||||
Whichever one the card is already showing — the expansion never disagrees with
|
||||
the definition printed above it. In practice that is M10's narrowing
|
||||
(`docs/features/include-nav/README.md`): the file's own `` `define`` first,
|
||||
then the one definition it reaches through its `` `include``s. Where hover
|
||||
falls back to listing several candidates ("`` `W `` is defined 2 times"), **no
|
||||
expansion is offered** — picking one to expand would be choosing a winner the
|
||||
lookup itself refused to choose.
|
||||
|
||||
## Truncation
|
||||
|
||||
`expand::CAP` is **2000 characters**. Real macro bodies run long — the UVM and
|
||||
`prim_assert.sv` families join five or more continued lines into one — and a
|
||||
hover card that fills the screen is worse than one that stops and says so. Past
|
||||
the cap the text is cut at a character boundary, ` …` is appended, and the card
|
||||
adds *"truncated at 2000 characters"* under the fence. The number is a display
|
||||
choice with no semantics attached: nothing downstream reads the expansion, so
|
||||
raising it later breaks nothing.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- **No stringification semantics.** `` `"`` and ```` `` ```` are passed through
|
||||
as the characters they are. Performing them would mean deciding what the
|
||||
resulting token *is*, which is preprocessing.
|
||||
- **No nested expansion**, per "one step" above.
|
||||
- **No conditional compilation.** `` `ifdef`` inside a body is body text, as
|
||||
`define-table` already records.
|
||||
- **Nothing reaches the formatter.** No output of this module is ever written
|
||||
to a buffer, so CLAUDE.md's hard invariants #1–#3 cannot be engaged by it and
|
||||
`verify.rs` is untouched (invariant #4 does not apply — the safety net's
|
||||
forgiveness was neither widened nor narrowed).
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The macro-use token carries the whole invocation.** `token.rs::is_macro`
|
||||
says so in its own doc comment, and `lexer.rs::scan_macro_args` is what makes
|
||||
it true (balanced `()`/`[]`/`{}`, strings and comments skipped, nesting
|
||||
capped). If the lexer ever split a call into several tokens, argument
|
||||
splitting here would have to be rewritten.
|
||||
- **The body is one logical line with continuations already joined**, per
|
||||
`define-table`'s normalization rule. The two documented warts of that rule
|
||||
ride along into the expansion: a `//` comment on a continuation line is body
|
||||
text, and a continuation into a blank final line leaves a literal `\`. Both
|
||||
are display warts in a tooltip, unchanged by this feature.
|
||||
- **A macro use inside a comment or a string is not a token**, so hovering one
|
||||
never reaches this code.
|
||||
- **Non-ASCII text is copied, never inspected.** A parameter name is ASCII by
|
||||
construction (`defines.rs` reads names as `[A-Za-z0-9_$]`), so every slice
|
||||
this module takes starts and ends on an ASCII boundary; multi-byte bodies are
|
||||
copied through and the cap counts characters, not bytes.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `vlog_parser`:** `defines::Define` — `params` (as written,
|
||||
defaults included) and `body` (normalized). Nothing new is asked of it; in
|
||||
particular `Define` is *not* extended, because everything needed was already
|
||||
recorded in 2026-08-19. Also `token::Token::is_macro`'s promise that the text
|
||||
is the whole invocation.
|
||||
|
||||
**Consumed from `crate::hover`:** the definition the card chose, and the macro
|
||||
use token under the cursor. The module is deliberately blind to the workspace,
|
||||
the index and the include graph — it takes two strings and a `Define`.
|
||||
|
||||
**Promised to `crate::hover`:** `expand::single_step(call, define) ->
|
||||
Option<Expansion>` and `expand::has_macro_use(text) -> bool`, plus the `CAP`
|
||||
constant the card quotes in its own note. `None` always means "render exactly
|
||||
the card you rendered before this feature".
|
||||
|
||||
**Promised to the extension:** the expansion fence is ```` ```systemverilog ````
|
||||
like every other code block the server emits — the language id the TextMate
|
||||
grammar of 0.4.1 is registered for (`docs/features/editor-packaging/README.md`).
|
||||
The e2e test pins the whole card byte for byte, tag included.
|
||||
|
||||
**Requested of nobody.** No other module changes: `hover.rs` gains one
|
||||
argument on a private function and one section on one card, `main.rs` gains one
|
||||
`mod` line, and nothing else in the workspace is touched.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `crates/vfmt_server/src/expand.rs` (new, ~250 lines with tests):
|
||||
`single_step`, `has_macro_use`, `CAP`, `Expansion`. No dependencies.
|
||||
- [x] Argument splitting on top-level commas, mirroring `read_params`
|
||||
(nesting, strings, comments, `` `NAME()`` = zero arguments).
|
||||
- [x] Whole-name substitution with strings, `` `"``/```` `` ````, nested macro
|
||||
names and escaped identifiers passed through.
|
||||
- [x] Empty argument takes the parameter's declared default.
|
||||
- [x] Count mismatch / no argument list / non-identifier parameter → no
|
||||
section.
|
||||
- [x] Object-like macro: section only when the body holds a macro use.
|
||||
- [x] Expansion follows the definition the card shows; several candidates →
|
||||
no section.
|
||||
- [x] 2000-character cap with an ellipsis and a note.
|
||||
- [x] `hover.rs`: the **expands to** section, the one-step footnote, the
|
||||
truncation footnote; `define_text` takes the call.
|
||||
- [x] Tests: 18 unit tests in `expand.rs`, 8 in `hover.rs`, 1 e2e stdio round
|
||||
trip pinning the exact card. All pre-existing hover tests unchanged.
|
||||
- [x] Version 0.5.0 across the workspace and the extension; `CHANGELOG.md`
|
||||
entry covering M7–M14.
|
||||
- [x] `define-table`'s promise annotated as kept; `vfmt-server`'s hover row
|
||||
updated.
|
||||
- [ ] **Not done, deliberately:** expanding the nest (see "One step"),
|
||||
stringification/paste semantics, and a `` `define`` chosen by cursor
|
||||
position rather than by "last definition in the file" — that last one is
|
||||
`define-table`'s own open `in_force_at` item and belongs there.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-25 — dev agent
|
||||
|
||||
- Read `CLAUDE.md`, the `define-table`, `include-nav` and `vfmt-server`
|
||||
READMEs, `hover.rs`, `defines.rs` and the lexer's `` ` `` arm before writing
|
||||
anything. Baseline: `cargo test --workspace` **1556 passed, 0 failed**;
|
||||
clippy silent; fmt clean.
|
||||
- **Put the logic in a module of its own** (`expand.rs`) rather than in
|
||||
`hover.rs`. Not for a second consumer — there is none — but because the rule
|
||||
table above is the whole feature, and it is testable as pure functions over
|
||||
`(call text, Define)`, which is what let the substitution rules get 18 tests
|
||||
without constructing a `Workspace`.
|
||||
- **The hard decision was what "one step" excludes**, and it was decided by
|
||||
what vfmt already refuses to know. Expanding a nested `` `INNER`` would need
|
||||
a definition set resolved through conditional compilation; `define-table`
|
||||
records both `` `ifdef`` arms and evaluates neither, so any cascade would sit
|
||||
on a guess. Stopping after one substitution pass also removes recursion,
|
||||
cycles and depth limits from the design entirely.
|
||||
- **The second decision was what substitution must not look inside.** Started
|
||||
from "replace whole names" and then walked the body's escapes one by one:
|
||||
plain strings (a preprocessor does not substitute into one), `` `"`` (the
|
||||
markers pass through but the name between them must still substitute — the
|
||||
opposite choice makes `` `PRIM_STRINGIFY`` show `__x` for every call),
|
||||
```` `` ```` (both halves substitute; the paste itself is not performed),
|
||||
`` `INNER`` (skipped whole, which is also what stops a parameter named `x`
|
||||
from being substituted inside `` `x``), and `\escaped$id` (skipped to
|
||||
whitespace). Each row of the table has a test.
|
||||
- **Mirrored `defines.rs::read_params` for argument splitting on purpose.**
|
||||
The count on both sides has to agree or the mismatch rule fires on
|
||||
well-formed calls; sharing the *convention* (rather than the code, which
|
||||
lives in another crate and is private) is what keeps `` `NAME()`` = zero on
|
||||
both sides. Pinned by the `` `M()`` case in
|
||||
`an_empty_argument_takes_the_parameters_default`.
|
||||
- **Empty argument → declared default** was added after writing the mismatch
|
||||
rule and noticing `` `M(1, )`` would otherwise render `1 + `, which reads as
|
||||
a bug in the user's code. Using the default is reading the source, not
|
||||
guessing; a call that omits the argument entirely still expands nothing.
|
||||
- **Truncation counts characters, not bytes**, so a multi-byte body cannot be
|
||||
cut mid-character; there is a test with a 2010-character `λ` body.
|
||||
- **Checked the existing hover tests rather than adapting them.** All eighteen
|
||||
(sixteen in `tests`, two in `qa_findings`) pass with no assertion changed:
|
||||
the new section is appended *after* the closing fence, so every
|
||||
`contains(...)` on the definition still holds, and the two macro cases they
|
||||
exercise are the two that gain nothing — `` `define WIDTH 8`` is a plain
|
||||
object-like macro, and `` `MAX(1, 2)`` only had its signature and body
|
||||
asserted. Nothing in the diff changes an existing expectation.
|
||||
- Version bumped to 0.5.0 in `Cargo.toml` (all eight crates inherit),
|
||||
`Cargo.lock` (via `cargo check --workspace`),
|
||||
`editors/vscode/package.json`, `editors/vscode/package-lock.json` (both
|
||||
places), `tools/RELEASING.md`'s examples, `README.md` and
|
||||
`editors/vscode/README.md`'s install lines — the same list
|
||||
`tools/RELEASING.md` §1 names. `CHANGELOG.md` gained the 0.5.0 entry, one
|
||||
section per M7–M14 milestone, each linking its feature README.
|
||||
- Did not run `git commit`/`git push`. Did not touch `TODO.md`'s M14 checkbox
|
||||
or the umbrella checklist (out of scope by instruction), the formatter, the
|
||||
linter, `verify.rs`, or any other crate.
|
||||
|
||||
**Results:** `cargo test --workspace` **1583 passed, 0 failed** (up 27: 18
|
||||
`expand.rs` + 8 `hover.rs` + 1 e2e), `cargo clippy --all-targets` silent,
|
||||
`cargo fmt --all --check` clean, `editors/vscode/smoke.js` OK against the
|
||||
0.5.0 server binary, and `npx @vscode/vsce ls` accepts the manifest.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-25 — QA agent
|
||||
|
||||
**1. Gates — PASS.** `cargo test --workspace`: **1583 passed, 0 failed**
|
||||
(summed across every test binary; matches the work log's claim exactly).
|
||||
`cargo clippy --all-targets`: silent. `cargo fmt --all --check`: clean.
|
||||
`node editors/vscode/smoke.js target/debug/vfmt-server`: `smoke: OK`.
|
||||
`npx @vscode/vsce ls` (in `editors/vscode/`): exit 0, manifest accepted.
|
||||
`vfmt --version` → `vfmt 0.5.0`. Version sweep: root `Cargo.toml`
|
||||
`version = "0.5.0"`, all eight crates inherit via `version.workspace = true`
|
||||
(confirmed by reading every `crates/*/Cargo.toml`), `editors/vscode/package.json`
|
||||
and `package-lock.json` (both places) at `0.5.0`, `tools/RELEASING.md`,
|
||||
`README.md`, `editors/vscode/README.md` examples all read `0.5.0`. The three
|
||||
remaining `grep -rn "0.4.2"` hits outside `CHANGELOG.md`
|
||||
(`docs/features/refactor/README.md:247`, `docs/features/semantic-lints/README.md:489`,
|
||||
`docs/features/editor-packaging/README.md:552`) are all dated work-log entries
|
||||
describing what happened *in* 0.4.2 — correctly historical, not stray current-
|
||||
version claims. No blocking finding.
|
||||
|
||||
**2. Substitution rules — attacked, all held.** Added 13 temporary attack
|
||||
tests directly to `expand::tests` (deleted after the run, per the
|
||||
`define-table` QA convention of not leaving probe tests in the tree — none of
|
||||
them are in the diff `git status` shows). All 13 passed on the first run,
|
||||
which is itself worth noting since the define-table QA round treated an
|
||||
all-green first pass as "a reason for suspicion, not comfort" — I re-read the
|
||||
code path for each before trusting the green:
|
||||
|
||||
| attack | result | verdict |
|
||||
|---|---|---|
|
||||
| `` `define M(a, ab) a + ab`` , `` `M(1, 2)`` — param name is a prefix of another param | `"1 + 2"` | OK — whole-name equality in `replace_names`'s `find`, no substring bleed |
|
||||
| `` `SHOW(a, b) a b`` , call `` `SHOW(1 /* x, y */, 2)`` — comma inside a block comment | `"1 /* x, y */ 2"` | OK — `split_arguments`'s comment skip works inside the call text |
|
||||
| `` `SHOW(a, b) a-b`` , call with a `//` comment holding a comma, real separator on the next physical line | `"1 // x, y-2"` | OK, and instructive: the argument's trailing embedded `\n` is trimmed away by the documented "trimmed at both ends" rule — not a bug, just worth flagging since it means a `//` comment's newline inside an argument does not survive. Not filed as a finding — the README already documents "trimmed at both ends," this is a corollary, not a surprise the README owes the reader |
|
||||
| call with an unbalanced `"unterminated` string | `None` | OK — `end_of_string` runs to `b.len()` and the outer loop exits without finding a closing `)`, no panic, no hang |
|
||||
| `` `define X `X`` , `` `X`` (self-reference) | `` "`X" `` | OK — one substitution pass, no recursion in the call graph (verified by reading `single_step`: it never calls itself) |
|
||||
| `` `define E`` (empty object-like body), `` `E`` | `None` | OK — `has_macro_use("")` is false |
|
||||
| `` `define E(a)`` (empty function-like body), `` `E(1)`` | `Some("")` | OK, matches "no section" not applying here since there *is* a call with a matching arg count — body is legitimately empty text |
|
||||
| `` `define A(x) x+1`` , use `` `A (b)`` — space before the paren | `None` | OK, and this is the one that needed lexer reading, not just `expand.rs`: `lexer.rs`'s `` ` `` arm checks `self.peek() == b'('` immediately after the identifier scan with no whitespace skip, so a space means `scan_macro_args` never runs and the macro token is just `` "`A" `` with no `(`. `split_arguments` then sees no `(` at all and returns `None` — correctly the documented "function-like macro used without an argument list" bucket, not a false expansion and not a false no-section either |
|
||||
| `` `M(a=1,b=2) a-b`` , `` `M(,)`` (two empty args, both defaulted) | `"1-2"` | OK |
|
||||
| `` `M(a,b) a-b`` , `` `M(,)`` (two empty args, no defaults) | `"-"` | OK, matches the table's "with no default declared, an empty argument substitutes empty text" |
|
||||
| `` `M(a=1,b=2) a-b`` , `` `M()`` (zero args, two defaulted params) | `None` | OK — confirms the claim in the task brief: zero arguments against two parameters is a count mismatch (`0 != 2`) even though both have defaults; defaults fill missing argument *text*, not a missing *argument*. `defines.rs`'s `Define::params` does record defaults (`Some(["a = 1", "b = 2"])`), read directly, so `split_parameter` has something to split on — the claim holds structurally too |
|
||||
| `` `M(a,b) 42`` , `` `M(1)`` (one param never used, wrong arg count) | `None` | OK — argument count is still validated even though the body would not have used the second one |
|
||||
| `` `M(a,b) a `"b`"`` , `` `M(1,2)`` — a param outside the `` `"..`" `` escape and a *different* param inside it | `` "1 `\"2`\"" `` | OK — confirms both halves of the escape-adjacency claim: the param outside substitutes normally, and the name between the stringify markers still substitutes |
|
||||
| `` `M(a[3]) a[3]+1`` , `` `M(x)`` — non-identifier parameter (`[`/`]` are not name bytes) | `None` | OK — `split_parameter`'s `is_name_byte` check rejects it, `substituted` declines via `?` |
|
||||
| CAP−1 ASCII bytes + one 2-byte `λ` landing exactly on the cap boundary + trailing text | truncated, `CAP + 2` chars, valid UTF-8 | OK — no panic slicing mid-character; `capped`'s `char_indices().nth(CAP)` is char-counted, not byte-counted, as claimed |
|
||||
|
||||
No corruption, no panic, no hang, no false "no section," no false expansion
|
||||
in any of the 13 probes. The skip-list (strings, `` `"``/```` `` ````, nested
|
||||
macro names, escaped identifiers) is honest.
|
||||
|
||||
**3. Empty-arg-default claim vs. `Define` — verified structurally.**
|
||||
Read `crates/vlog_parser/src/defines.rs` directly (not just the README):
|
||||
`Define::params` is `Option<Vec<String>>`, one entry per parameter *as
|
||||
written*, defaults included (`` `define MAX(a, b = 8)`` → `Some(["a", "b = 8"])`,
|
||||
confirmed by the doc comment on the field and by the define-table README's own
|
||||
API section). `expand.rs::split_parameter` splits each entry on its first `=`
|
||||
to recover the default — the dependency the define-table README's Handshakes
|
||||
section already calls out as "no longer free to change (M14)". The claim is
|
||||
accurate: `defines.rs` does record defaults, and `expand.rs` reads them
|
||||
structurally rather than guessing.
|
||||
|
||||
**4. Truncation — re-verified.** `an_expansion_at_the_cap_is_not_cut` (body of
|
||||
exactly `CAP` chars, dev's own test) passed. The dev's own multi-byte cap test
|
||||
plus my boundary probe above cover the char-vs-byte question from two angles;
|
||||
both green.
|
||||
|
||||
**5. M10-narrowing consistency — independently re-verified outside the unit
|
||||
tests**, by building two `vfmt-server` binaries and driving both over real
|
||||
stdio with a hand-written Python LSP client (temporary, deleted after the
|
||||
run — not `cargo test`, so it exercises the wire format the same way
|
||||
`smoke.js` does but for hover):
|
||||
|
||||
- **1-of-2 narrowed, hover follows the shown definition.** Fixture: `a.svh`
|
||||
defines `` `define M(x) x + 1``, only `a.svh` is `` `include``d. Hovering
|
||||
`` `M(7)`` shows `defined in \`a.svh:1\`` and **expands to** `7 + 1` — the
|
||||
narrowed definition, not a guess.
|
||||
- **2 candidates, unnarrowed, byte-identical to pre-M14.** Fixture: both
|
||||
`a.svh` (`x + 1`) and `b.svh` (`x + 2`) included, so the lookup lists both
|
||||
candidates. Built `vfmt-server` at HEAD (`36ddaba`, pre-M14, via
|
||||
`git stash push -u` / `git stash pop` around the build — working tree
|
||||
restored immediately after, confirmed via `git status --short` matching the
|
||||
pre-stash listing exactly) and at the current M14 tree, ran the identical
|
||||
hover request against both binaries, and `diff`'d the two markdown outputs:
|
||||
**byte-identical.** This also follows directly from reading the `hover.rs`
|
||||
diff — the only change to `define_text` is one `if let Some(expansion) =
|
||||
call.and_then(...)` block appended after the existing render, and the
|
||||
multi-candidate call site passes `call = None`, so the added block is
|
||||
fully skipped and nothing upstream of it changed — but I verified it
|
||||
empirically as the task asked rather than relying on the read alone.
|
||||
|
||||
**6. Independent e2e — PASS.** Same Python stdio client (not the dev's
|
||||
`e2e.rs`, a separate harness) against `` `define M(x) x + 1`` / `` `M(7)``
|
||||
returned `expands to` → `7 + 1` over the real LSP wire. The dev's own
|
||||
`crates/vfmt_server/tests/e2e.rs::a_macro_call_hover_carries_its_single_step_expansion_over_the_wire`
|
||||
was also run and pins a whole card byte for byte
|
||||
(`` `define MAX(a, b) ((a) > (b) ? (a) : (b))`` / `` `MAX(p, q + 1)`` →
|
||||
`((p) > (q + 1) ? (p) : (q + 1))``) — both independently green.
|
||||
|
||||
**7. Version/CHANGELOG accuracy — PASS, one informational note.** Delegated
|
||||
the M7–M13 CHANGELOG-vs-README cross-check (M14 itself I read directly, see
|
||||
above) to a second pass reading each of the seven earlier feature READMEs'
|
||||
Goal/Assumptions/Status-TODO/Work-log sections against the corresponding
|
||||
CHANGELOG subsection. Result: no blocking mismatch, every claimed capability
|
||||
matches a `[x]` in its README, "off by default" for the three semantic lints
|
||||
confirmed word-for-word, no section claims something its README doesn't
|
||||
support. One informational-only gap: the `file-watching` (M9) subsection
|
||||
states index rebuilding on external change without noting the README's
|
||||
Assumptions caveat that this needs the client to advertise
|
||||
`didChangeWatchedFiles.dynamicRegistration` (true of both shipped clients,
|
||||
VS Code and Neovim, so not a functional overclaim for any real user, just
|
||||
missing nuance). Not fixed — a CHANGELOG entry is prose the lead owns, and
|
||||
this isn't wrong, just less complete than the README.
|
||||
|
||||
**8. Test counts — all confirmed by direct execution**, not by trusting the
|
||||
work log: `expand.rs` 18 unit tests (counted directly, matches), `hover.rs`
|
||||
+8 tests (counted the diff's new `#[test]` functions, matches), +1 e2e
|
||||
(`a_macro_call_hover_carries_its_single_step_expansion_over_the_wire`,
|
||||
confirmed present and green), 1583 total workspace (summed every `test
|
||||
result: ok` line myself rather than trusting the printed total).
|
||||
`vfmt_server`'s own count (498 unit + 27 e2e + 3 grammar = 528, from
|
||||
`docs/features/vfmt-server/README.md`'s work log) reproduced exactly with a
|
||||
clean tree; it read 510 while my 12 temporary QA tests were still present
|
||||
(510 − 12 = 498), which is itself a small confirmation the base count is
|
||||
honest rather than coincidental.
|
||||
|
||||
**9. Scope — PASS.** `git status --short` after this QA pass is identical to
|
||||
the dev's own hand-off list (`CHANGELOG.md`, `Cargo.lock`, `Cargo.toml`,
|
||||
`README.md`, `hover.rs`, `main.rs`, `e2e.rs`, both `README.md`s under
|
||||
`docs/features/`, `editors/vscode/README.md`, both vscode `package*.json`,
|
||||
`tools/RELEASING.md` modified; `expand.rs` and
|
||||
`docs/features/macro-expansion/` new) — no stray file left behind by any QA
|
||||
probe. `TODO.md` and the umbrella README untouched, as instructed.
|
||||
|
||||
### Summary
|
||||
|
||||
No blocking findings. No corruption, no panic, no hang, no false expansion
|
||||
and no false "no section" found across 13 targeted attacks on the honesty
|
||||
core (`replace_names`/`split_arguments`/`split_parameter`), the M10-narrowing
|
||||
consistency claim held under an independent binary-diff, the empty-arg-
|
||||
default claim checks out structurally against `Define`, and the whole-card
|
||||
e2e round trip is byte-for-byte over the real wire from a second, independent
|
||||
client. One informational-only CHANGELOG nuance (file-watching's client-
|
||||
capability precondition), not fixed since it isn't inaccurate, just less
|
||||
complete than its README.
|
||||
|
||||
**Verdict: ship.**
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-25 — lead.** Reviewed after QA's clean ship verdict — the run's
|
||||
third first-pass; gates run independently (1583 tests, 0 failures). The
|
||||
design's honesty core is `single_step` being blind to lookup: it expands
|
||||
the definition the card already chose, so the two can never disagree, and
|
||||
QA's byte-identical diff against a pre-M14 binary for the
|
||||
multiple-candidate card proves the addition is purely additive. The
|
||||
skip-list (strings, nested `` `NAME``, `` `" `` markers, escaped
|
||||
identifiers) held under thirteen attack tests, including the
|
||||
self-referential macro and the cap-boundary multibyte char. The
|
||||
empty-argument-takes-default deviation is accepted — verified against
|
||||
what `Define::params` actually records, it reads the source rather than
|
||||
guessing. One step means one step, pinned by test. Accepted; M14 and the
|
||||
0.5.0 bump close the M7–M14 run.
|
||||
|
||||
@@ -174,7 +174,7 @@ built but nothing consumes yet. Ordered by value ÷ cost:
|
||||
- [x] **CLI `-f` filelist flag** — the vfmt.toml `filelist` key and the
|
||||
server consume M1's parser; `vfmt -f files.f` (format/lint exactly the
|
||||
project's files) still does not exist.
|
||||
- [ ] **Single-step macro expansion on hover** — the define-table README
|
||||
- [x] **Single-step macro expansion on hover** — the define-table README
|
||||
promised it "later"; hover shows the body but expands nothing.
|
||||
|
||||
Already tracked elsewhere, deliberately not duplicated here: the
|
||||
@@ -268,6 +268,7 @@ commit — in order:
|
||||
- [x] M11 hierarchy — done, QA doc-fixes in-round, reviewed
|
||||
- [x] M12 semantic-lints — done, one QA medium reworked, reviewed
|
||||
- [x] M13 cli-filelist — done, QA clean first pass, reviewed
|
||||
- [x] M14 macro-expansion — done, QA clean first pass, reviewed; 0.5.0
|
||||
|
||||
## Work log
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ looks like language knowledge in here is a bug or a `Handshake` request.
|
||||
| `textDocument/rangeFormatting` | `vlog_formatter::format_range` | Same edit shape; the LSP `Range`'s *lines* become the engine's `--lines` (round 18) |
|
||||
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, full-text sync |
|
||||
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries |
|
||||
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise |
|
||||
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md` |
|
||||
| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. See `docs/features/include-nav/README.md` |
|
||||
| `textDocument/documentLink` | `includes::IncludeGraph` | One link per **resolvable** `` `include``, covering the quoted path, target already resolved (`resolveProvider: false`). Search order: the including file's own directory, then each `+incdir+` of the configured filelist in order; the `<angled>` form skips the first rung. An include nothing answers to gets no link and no error. Same feature README |
|
||||
| `textDocument/references` | `vlog_refactor::find_references`, else `Semantics::references_of` | Cross-file when the symbol is one the workspace index holds (a module, a package, an exported member, a port); in-file for everything else, which is what keeps a local `wire` off the workspace walk. See `docs/features/references-nav/README.md` |
|
||||
@@ -405,6 +405,19 @@ Two rules that are easy to get wrong and are tested:
|
||||
The snippet is `decl_span` widened to whole lines, so a declaration reads as
|
||||
it was written rather than starting mid-line.
|
||||
|
||||
**A macro card has a second half since M14 (0.5.0).** Under the definition it
|
||||
shows what the hovered *use* expands to in one step — the body with this call's
|
||||
arguments substituted for the parameters — fenced identically, with a footnote
|
||||
when a nested macro use survives the step and another when a long body was cut
|
||||
at 2000 characters. It is offered only where it says something the definition
|
||||
does not: never for a plain object-like macro (whose expansion *is* the body
|
||||
printed above), never when the argument count disagrees with the parameter
|
||||
list, and never when the lookup above listed several candidates, because the
|
||||
expansion must always be of the definition the card is showing. The rules and
|
||||
the non-goals (no nested expansion, no stringification, no preprocessing) are
|
||||
in `docs/features/macro-expansion/README.md`; `crate::expand` holds the code
|
||||
and takes no part in lookup.
|
||||
|
||||
**The fence tag is a contract now (0.4.1).** Every code block this server puts
|
||||
in markdown — both hover snippets and the completion templates' documentation
|
||||
panel — opens ```` ```systemverilog ````, unconditionally, `.v` buffers
|
||||
@@ -480,11 +493,34 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
|
||||
the module hierarchy both directions, modules as the nodes and
|
||||
instantiations as the calls, off a walk shared with the inlay hints.
|
||||
`docs/features/hierarchy/README.md`.
|
||||
- [x] Single-step macro expansion on a hover card (`src/expand.rs`, M14) —
|
||||
`docs/features/macro-expansion/README.md`.
|
||||
- [ ] **Not done:** editor packaging (the VS Code extension and the
|
||||
`lspconfig` snippet are their own TODO.md §6 item).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-25 — dev agent (M14 macro-expansion, 0.5.0)
|
||||
|
||||
- **No new capability, one new module, one card grew a section.**
|
||||
`crates/vfmt_server/src/expand.rs` turns a macro-use token plus the `Define`
|
||||
the card already chose into an "expands to" block; `hover.rs`'s private
|
||||
`define_text` takes the call text as a fourth argument and appends the
|
||||
section when there is one. `server.rs`, `state.rs`, the capability list and
|
||||
every engine crate are untouched.
|
||||
- **`expand` is deliberately blind to lookup.** It never sees the workspace,
|
||||
the index or the include graph — `hover.rs` decides *which* definition is on
|
||||
the card (M10's narrowing) and hands it over, so the expansion can never
|
||||
disagree with the definition printed above it. Where hover lists several
|
||||
candidates it passes no call text, and nothing is expanded.
|
||||
- **The fence contract of 0.4.1 extends to the new block**: ```` ```systemverilog ````,
|
||||
pinned by the e2e round trip, which now asserts a whole macro hover card byte
|
||||
for byte rather than by `contains`.
|
||||
- All eighteen pre-existing hover tests pass with no assertion changed.
|
||||
`cargo test -p vfmt_server`: **528 passed, 0 failed** (498 unit + 27 e2e +
|
||||
3 grammar), up 27. Rules and non-goals:
|
||||
`docs/features/macro-expansion/README.md`.
|
||||
|
||||
### 2026-08-25 — dev agent (M11 hierarchy)
|
||||
|
||||
- **One new capability, two new modules, one lifted walk.**
|
||||
|
||||
@@ -47,14 +47,14 @@ catches "the binary moved" or "the handshake broke" without launching VS Code.
|
||||
```bash
|
||||
npm ci # installs vscode-languageclient (the only dependency)
|
||||
npx @vscode/vsce package
|
||||
code --install-extension vfmt-0.4.2.vsix
|
||||
code --install-extension vfmt-0.5.0.vsix
|
||||
```
|
||||
|
||||
Then reload VS Code and open a `.v`/`.sv`/`.vh`/`.svh` file.
|
||||
|
||||
`tools/release.sh` from the repo root does all of the above (plus the release
|
||||
binaries and checksums) and drops the `.vsix` in `dist/`, so
|
||||
`code --install-extension dist/vfmt-0.4.2.vsix` is the one-command path.
|
||||
`code --install-extension dist/vfmt-0.5.0.vsix` is the one-command path.
|
||||
`editors/vscode/LICENSE` is a copy of the repo's MIT license and is what lets
|
||||
`vsce package` run without `--skip-license`. If you are packaging a fork that
|
||||
dropped `package.json`'s `repository` field, add `--allow-missing-repository`.
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "vfmt",
|
||||
"version": "0.4.2",
|
||||
"version": "0.5.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "vfmt",
|
||||
"version": "0.4.2",
|
||||
"version": "0.5.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"vscode-languageclient": "9.0.1"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "vfmt",
|
||||
"displayName": "vfmt — Verilog/SystemVerilog",
|
||||
"description": "Formatting, diagnostics, navigation and semantic highlighting for Verilog and SystemVerilog, served by the vfmt language server.",
|
||||
"version": "0.4.2",
|
||||
"version": "0.5.0",
|
||||
"publisher": "REPLACE-ME",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
|
||||
+10
-10
@@ -61,9 +61,9 @@ recreated on every run.
|
||||
|
||||
```
|
||||
dist/
|
||||
vfmt-0.4.2-aarch64-apple-darwin
|
||||
vfmt-server-0.4.2-aarch64-apple-darwin
|
||||
vfmt-0.4.2.vsix
|
||||
vfmt-0.5.0-aarch64-apple-darwin
|
||||
vfmt-server-0.5.0-aarch64-apple-darwin
|
||||
vfmt-0.5.0.vsix
|
||||
SHA256SUMS
|
||||
```
|
||||
|
||||
@@ -113,11 +113,11 @@ npx @vscode/vsce package --out ../../dist/vfmt-<version>.vsix
|
||||
|
||||
```bash
|
||||
# the CLI and the server: anywhere on PATH
|
||||
install -m 755 dist/vfmt-0.4.2-aarch64-apple-darwin ~/.local/bin/vfmt
|
||||
install -m 755 dist/vfmt-server-0.4.2-aarch64-apple-darwin ~/.local/bin/vfmt-server
|
||||
install -m 755 dist/vfmt-0.5.0-aarch64-apple-darwin ~/.local/bin/vfmt
|
||||
install -m 755 dist/vfmt-server-0.5.0-aarch64-apple-darwin ~/.local/bin/vfmt-server
|
||||
|
||||
# the editor extension: sideload, no marketplace involved
|
||||
code --install-extension dist/vfmt-0.4.2.vsix
|
||||
code --install-extension dist/vfmt-0.5.0.vsix
|
||||
```
|
||||
|
||||
Publishing the artifacts is a matter of attaching `dist/`'s contents plus
|
||||
@@ -125,8 +125,8 @@ Publishing the artifacts is a matter of attaching `dist/`'s contents plus
|
||||
gate is green:
|
||||
|
||||
```bash
|
||||
git tag -a v0.4.2 -m 'vfmt 0.4.2'
|
||||
git push origin v0.4.2
|
||||
git tag -a v0.5.0 -m 'vfmt 0.5.0'
|
||||
git push origin v0.5.0
|
||||
```
|
||||
|
||||
## Appendix — if the owner ever publishes to a marketplace
|
||||
@@ -153,10 +153,10 @@ The commands themselves, once those exist:
|
||||
# VS Code Marketplace: needs an Azure DevOps PAT for the publisher
|
||||
npx @vscode/vsce publish -p "$VSCE_TOKEN"
|
||||
# ... or publish an already-built package
|
||||
npx @vscode/vsce publish --packagePath dist/vfmt-0.4.2.vsix -p "$VSCE_TOKEN"
|
||||
npx @vscode/vsce publish --packagePath dist/vfmt-0.5.0.vsix -p "$VSCE_TOKEN"
|
||||
|
||||
# Open VSX (VSCodium, Gitpod, Cursor): needs an Eclipse Foundation account
|
||||
npx ovsx publish dist/vfmt-0.4.2.vsix -p "$OVSX_TOKEN"
|
||||
npx ovsx publish dist/vfmt-0.5.0.vsix -p "$OVSX_TOKEN"
|
||||
```
|
||||
|
||||
Both tokens are secrets. Neither belongs in this repo, in a shell history, or
|
||||
|
||||
Reference in new issue
Block a user