27 KiB
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:
- Expanding the nest is preprocessing. It needs a definition set, which
needs the conditional-compilation state, which lucisv deliberately does not
have (
define-table's Assumptions:`ifdefarms 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. - It terminates by construction. No recursion, no depth counter, no cycle
check —
`define A `Ais one substitution pass over one body, so the recursion budget indocs/features/recursion-limit/README.mdis 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) |
ab `` |
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 (
`MAXwhereMAXtakes two parameters). Legal to write, nothing to substitute. - A parameter that is not a plain identifier.
defines.rsrecords 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 `includes. 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.
`ifdefinside a body is body text, asdefine-tablealready 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.rsis 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_macrosays so in its own doc comment, andlexer.rs::scan_macro_argsis 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.rsreads 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
crates/lucisv_server/src/expand.rs(new, ~250 lines with tests):single_step,has_macro_use,CAP,Expansion. No dependencies.- Argument splitting on top-level commas, mirroring
read_params(nesting, strings, comments,`NAME()= zero arguments). - Whole-name substitution with strings,
`"/``, nested macro names and escaped identifiers passed through. - Empty argument takes the parameter's declared default.
- Count mismatch / no argument list / non-identifier parameter → no section.
- Object-like macro: section only when the body holds a macro use.
- Expansion follows the definition the card shows; several candidates → no section.
- 2000-character cap with an ellipsis and a note.
hover.rs: the expands to section, the one-step footnote, the truncation footnote;define_texttakes the call.- Tests: 18 unit tests in
expand.rs, 8 inhover.rs, 1 e2e stdio round trip pinning the exact card. All pre-existing hover tests unchanged. - Version 0.5.0 across the workspace and the extension;
CHANGELOG.mdentry covering M7–M14. define-table's promise annotated as kept;lucisv-server's hover row updated.- Not done, deliberately: expanding the nest (see "One step"),
stringification/paste semantics, and a
`definechosen by cursor position rather than by "last definition in the file" — that last one isdefine-table's own openin_force_atitem and belongs there.
Work log
2026-08-25 — dev agent
- Read
CLAUDE.md, thedefine-table,include-navandlucisv-serverREADMEs,hover.rs,defines.rsand the lexer's`arm before writing anything. Baseline:cargo test --workspace1556 passed, 0 failed; clippy silent; fmt clean. - Put the logic in a module of its own (
expand.rs) rather than inhover.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 aWorkspace. - The hard decision was what "one step" excludes, and it was decided by
what lucisv already refuses to know. Expanding a nested
`INNERwould need a definition set resolved through conditional compilation;define-tablerecords both`ifdefarms 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_STRINGIFYshow__xfor every call),``(both halves substitute; the paste itself is not performed),`INNER(skipped whole, which is also what stops a parameter namedxfrom being substituted inside`x), and\escaped$id(skipped to whitespace). Each row of the table has a test. - Mirrored
defines.rs::read_paramsfor 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 inan_empty_argument_takes_the_parameters_default. - Empty argument → declared default was added after writing the mismatch
rule and noticing
`M(1, )would otherwise render1 +, 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 inqa_findings) pass with no assertion changed: the new section is appended after the closing fence, so everycontains(...)on the definition still holds, and the two macro cases they exercise are the two that gain nothing —`define WIDTH 8is 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(viacargo check --workspace),editors/vscode/package.json,editors/vscode/package-lock.json(both places),tools/RELEASING.md's examples,README.mdandeditors/vscode/README.md's install lines — the same listtools/RELEASING.md§1 names.CHANGELOG.mdgained 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 touchTODO.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/lucisv-server: smoke: OK.
npx @vscode/vsce ls (in editors/vscode/): exit 0, manifest accepted.
lucisv --version → lucisv 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 lucisv-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.svhdefines`define M(x) x + 1, onlya.svhis`included. Hovering`M(7)showsdefined 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) andb.svh(x + 2) included, so the lookup lists both candidates. Builtlucisv-serverat HEAD (36ddaba, pre-M14, viagit stash push -u/git stash poparound the build — working tree restored immediately after, confirmed viagit status --shortmatching the pre-stash listing exactly) and at the current M14 tree, ran the identical hover request against both binaries, anddiff'd the two markdown outputs: byte-identical. This also follows directly from reading thehover.rsdiff — the only change todefine_textis oneif let Some(expansion) = call.and_then(...)block appended after the existing render, and the multi-candidate call site passescall = 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/lucisv_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).
lucisv_server's own count (498 unit + 27 e2e + 3 grammar = 528, from
docs/features/lucisv-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.mds 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.