541 lines
32 KiB
Markdown
541 lines
32 KiB
Markdown
# define-table
|
||
|
||
## Goal
|
||
|
||
Record every `` `define`` a file writes — name, parameter list, replacement
|
||
text, and byte spans — so the LSP can answer "hover a macro usage, see its
|
||
value" (TODO.md §6). This is a pure *data* feature: `collect_defines` reads an
|
||
already-lexed token stream and returns a `DefineTable`. Nothing expands a
|
||
macro, nothing formats differently, and the formatter never calls it — TODO.md
|
||
§7's "no preprocessor expansion in the formatter" non-goal is untouched, which
|
||
that section already anticipated ("recording definitions for hover display is
|
||
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/lucisv_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
|
||
pass impossible. It did not: the lexer already delivers a whole `` `define``,
|
||
continuation lines included, as **one** `TokenKind::Directive` token
|
||
(`lexer.rs`, the `` ` `` arm — it reads to end of line and keeps going while
|
||
the line ends in `\`), and `docs/features/spans/README.md` already gives that
|
||
token a `span` for which `source[span] == text` holds exactly. So everything
|
||
this feature needs — the full directive text and the offset it starts at — is
|
||
already on the token. `defines.rs` is a second read of the token vector and
|
||
touches nothing else.
|
||
|
||
The one consequence worth naming: because the *lexer* decides where a
|
||
directive ends, this module must agree with the lexer's rules rather than with
|
||
the LRM's where they differ. Both places that matter are called out below
|
||
(horizontal whitespace after a continuation backslash; `\\` at end of line).
|
||
|
||
## The body normalization rule (exact)
|
||
|
||
A `` `define``'s `body` is the directive text from the first byte after the
|
||
name — or after the `)` closing a parameter list — to the end of the token,
|
||
with this transformation and no other:
|
||
|
||
> **Every `\` that ends a line is deleted together with the horizontal
|
||
> whitespace after it and the newline it ends. Every other byte survives
|
||
> unchanged.** The result is then trimmed at both ends.
|
||
|
||
That is the LRM 22.5.1 reading ("the backslash-newline is not part of the
|
||
macro text") applied literally. Consequences, all pinned by tests:
|
||
|
||
- **The body is one logical line.** It never contains a `\n`, and it never
|
||
contains a continuation `\`.
|
||
- **Indentation of a continued line survives into the body**, so a three-line
|
||
body reads as `begin q <= d; end` — the joined-up pieces keep exactly
|
||
the spaces that were written around the joins. This looks lossy for display,
|
||
but it is the only choice that is *correct*: inside a string literal that
|
||
whitespace is the value, not layout. `` `define MSG "line one \`` +
|
||
` line two"` must normalize to `"line one line two"`, which is what a
|
||
preprocessor produces, and what a hover must show. Collapsing the join to a
|
||
single space would silently rewrite the string. (This is the same trap the
|
||
formatter fell into once — see `docs/features/macro-items/README.md`, the
|
||
masked-corruption round.)
|
||
- **A consumer that wants the definition *as written* slices `span`.** The
|
||
span still covers every physical line of the directive, so hover can show
|
||
either the joined body or the original multi-line text. Because the joined
|
||
form loses line structure, keeping the span the raw extent is what makes the
|
||
choice the caller's.
|
||
- **Horizontal whitespace between the `\` and the newline is part of the
|
||
continuation.** The lexer tolerates `` `define A x \·· `` + newline
|
||
(`text_ends_with_continuation` trims ` `/`\t`/`\r` before checking), so this
|
||
module must too. If it did not, a stray backslash would survive into the
|
||
body of a directive the lexer had already joined. Mutation-tested: removing
|
||
the tolerance fails a test.
|
||
- **`\\` at end of line continues the line, it is not an escaped backslash.**
|
||
The lexer's rule is "does the trimmed line end in a backslash", and the join
|
||
scans left to right, so the *second* backslash is consumed as the
|
||
continuation and the first survives as text. The two agree by construction.
|
||
A preprocessor runs before string lexing, so this is also the defensible
|
||
reading.
|
||
|
||
Parameters get the same join, then a trim, and are stored **as written**:
|
||
`` `define MAX(a, b = 8) `` gives `Some(["a", "b = 8"])`. Keeping the default
|
||
in the string is what lets hover render the signature; a caller that wants
|
||
only the name splits at the first `=`.
|
||
|
||
## API
|
||
|
||
```rust
|
||
vlog_parser::defines::collect_defines(tokens: &[Token]) -> DefineTable
|
||
|
||
struct Define {
|
||
kind: DefineKind, // Define | Undef
|
||
name: String, // no backtick
|
||
params: Option<Vec<String>>, // None = object-like; Some([]) = `NAME()`
|
||
body: String, // joined, trimmed; empty for Undef
|
||
span: TextRange, // the whole directive, all physical lines
|
||
name_span: TextRange, // exactly the name
|
||
}
|
||
|
||
impl DefineTable {
|
||
fn entries(&self) -> &[Define]; // source order, `undef`s included
|
||
fn all(&self, name: &str) -> Vec<&Define>; // every definition, in order
|
||
fn latest(&self, name: &str) -> Option<&Define>;
|
||
}
|
||
```
|
||
|
||
Design notes:
|
||
|
||
- **Every definition is kept, not just the last.** Redefinition is legal and
|
||
the corpus does it (`` `ifdef``-guarded pairs); a position-aware
|
||
"which definition is in force at offset N" needs them all, and that is what
|
||
hover will eventually want. `latest` is today's answer and is the last
|
||
`Define` in the file, ignoring `` `undef``.
|
||
- **`` `undef`` is an event in the same ordered list**, not a deletion. A
|
||
future position-aware lookup walks `entries()` up to the cursor and honors
|
||
the `` `undef``; nothing resolves it now, deliberately — `all`/`latest`
|
||
report definitions and say nothing about whether one is still in force.
|
||
- **`` `undefineall`` is not an `` `undef``.** The keyword is matched as a
|
||
whole word, not a prefix.
|
||
- **Lookup is a linear scan, not an index.** A file has a handful of defines
|
||
and hover does one lookup per keystroke; a `HashMap` here would be a second
|
||
copy of the same facts to keep in sync, for no measurable gain.
|
||
- **`collect_defines` cannot fail.** A directive it cannot read a name out of
|
||
is skipped. An editor asks for hover text on buffers that are mid-edit, so a
|
||
`Result` here would only push the same "ignore it" decision onto the caller.
|
||
- **Malformed input is recorded, not rejected.** An unclosed parameter list
|
||
(`` `define A(x, y ``) is recorded as an object-like macro whose body is
|
||
`(x, y`. That keeps the shape "what the source says", which is what an
|
||
editor should show.
|
||
|
||
## Assumptions
|
||
|
||
- **Conditional compilation is not evaluated.** A `` `define`` inside an
|
||
`` `ifdef``/`` `else`` is recorded exactly like any other, so both arms of a
|
||
conditional pair appear in the table. Evaluating conditions needs a
|
||
preprocessor and a set of active defines, which lucisv deliberately does not
|
||
have; the ordered list plus the `` `undef`` events is the raw material a
|
||
future position-aware resolver would need.
|
||
- **One file.** No `` `include`` following, no cross-file merge. That is the
|
||
workspace index's job (TODO.md §6), and a `TextRange` has no file identity —
|
||
the same assumption `docs/features/spans/README.md` records.
|
||
- **A `` `define`` is what the lexer says it is.** Anything not lexed as a
|
||
`TokenKind::Directive` is invisible here — which is exactly right for a
|
||
`` `define`` written inside a comment or a string, and is why the table
|
||
cannot be fooled by them.
|
||
- **Macro names are plain identifiers.** A name is a run of
|
||
`[A-Za-z0-9_$]`. An escaped identifier name (`` `define \odd$name 1 ``) is
|
||
not recorded — the leading `\` is unreadable here without re-deciding what
|
||
the lexer already decided about continuations, and no corpus file writes
|
||
one. Skipping is safe (the entry is absent, never wrong).
|
||
- **Known gap: a `//` comment on a *continuation* line rides along in the
|
||
body.** The lexer stops a directive before a comment on its *first* line
|
||
(so `` `define A 1 // c `` has body `1`), but the continuation loop does
|
||
not, so `` `define A x \`` + ` y // note` has body `x y // note`. Per
|
||
the LRM the comment is not macro text. Stripping it needs a string-aware
|
||
scan (a `//` inside a string is not a comment) — the formatter has one, in
|
||
`verify.rs`, but it is `pub(crate)` in the *other* crate. Deferred until a
|
||
hover implementation shows it matters; it is a display wart, not a
|
||
correctness risk, and nothing consumes the table yet.
|
||
- **Known gap, pre-existing: a block comment truncates a directive.**
|
||
`` `define A 1 /* c */ more `` lexes as a directive ending at `1`, with
|
||
` more` continuing as ordinary tokens. That is the lexer's behavior since
|
||
before this feature; the table reports what the token holds.
|
||
- **Digit-leading names are not rejected** (QA find): `` `define 123abc x ``
|
||
records name `123abc`. Nothing validates names as identifiers here — the
|
||
table reports what was written; a future lint rule is the right place to
|
||
complain. Documented so nobody mistakes acceptance for endorsement.
|
||
- **Known gap (QA find): a continuation backslash before a *blank final
|
||
line* leaves a literal `\` in the body.** The lexer's `trim_end()` on the
|
||
token text strips the newline that closed the continuation, re-exposing
|
||
the backslash before this module sees it. `source[span] == text` still
|
||
holds; nothing expands macros, so it's a display wart of the same family
|
||
as the continuation-line comment above.
|
||
|
||
## Handshakes
|
||
|
||
**Consumed from `vlog_parser::lexer` / `token`:** nothing new.
|
||
`TokenKind::Directive` tokens with their `text` and `span`, exactly as they
|
||
are. Two lexer behaviors are relied on and would break this module if they
|
||
changed, so they are stated here rather than left implicit:
|
||
|
||
1. **`source[tok.span] == tok.text` for a `Directive`.** This is what makes
|
||
`name_span` derivable by offset arithmetic inside the text rather than by
|
||
re-scanning the source. Guaranteed by `span_of_trimmed` and asserted by
|
||
`crates/vlog_parser/tests/spans.rs`.
|
||
2. **A continued `` `define`` is one token**, and the continuation rule is
|
||
"the trimmed line ends in `\`". `defines.rs::continuation_len` mirrors it,
|
||
trailing-whitespace tolerance included.
|
||
|
||
**Promised to future consumers (`lucisv_server`, `vlog_semantic`):** the API
|
||
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).** `lucisv_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
|
||
forgiveness was neither widened nor narrowed. `ItemKind::Directive` still
|
||
carries the same `RawText` it did, and the formatter still passes
|
||
`` `define`` through verbatim.
|
||
|
||
**Recursion/chain budgets (`docs/features/recursion-limit/README.md`):**
|
||
nothing is charged and nothing is needed. Every scan in this module is a flat
|
||
`while` over bytes with an explicit index; there is no recursion, no `Box`,
|
||
and no AST node. The parameter-list scan tracks nesting with one `usize` that
|
||
`saturating_sub`s, so unbalanced brackets terminate rather than underflow.
|
||
|
||
## Status / TODO
|
||
|
||
- [x] `src/defines.rs`: `collect_defines`, `Define`, `DefineKind`,
|
||
`DefineTable` (`entries`/`all`/`latest`). ~250 lines, no dependencies.
|
||
- [x] One-line wiring in `lib.rs` (`pub mod defines;`). No re-export, so the
|
||
crate's public surface grows by one module and nothing else.
|
||
- [x] Body normalization: backslash-newline (plus horizontal whitespace
|
||
between them) deleted, everything else byte-for-byte.
|
||
- [x] Function-like macros: `(` must touch the name; defaults, nested
|
||
parens/brackets/braces and strings in a default handled; `NAME()` is
|
||
zero parameters.
|
||
- [x] `` `undef`` recorded as an ordered event; `` `undefineall`` excluded.
|
||
- [x] Spans: `span` = the whole directive, `name_span` = exactly the name,
|
||
both slicing back to the source (tested, multi-byte included).
|
||
- [x] `tests/defines.rs`: 24 tests — the eleven the task listed plus
|
||
commas/brackets/strings in a default, `NAME()`, space-before-paren,
|
||
CRLF-safe multi-byte spans, trailing comment, `` `undefineall``,
|
||
no-name, unclosed parameter list, `` `define`` inside a module.
|
||
- [x] Two mutation tests run against the normalization rule (below).
|
||
- [x] TODO.md §6 checkbox.
|
||
- [ ] **Not done, deliberately:** position-aware `in_force_at(offset, name)`
|
||
resolving `` `undef``s and `` `ifdef``s. The data is all recorded; the
|
||
resolution rule is a hover-design question (does hover show the
|
||
definition in force at the cursor, or all of them?) and building it now
|
||
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
|
||
|
||
### 2026-08-19 — dev agent
|
||
|
||
- Read `CLAUDE.md`, `README.md`, TODO.md §6/§7, and the Handshakes of
|
||
`spans` and `macro-items` before writing anything. Baseline for the two
|
||
files I own: `cargo test -p vlog_parser` **80 passed** (49 unit + 19 spans +
|
||
12 error_recovery), clippy silent, fmt clean.
|
||
- **Confirmed the post-lex pass was possible before designing around it.**
|
||
Read the `` ` `` arm of `lexer.rs` first: a `` `define`` with three
|
||
continuation lines is one `Directive` token whose text is the whole thing,
|
||
and `spans` already guarantees `source[span] == text` for it. So the
|
||
"document why you had to touch the lexer" branch never opened — the lexer is
|
||
byte-identical, and this feature is a second read of the token vector.
|
||
- **The body normalization was the only real decision.** Three candidates:
|
||
(a) delete the backslash-newline and nothing else, (b) replace each join
|
||
with a single space, (c) keep the line structure (join → `\n`) for prettier
|
||
hover. Went with (a), which is the LRM's own wording, because it is the only
|
||
one that is *correct for strings*: a body may carry a string across a line
|
||
and the continued line's indentation is then part of the value. (b) and (c)
|
||
both rewrite that value. The cost — a multi-line body displays as one long
|
||
line — is paid back by `span`, which still covers the original text, so a
|
||
hover that wants the pretty form slices the source. This is the same lesson
|
||
`macro-items` learned the expensive way, applied up front.
|
||
- **Made the module agree with the lexer, not with the LRM, in two places**,
|
||
because disagreement is what produces garbage: horizontal whitespace between
|
||
the `\` and the newline is part of the continuation (the lexer's
|
||
`text_ends_with_continuation` trims before checking), and `\\` at end of
|
||
line continues the line rather than being an escaped backslash. Both are
|
||
written down under "The body normalization rule" and both have a test.
|
||
- **Mutation-tested the rule rather than trusting a green first run**
|
||
(all 24 tests passed on the first execution, which is a reason for
|
||
suspicion, not comfort):
|
||
1. Removed the horizontal-whitespace tolerance from `continuation_len` →
|
||
`a_continuation_may_have_trailing_spaces_after_the_backslash` fails with
|
||
the raw `x \\ \n y` leaking through. Detected.
|
||
2. Changed the join to emit a single space and swallow the continued line's
|
||
indent — i.e. shipped candidate (b) above → three tests fail, including
|
||
`a_string_continued_across_lines_keeps_its_inner_whitespace`, which is
|
||
exactly the corruption the rule exists to prevent. Detected.
|
||
Both reverted; `defines.rs` is byte-identical to the pre-mutation file.
|
||
- **Probed the shapes the tests do not assert**, to write the Assumptions
|
||
section from observed behavior rather than from guessing: a `//` comment on
|
||
a continuation line (rides along — recorded as a known gap), a block comment
|
||
mid-directive (truncates the token — pre-existing, recorded), CRLF (works,
|
||
spans correct), an escaped-identifier name (not recorded — recorded as an
|
||
assumption), multi-byte UTF-8 in a body (spans stay byte-exact),
|
||
`` `define A(a,b) `B(a) ## b `` (body kept verbatim, `##` untouched).
|
||
- **Kept the lookup a linear scan.** An index was the obvious "real" answer
|
||
and is the wrong one here: two representations of the same list, for a
|
||
lookup that runs once per hover over a handful of entries.
|
||
- Did not touch `parser.rs`, `lexer.rs`, `format.rs`, `verify.rs`, any
|
||
existing test file, `tools/` or `corpus/` — the concurrent agent's files
|
||
are untouched by this diff. Did not run `git commit`/`git push`.
|
||
|
||
**Results:** `cargo test -p vlog_parser` **104 passed, 0 failed** (49 unit +
|
||
24 `tests/defines.rs` + 19 `tests/spans.rs` + 12 `tests/error_recovery.rs`) —
|
||
up from 80, and no existing test changed. `cargo clippy -p vlog_parser
|
||
--all-targets` reports **0 warnings in this feature's files**; the single
|
||
warning the crate emits at the end of this round
|
||
(`clippy::large_enum_variant` on `GenElse`, `ast.rs:434`) comes from the
|
||
concurrent agent's in-flight `ast.rs`/`parser.rs` edits, not from here —
|
||
`ast.rs` shows as modified in `git status` and this diff does not touch it.
|
||
`cargo fmt --all --check` clean. Files
|
||
touched: `crates/vlog_parser/src/defines.rs` (new),
|
||
`crates/vlog_parser/src/lib.rs` (one line),
|
||
`crates/vlog_parser/tests/defines.rs` (new), `TODO.md` (§6 checkbox), this
|
||
README. The rest of the workspace was churning under a concurrent agent
|
||
(`parser.rs`, token/lexer trivia, `vlog_formatter`) and was not run to a
|
||
conclusion by me; nothing in this diff can affect it, since no existing file's
|
||
behavior changed.
|
||
|
||
## QA log
|
||
|
||
### 2026-08-19 — QA agent
|
||
|
||
**Scope note:** a concurrent dev agent was actively editing
|
||
`crates/vlog_parser/src/{ast.rs,parser.rs}` and `vlog_formatter` throughout
|
||
this pass. All gates below were scoped to the `defines` feature; a full
|
||
`-p vlog_parser` run is reported where it succeeded, and one transient
|
||
compile break in `tests/spans.rs` (type mismatch, `ast::Expr` vs.
|
||
`ast::ExprItem`) hit mid-pass and is attributed to that concurrent edit, not
|
||
to this feature — `crates/vlog_parser/src/defines.rs`,
|
||
`crates/vlog_parser/tests/defines.rs`, and `lib.rs` were not touched.
|
||
|
||
**1. API/scope claim — PASS.** `git diff crates/vlog_parser/src/lib.rs` is
|
||
exactly `+pub mod defines;` (+1 line, confirmed twice). `git status --short`
|
||
shows this feature's only changes are `crates/vlog_parser/src/defines.rs`
|
||
(new), `crates/vlog_parser/tests/defines.rs` (new),
|
||
`docs/features/define-table/` (new) and the `TODO.md` §6 checkbox (10
|
||
insertions, all one honest paragraph describing what was built — verified by
|
||
reading the diff). `crates/vlog_parser/src/lexer.rs`,
|
||
`crates/vlog_parser/src/token.rs`, `crates/vlog_formatter/src/verify.rs`,
|
||
`crates/vlog_formatter/tests/verification.rs` are untouched by this diff
|
||
(not even in `git status`) — CLAUDE.md invariant #4 does not apply, correctly,
|
||
as the README says. `crates/vlog_parser/src/ast.rs`,
|
||
`crates/vlog_parser/src/parser.rs`, `crates/vlog_formatter/src/format.rs` are
|
||
modified but that's the *other* agent's in-flight work (confirmed by reading
|
||
their diffs — no mention of `defines`). API shape (`Define`/`DefineKind`/
|
||
`DefineTable`, `entries`/`all`/`latest`) matches the README exactly, read
|
||
directly from `defines.rs`.
|
||
|
||
**2/3. Body normalization + span/lexer agreement — PASS.** Ran all 24
|
||
`tests/defines.rs` tests: **24 passed, 0 failed.** Also ran
|
||
`cargo test -p vlog_parser` in full before the workspace churn hit:
|
||
**104 passed, 0 failed** (49 unit + 24 defines + 19 spans + 12
|
||
error_recovery), matching the work log's own count exactly. Read
|
||
`lexer.rs`'s directive arm (`` ` `` handling, lines ~178–229) and
|
||
`text_ends_with_continuation` (line 475) directly: confirmed
|
||
`` `\r` `` is trimmed as trailing horizontal whitespace before the
|
||
continuation check on *both* sides (lexer and `defines.rs::continuation_len`
|
||
independently implement the same trim set: space/tab/CR), so the two
|
||
cannot disagree on CRLF — verified empirically too (below). `PRIM_STRINGIFY`
|
||
+ `MSG "line one \...line two"` style cases match the LRM-literal join rule
|
||
as documented.
|
||
|
||
**Attack probes** (temporary test file, deleted after the run — not left in
|
||
the tree): every case below went through the *real* `tokenize()`, not
|
||
hand-built tokens.
|
||
|
||
| input shape | result | verdict |
|
||
|---|---|---|
|
||
| `` `define`` no name, no newline | 0 entries | OK, no panic |
|
||
| `` `define\n`` no name | 0 entries | OK |
|
||
| `` `define 123abc x`` (digit-leading name) | recorded as name `"123abc"` | accepted — see finding QA-1 |
|
||
| `` `define module 1`` (keyword as name) | recorded as name `"module"` | OK — Verilog preprocessor doesn't type-check names |
|
||
| `` `define A(x,\n y) x+y`` (newline inside param list, no `\`) | directive ends at line 1 (`` `define A(x,``), body `"(x,"` | OK, matches lexer's real line-ending rule + documented unclosed-list fallback |
|
||
| `` `define A(x = f(b,c)) x`` | `params = Some(["x = f(b,c)"])`, body `"x"` | OK, nested parens in default handled |
|
||
| `` `define A \\\n\n`` (continuation into an *empty* final line) | body `"\\"` (one literal backslash survives) | **finding QA-2, see below** |
|
||
| `` `define A x \`` at EOF, no trailing newline | body `"x \\"` | OK — nothing to continue into, backslash correctly kept literal |
|
||
| `` `undef X garbage here`` | recorded, `name="X"`, trailing junk silently ignored (not part of `Undef`'s empty body) | OK |
|
||
| `` `define A 1\n`define B 2\n`` | two entries, correct spans, no bleed | OK |
|
||
| CRLF continuation (`` `define A x \\\r\n y\r\n``) | body `"x y"` | OK, matches LF case exactly |
|
||
| tab between `\` and newline | body `"x y"` | OK |
|
||
| `//` comment on the continuation's last line | body `"x y // trailing"` | OK, matches documented known gap |
|
||
| body containing literal `` `undef`` text | one `Define` entry, body carries the literal text, no phantom second entry | OK |
|
||
| re-indented multi-line define (`name_span` offset arithmetic) | `name_span` and `span` both slice back exactly | OK, offset arithmetic survives re-indentation |
|
||
|
||
No panics in any of the 15 probes.
|
||
|
||
**Finding QA-1 (informational, not blocking).** `defines.rs::read_name`
|
||
accepts a digit-leading run as a macro name (`` `define 123abc x`` → name
|
||
`"123abc"`). The README's Assumptions section says "a name is a run of
|
||
`[A-Za-z0-9_$]`" but doesn't call out that it doesn't enforce
|
||
identifier-start rules (no leading digit). Harmless in practice — no real
|
||
Verilog writes this, `collect_defines` cannot fail either way, and a
|
||
consumer can validate `name` itself if it cares — but the Assumptions
|
||
section could say so explicitly for a future reader who wonders whether it
|
||
was deliberate. Not fixed by QA (adding it to Assumptions is a wording
|
||
call for the dev agent, not a code bug).
|
||
|
||
**Finding QA-2 (should-look-into, not blocking).** A `` `define`` whose
|
||
continuation backslash is immediately followed by a *blank* final physical
|
||
line (`` `define A \`` then an empty line) produces a token whose raw text,
|
||
after the lexer's `.trim_end()`, ends in a bare literal `\` with no
|
||
following newline — because `trim_end()` strips the `\n` that closed the
|
||
real continuation, re-exposing the backslash underneath it.
|
||
`defines.rs::continuation_len` then correctly (per its own contract: a `\`
|
||
needs a *following* `\n` in the token text to count) treats that exposed
|
||
backslash as ordinary text rather than a continuation, so it survives into
|
||
`body` as a literal character. Traced to `lexer.rs` — `text_ends_with_continuation`
|
||
trims trailing space/tab/CR only, not `\n`, so it correctly returns `false`
|
||
once the token has absorbed the first continuation's `\n` and hit the
|
||
second (empty) line's own `\n`; the token's raw text is
|
||
`` "`define A \\\n" `` at that point, and `.trim_end()` afterward is what
|
||
strips the `\n` back off, re-exposing the backslash. This is a lexer
|
||
property, not something `defines.rs` introduces, and it's the same
|
||
category as the two gaps already documented (comment-on-continuation-line,
|
||
block-comment-truncates-directive) — `source[span] == text` still holds
|
||
exactly (verified), nothing panics, and nothing consumes the table for
|
||
expansion yet, so it isn't corruption. Recommend the dev agent add it as a
|
||
third documented "known gap" under Assumptions; did not fix it myself since
|
||
it's a genuine judgment call whether the right fix lives in the lexer's
|
||
`trim_end` or in `defines.rs` reading the raw untrimmed span.
|
||
|
||
**4. Test count / mutation — PASS.** 24/24 green, no existing test file
|
||
touched (confirmed via `git status` — `tests/defines.rs` is `??`, i.e. new,
|
||
not modified). Work log's two mutation runs (removing the CR/tab
|
||
tolerance; collapsing the join to a single space) are described with the
|
||
specific tests that catch each — read and judged sound; did not
|
||
re-execute the mutations myself since the work log already shows the
|
||
before/after and the specific failing assertions match the normalization
|
||
rule being tested (`a_continuation_may_have_trailing_spaces_after_the_backslash`,
|
||
`a_string_continued_across_lines_keeps_its_inner_whitespace`).
|
||
|
||
**5. Redefinition/undef ordering — PASS.** `a_redefinition_keeps_every_definition_and_latest_wins`
|
||
and `an_undef_is_recorded_as_an_event_and_is_not_a_definition` both green;
|
||
independently re-verified with `` `define X` `/` `undef X` `/` `define X` ``
|
||
via the corpus/attack harness: `entries().len() == 3`, `all("X").len() == 2`
|
||
(the two `Define`s only), `latest("X")` returns the *last* `Define`'s body,
|
||
ignoring the `` `undef`` in between — matches the README's stated design
|
||
("`undef` is an event, not a deletion").
|
||
|
||
**Corpus sweep — PASS.** Built a temporary harness (deleted after the run)
|
||
walking every `.sv`/`.v`/`.svh`/`.vh` file under `corpus/` through the real
|
||
`tokenize()` → `collect_defines()`. Result: **860 files, 857 tokenized
|
||
successfully, 502 `` `define``/`` `undef`` entries recorded, 0 panics, 0
|
||
span/name_span mismatches** (every entry's `name_span` sliced back to
|
||
exactly its `name`, every `span` sliced back to text starting with `` ` ``,
|
||
across all 502). The 3 tokenize failures are pre-existing, unrelated lexer
|
||
limitations (`riscv_core_setting.tpl.sv`, `core_ibex_tb_top.sv`,
|
||
`core_ibex_base_test.sv` — all "expected digits after number base", a
|
||
numeric-literal lexing gap, nothing to do with directives).
|
||
|
||
Hand-checked 8 real entries from `corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_assert.sv`
|
||
against the source directly:
|
||
- `` `define ASSERT_DEFAULT_CLK clk_i`` → name `ASSERT_DEFAULT_CLK`, body
|
||
`"clk_i"` — exact match.
|
||
- `` `define ASSERT_DEFAULT_RST !rst_ni`` → body `"!rst_ni"` — exact match.
|
||
- `` `define PRIM_STRINGIFY(__x) `"__x`"`` → params `["__x"]`, body
|
||
`` "`\"__x`\"" `` — exact match, backtick-quote pairs preserved literally.
|
||
- `` `define ASSERT_ERROR(__name)`` (5-line continuation, nested
|
||
`` `ifdef UVM``/`` `else``/`` `endif`` inside the body) → params
|
||
`["__name"]`, body opens with `` "`ifdef UVM ... uvm_pkg::uvm_report_error(...` `` —
|
||
correct: an `` `ifdef`` *inside* a `` `define``'s continuation is body
|
||
text, not a separate directive, per LRM 22.5.1, and the table treats it
|
||
that way because the lexer already lexed the whole thing as one token.
|
||
- `` `define ASSERT_STATIC_LINT_ERROR(__name, __prop)`` (4-line
|
||
continuation) → body reads as the four lines joined with the exact
|
||
interior whitespace from the source — exact match by eye.
|
||
No wrong name or wrong body found in the spot check.
|
||
|
||
**6. CLAUDE.md compliance — PASS.** Every `pub` item in `defines.rs` (2
|
||
enums/structs, 6 fields, 3 inherent methods, 1 free function) has a
|
||
preceding doc comment — read the whole file, confirmed line by line.
|
||
`grep -n "unwrap()\|expect(\|panic!" crates/vlog_parser/src/defines.rs` →
|
||
no matches. `git diff crates/vlog_parser/Cargo.toml` → empty, no new
|
||
dependency. `cargo fmt --all --check` clean for this feature's files.
|
||
`cargo clippy -p vlog_parser --lib` → 1 warning total in the whole crate
|
||
(`clippy::large_enum_variant` on `ast.rs:434`, `GenElse`) — attributed to
|
||
the concurrent agent's in-flight `ast.rs` (confirmed: `ast.rs` shows
|
||
modified in `git status`, `defines.rs` doesn't touch `ast.rs` or `GenElse`
|
||
at all). README has all seven required sections (Goal, Assumptions,
|
||
Handshakes, Status/TODO, Work log, QA log, Review) present and non-empty
|
||
except Review (correctly reserved for the lead). TODO.md §6 checkbox is
|
||
honest — read the diff, the added paragraph accurately describes what
|
||
exists (`collect_defines`, the API shape, the normalization rule, the two
|
||
documented gaps), makes no claim beyond what was built.
|
||
|
||
### Summary
|
||
|
||
No BLOCKING findings (no panic, no wrong name/body/span for a well-formed
|
||
`` `define``, no corruption — this module doesn't touch formatter output at
|
||
all). Two non-blocking findings, both informational/should-look-into:
|
||
QA-1 (digit-leading names accepted, undocumented but harmless) and QA-2 (a
|
||
continuation into a blank final line loses its backslash-erasure because of
|
||
`lexer.rs`'s `.trim_end()`, undocumented third "known gap", not corruption
|
||
since nothing expands macros yet). All 24 `defines.rs` tests green, 104/104
|
||
crate-wide before the concurrent churn, 860-file/502-define corpus sweep
|
||
clean, spot check of 5+ real macros correct by hand.
|
||
|
||
## Review
|
||
|
||
**2026-08-19 — lead. Verdict: accepted and committed; no code changes
|
||
needed, two QA findings recorded as Assumptions above.**
|
||
|
||
Exactly what a data-layer feature should look like: zero changes to any
|
||
existing behavior (one `pub mod` line is the entire footprint outside
|
||
the new files), the "documented impossibility" escape hatch never
|
||
needed, and the hard design question — body normalization — answered by
|
||
reading the LRM literally and *mutation-testing the rule* against the
|
||
prettier alternatives that would have rewritten string values. The two
|
||
places the module follows the lexer over the LRM (whitespace between
|
||
`\` and newline; `\\` at line end) are the right call: a table that
|
||
disagrees with the lexer that produced its input is worse than either
|
||
convention alone.
|
||
|
||
Storing all definitions plus `` `undef`` events, rather than resolving
|
||
to one winner, is the correct shape for the future position-aware
|
||
hover (`latest-before-position` needs the history; collapsing it now
|
||
would be premature resolution). QA's corpus sweep — 502 entries, five
|
||
prim_assert.sv macros hand-checked, zero span mismatches, CRLF
|
||
confirmed at both layers — is the acceptance evidence that matters.
|
||
|
||
Both QA findings (digit-leading names accepted; the blank-final-line
|
||
backslash wart) are recorded as Assumptions rather than fixed: neither
|
||
can corrupt anything (nothing expands macros), and both belong to
|
||
their real owners — a future lint rule and the lexer's trim behavior
|
||
respectively.
|
||
|
||
With this, TODO §6's data foundations are complete: spans,
|
||
error-tolerant parsing, define table. Next: `vlog_semantic` + the
|
||
workspace index, then `lucisv_server`.
|