Files
lucisv/docs/features/bind/README.md
T
lucioandClaude Fable 5 81df63d942 Bind semantics, the spaced macro call and the directive inside a connection, and lucisv.instantiate
TODO section 26; closes docs/topo.md 2.9-15 and 2.9-19; coverage_gaps
M4/M5/M6 corrected against a fresh opentitan census.
A bind directive's target is a path of segments with optional indices
(bind top.gen[0].u_core chk u_chk (...)); a lone target binds as a
module reference, an instance path records nothing rather than a guess.
Each connection's port half resolves against the module being bound in
and its expression half in the target module's scope first, the
workspace's member path when the target lives elsewhere, the writing
scope last (Target::BindScope, resolve::in_bind_target - the
inline-constraint shape). FACTS_FORMAT 14 -> 15: binds now post
references and an instantiation edge.
Expression-position spaced macro calls (assign x = `WIDTH (a + b);)
keep the author's gap, read from the source as glued_null_item reads
its gap; verify.rs untouched, both pins stand. A conditional directive
inside a connection value becomes ExprKind::Verbatim, byte-exact
through raw_inline as Doc::Inline, with the closing paren's line and
the list's break read from the source - so the instantiation keeps its
edge, lens and port references instead of collapsing to opaque bytes
(opentitan: the two padring sites in chip_earlgrey_{asic,cw340}.sv,
+2 edges, everything else byte-identical to 0.31.0).
lucisv.instantiate [uri, position, module] renders the inline ghost's
plan as plain text through workspace/applyEdit for clients without
inline completion; the Neovim README documents it.
QA: 3186 tests / 47 binaries, corpus 814/820, independent binary diff
over corpus and 2 645 opentitan files: only the two named files differ.

docs/features/bind-semantics/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 13:15:21 -07:00

333 lines
20 KiB
Markdown

# bind
## Goal
Parse and format the SystemVerilog `bind` directive (IEEE 1800-2017 §23.11) —
the second-largest parse blocker in the corpus after `interface`, at 28 files.
A directive is
```
bind <target_scope> [ : <instance_list> ] <module_name> [ #( <overrides> ) ] <inst_name> ( <ports> );
```
where `<target_scope>` is a module identifier, an interface identifier or an
instance name, and **everything after it is exactly an ordinary module
instantiation**. That is the whole design point: `bind` reuses the existing
`Instantiation` node and the existing `Instantiation` layout code unchanged, so
a bound instantiation is laid out byte-for-byte the way the same instantiation
written on its own would be — same `#( )` override group, same instance name,
same connection-list group, same alignment inference for named connections.
## What is structural, and what is verbatim
All structural — a real `ItemKind::Bind(BindDirective)` node with a canonical
layout. Nothing is captured verbatim, no new normalization was needed, and
`crates/vlog_formatter/src/verify.rs` is untouched.
| shape | corpus evidence |
|---|---|
| target on one line, module + instance on the next, implicit named connections (`.clk_i,`) | `corpus/ibex/vendor/lowrisc_ip/ip/prim/fpv/tb/prim_secded_22_16_bind_fpv.sv:9` (+19 sibling `prim_secded_*_bind_fpv.sv` / `prim_alert_rxtx*_bind_fpv.sv` files) |
| with `#( ... )` parameter overrides on the wrapped line | `corpus/ibex/vendor/lowrisc_ip/ip/prim/fpv/tb/prim_esc_rxtx_bind_fpv.sv:8` |
| target is an **instance** name, directive inside a module | `corpus/ibex/vendor/lowrisc_ip/ip/prim/fpv/tb/prim_fifo_sync_bind_fpv.sv:17` (12 directives in that one file) |
| `.*` connection list | `corpus/ibex/dv/uvm/core_ibex/fcov/core_ibex_fcov_bind.sv:6` |
| `#(` glued to the module name (`iface#(`) | `corpus/ibex/dv/uvm/icache/dv/fcov/ibex_icache_fcov_bind.sv:8` |
| **implicit named parameter overrides** (`.SecureIbex,` with no parens) + a hand-aligned connection table | `corpus/ibex/dv/verilator/simple_system_cosim/ibex_simple_system_cosim_checker_bind.sv:6` |
| two directives at module scope, blank line kept between them | `corpus/opentitan/hw/ip/uart/dv/sva/uart_bind.sv:7,16` |
| directive at **top level**, outside any module | `corpus/common_cells/formal/counter_properties.sv:96`, `fifo_v3_properties.sv:134`, `fall_through_register_properties.sv:84` (these three still fail on a *later* blocker, `assume` — category `assertions`, not mine) |
**Verified already parsing, no work needed:** implicit named parameter
overrides `#(.SecureIbex, .ICache)`, `#(` with no preceding space, and `.*` all
went through the existing `parse_connection` / `parse_instantiation` path
unchanged — checked against the pre-change release binary before writing any
code, so the brief's "check whether the existing `#( )` override parser accepts
`.Name` with no parens" is answered *yes*. A case pins it for a plain
instantiation too (`bind.cases`, "implicit named *parameter* overrides").
## Assumptions
- **`bind` is deliberately NOT added to the lexer keyword table.** It is a
reserved word in IEEE 1800 Table B.1, but promoting it would break
`obj.bind()` and `x = obj.bind`, because member access after `.` requires a
`TokenKind::Ident` (`parser.rs`, `self.nth(1).kind == TokenKind::Ident`).
This follows the call the codebase already makes for `new`/`this`/`super`
(see the comment in `token.rs::is_keyword`). A directive is recognized
instead by shape, in `Parser::at_bind_directive`: the word `bind`, then a
target scope (a name, optionally a `.`-separated hierarchical path, each
segment optionally carrying one `[…]` selector since 2026-09-02), then
either the `:` of an instance list or the module name of the instantiation.
A declaration of a variable called `bind` reaches `;`, `,`, `=` or a
dimension at that point, so it never matches — pinned by
`bind_is_still_a_usable_identifier` in `parser.rs`.
A whole-word `grep` over the 820-file corpus found **no** use of `bind` as an
identifier, so this is belt-and-braces rather than a live constraint.
- **Recognition is item-position only.** `at_bind_directive` is consulted from
`parse_item_kind`, so nothing in expression or statement position changes.
- ~~**The target is stored as one glued string** (`top.u_dut.u_core`), the same
way `Instantiation::module` glues `pkg::mod`.~~ — **superseded 2026-09-02 by
bind-semantics**: it is a `Vec<PathSegment>`, one entry per name plus the
`[…]` a segment may carry, because an escaped segment needs the whitespace
that terminates it and a selector is not part of any name.
`BindDirective::target_span` still covers the whole path (separators and
selectors included), so only each *segment's* span slices back to a name —
which is what `tests/spans.rs` now asserts, exactly rather than despaced.
`BindDirective::target_path()` is the joined spelling for a consumer that
wants one.
- **The head is one flat run of names.** `bind <target> `, then the
instantiation. The head never breaks on its own: if the whole directive does
not fit, the instantiation's own groups (`#( )` first, then the connection
list) break exactly as they would without the `bind` prefix. Verified by
formatting the identically wide standalone instantiation and diffing —
same output, and the case comments say so.
- **A `bind` inside a `` `ifdef `` arm needs nothing special**: directives are
pass-through items, so the bind items around them parse normally (case: "an
`` `ifdef `` inside the connection list of a bind" plus a manual check of a
directive-split around whole directives).
## Non-goals (clean parse error, never wrong output)
- ~~**An indexed hierarchical target** — `bind top.u_arr[0].u_core chk u (.*);`.
The path scan stops at `[`, so `at_bind_directive` declines and the file
fails to parse with `expected ';'`.~~ — **delivered 2026-09-02 by
bind-semantics** (`docs/coverage_gaps.md` M6): `BindDirective::target` is a
`Vec<PathSegment { name, span, index }>`, `at_bind_directive` steps over one
`[…]` per segment, and the formatter prints the segments one at a time so an
escaped one keeps its terminating space. Still no corpus or opentitan hit;
the reason to do it was that a formal setup binding SVA into a generate
array is a real shape, not a measured one.
- ~~**`bind` in the config-file/`bind_instantiation` sense of resolving the
target scope.**~~ — **delivered 2026-09-02 by bind-semantics** (`docs/topo.md`
§2.9-15): a lone target name resolves as a module or interface, each
connection's port half against the bound-in module and each expression half
in the target's scope. A hierarchical *instance* path still resolves to
nothing at all, deliberately: it names a place in an elaborated hierarchy
no single file knows.
## Handshakes
### Consumed
- `Parser::parse_instantiation` (`crates/vlog_parser/src/parser.rs`) — the
whole grammar after the target. `parse_bind` calls it and stores the result
verbatim; no fork, no copy.
- `Formatter::instantiation` (`crates/vlog_formatter/src/format.rs`) — the
whole layout after the target, `;` included. `Formatter::bind` emits
`text("bind <target> [: <list>] ")` and then delegates. Every layout
decision listed in the brief (module name, `#(` overrides group, instance
name, connection-list group, alignment inference for named connections)
applies unchanged because none of them is re-implemented.
### Promised / requested
- **`BindDirective::target_comments` / `::module_comments`** (QA round-1 fix):
the comments written between `bind` and the target, and between the target
(or the `: instance, list`) and the module name. Both are plain
`Vec<Comment>` fields, so no consumer had to change; only `Fmt::bind`
reads them.
- **New AST variant `ItemKind::Bind(BindDirective)`** in
`crates/vlog_parser/src/ast.rs`. Two exhaustive matches in other crates
needed an arm; both got the minimal one:
- `crates/vlog_formatter/src/format.rs::item_kind` — delegates as above.
- `crates/vlog_semantic/src/bind.rs::bind_item` — **request for the
vlog_semantic owner, answered 2026-09-02 by bind-semantics**
(`Binder::bind_bind`, `Target::BindScope`, `FACTS_FORMAT` 14 → 15). The
arm this round added recorded *only the instantiated module name*
(`bind_instantiation_module`), so a bind still made the bound module a
resolvable dependency of the file for the workspace index.
It deliberately does **not** declare the instance or resolve the
connections: a bind instantiates into the *target* scope, so the instance
name does not belong to the enclosing scope and the connection
expressions name signals in the target module, not here — resolving them
against the enclosing scope would manufacture bogus unresolved-name
results. Whether the target scope (`b.target`, with `b.target_span`
already recorded for go-to-definition) and the connections should resolve
through the workspace index is a vlog_semantic design decision, not a
parser one.
- `crates/vlog_linter/src/visit.rs`, `vlog_formatter/src/{range,fence}.rs`
match with a wildcard arm and needed no change; a bind is a leaf item for
all three, which is correct (fences and range formatting work at item
granularity).
- `crates/vlog_parser/tests/spans.rs` — the item walker is exhaustive, so a
`Bind` arm was added. The `Instantiation` body was extracted into
`check_instantiation` and is now shared by both arms rather than duplicated.
## Status / TODO
- [x] Baseline score saved before any change (671/820, 81.8%).
- [x] `ItemKind::Bind` + `BindDirective` in `ast.rs`.
- [x] `Parser::at_bind_directive` (shape-based, no new keyword) and
`Parser::parse_bind`.
- [x] `Formatter::bind`, delegating wholesale to `Formatter::instantiation`.
- [x] Minimal arms in `vlog_semantic/src/bind.rs` and `tests/spans.rs`.
- [x] `crates/vlog_formatter/tests/cases/bind.cases` — 18 cases, one per
corpus shape cited above plus the `: instance_list` form, a
hierarchical target, top level, inside `generate`, attached comments,
a `` `ifdef `` inside the connection list, a `verilog_format: off`
fence, both sides of the 100-column boundary, and `obj.bind()`.
- [x] Parser-level tests: `bind_directive_forms`,
`a_bind_directive_wraps_an_ordinary_instantiation`,
`bind_is_still_a_usable_identifier`.
- [x] `cargo fmt --all`, `cargo clippy --all-targets`, `cargo test` all clean.
- [x] Score after: 699/820 (85.2%), passing set a strict superset.
- [x] `TODO.md` and `README.md` updated.
- [x] QA round-1: comments between `bind` and the target, and before the
module name, are preserved (2 cases + 1 parser test).
- [x] 2026-09-02 (bind-semantics): the indexed target and the semantics
request above are both delivered; see
`docs/features/bind-semantics/README.md`.
- [ ] A comment written *inside* the `: instance, list` is still a clean
exit-2 refusal — `instances: Vec<Name>` has no `Meta` and no corpus
file writes one. See the 2026-08-21 work log entry.
## Work log
### 2026-08-20 — dev
- **Baseline.** `cargo build --release && scripts/score.sh` →
`{"passing":671,"total":820,"pct":81.8,"failures_by_category":{"interface":31,"bind":28,"dv-statements":26,"expressions":19,"directive-split":14,"assertions":13,"types-decls":11,"invalid-or-fragment":3,"lex-macro-number":2,"not-verilog":1,"other":1}}`.
TSV saved; all 28 `bind`-category rows are `expected ';' (found "<module>")`,
i.e. the parser was reading `bind <target>` as a data declaration.
- **Keyword decision, made before writing code.** Grepped the whole corpus for
a whole-word `bind`: 64 hits, every one of them a real directive or a
comment — none is an identifier. Then checked the current binary on
`obj.bind(); x = obj.bind;` — it parses today precisely *because* `bind` is
an ordinary `Ident`, and member access after `.` demands `TokenKind::Ident`.
Adding `bind` to `is_keyword` would have broken it, so recognition is
shape-based instead. Recorded in Assumptions with the `new`/`this`/`super`
precedent, and pinned by a parser test and a formatter case.
- **Also checked before writing code:** whether `#(.SecureIbex, .ICache)`
(implicit named parameter overrides, no parens) already parses. It does —
`parse_connection` returns `expr: None` for a bare `.name`, and the pre-change
binary formats it. So the brief's contingency ("if not, that is in scope for
you") did not fire and no instantiation-grammar change was made at all.
- **Model.** `ItemKind::Bind(BindDirective { target, target_span, instances,
inst })`, with `inst: Instantiation` reused whole. `parse_bind` consumes
`bind`, the dotted target, the optional `: a, b` instance list, then calls
`parse_instantiation` — which also consumes the `;`.
- **Layout.** `Formatter::bind` is four lines: build the head string, then
`concat([head, self.instantiation(&b.inst, depth)])`. Confirmed by
experiment that this is genuinely the same layout: `bind prim_esc_rxtx_tb
prim_esc_rxtx_assert_fpv #(.TimeoutCntDw(6)) …` breaks its `#( )` group and
keeps the connection list flat, and a standalone instantiation padded to the
same total width makes the identical choice. Alignment inference is likewise
untouched — the `ibex_simple_system_cosim_checker_bind` case keeps its
hand-aligned connection table.
- **After.** `{"passing":699,"total":820,"pct":85.2,"failures_by_category":{"interface":31,"dv-statements":26,"expressions":19,"directive-split":14,"assertions":13,"types-decls":11,"invalid-or-fragment":3,"lex-macro-number":2,"not-verilog":1,"other":1}}`.
`bind` is gone from the histogram: **28 gained, 0 lost**, and
`comm -23 <old passing> <new passing>` is empty, so the passing set is a
strict superset.
- **Still failing in my category: none.** The three `common_cells/formal/*`
files that contain a top-level `bind` are counted under `assertions`, not
`bind`: they hit an unsupported `assume` (line 38 / 36 / 61) *before* the
parser reaches the `bind` at the end of the file. Their directives were
extracted and fed through the new binary on their own — all three format
cleanly (`bind counter counter_properties #(...) i_counter_properties (.*);`
from `counter_properties.sv:96`), so nothing in this category is left over;
those files belong to the `assertions` owner.
### 2026-08-21 — dev (response to QA round 1)
The round-1 finding below (a comment between `bind` and its target is dropped
internally and the file becomes unformattable) is fixed, together with its
sibling position (between the target — or the `: instance, list` — and the
module name of the instantiation).
Both positions sit between two tokens that no node owns: the target is a bare
`String`, so a comment written there had nowhere to attach and drifted onto
the instance below, which moves it across tokens and `verify_equivalence`
rightly refused the output. `BindDirective` now carries `target_comments` and
`module_comments`, harvested in `parse_bind` with the same `take_dangling`
the rest of the parser uses, and `Fmt::bind` prints each back where it was
written (`Fmt::inline_comments_spaced`, so a *line* comment ends its line and
the target starts the next one). Both round-trip and are idempotent; two
cases in `bind.cases` pin them, plus a parser test
(`the_comments_around_a_binds_head_are_kept`).
The QA note's "same class of gap ... after the module name / before the
instance name" turned out **not** to reproduce: `checker_mod /*c3*/ c_inst
/*c4*/ (.clk(clk));` already round-trips, because those two positions are the
instance's `meta.leading` and `conn_comments`, which `parse_instantiation`
has always harvested.
**Still refused, deliberately:** a comment written *inside* the `: instance,
list` (`bind dut : /*x*/ u_a chk u (.*);`). `instances: Vec<Name>` has no
`Meta`, and giving one to a list nothing else needs — no corpus file writes a
comment there — is the abstraction-for-a-second-user-that-does-not-exist the
project rules forbid. It stays a clean exit-2 refusal with the input
untouched, not corruption.
Score unchanged before and after
(`{"passing":800,"total":820,"pct":97.6,...}`), passing set identical, and
all 800 passing corpus files format to byte-identical output against the
pre-change binary; the two-pass idempotency sweep over them is clean.
Files changed: `crates/vlog_parser/src/ast.rs` (two fields on
`BindDirective`), `crates/vlog_parser/src/parser.rs` (`parse_bind` + 1 test),
`crates/vlog_formatter/src/format.rs` (`Fmt::bind`),
`crates/vlog_formatter/tests/cases/bind.cases` (2 cases).
## QA log
### 2026-08-21 — round-1 adversarial QA
Verified: `cargo test --workspace`/clippy/fmt clean; corpus score 796/820;
whole-corpus idempotency + comment-preservation sweep clean; 476-case mutation
fuzz clean.
Targeted attacks:
- **`bind` recognized by shape, not keyword — `obj.bind()` must still
parse.** Confirmed: `obj.bind(); obj.bind(1, 2);` (method calls named
`bind`) format unchanged, not confused with the directive.
- **Indexed hierarchical bind targets are a clean parse error.** Confirmed:
`bind dut[3] checker_mod c_inst(.clk(clk));` → `parse error: 2:15: expected
';' (found "checker_mod")`, exit 2, zero bytes on stdout. Clean rejection,
not corruption, matches the dev's own note.
- **Comment placement inside a `bind` directive.** Found a real (but
non-corrupting) gap: a comment sitting between `bind` and the target name —
`bind /*c1*/ dut checker_mod c_inst(.clk(clk));` — is **not** currently
reproduced by the formatter's internal `Doc` construction; the safety net
catches it (`verify_equivalence`: "token stream diverges ... input has
comment `/*c1*/` at 2:8, output has identifier `dut` at 2:8") and the CLI
exits 2 with zero bytes written to stdout. Root cause: `parse_bind`
(parser.rs, `fn parse_bind` — target-name parsing via `expect_ident()`
around parser.rs:2627) never routes through `take_meta()`/the comment
bucket the way ordinary item/list elements do, so a comment landing exactly
there has nowhere to attach and gets dropped internally — but the net
refuses to let that reach the file. **NON-BLOCKING** per the hard
invariants (no corruption occurred; input is left untouched on disk), but
worth a follow-up: comments in that position currently make the file
unformattable via lucisv rather than being preserved and formatted. Same
class of gap reproduces for a comment right after the module name / before
the instance name of the `bind`'s instantiation tail — not otherwise
explored in depth.
No BLOCKING findings for this cluster.
### 2026-08-21 — round-2 adversarial QA (verifying the round-1 fix)
Confirms the dev's 2026-08-21 "response to QA round 1" work log entry above:
`target_comments`/`module_comments` on `BindDirective`.
- **The exact repro from round-1** (`bind /*c1*/ dut checker_mod
c_inst(.clk(clk));`) now round-trips: the comment stays between `bind` and
the target, byte-identical, idempotent.
- **The sibling position**, between the target (or `: instance, list`) and
the instantiation's module name — `bind dut /*c2*/ chk u (.*);` and `bind
dut : u_a /*c2*/ chk u (.*);` — both round-trip.
- **Line comments in both slots**, not just block comments —
`bind // c\n dut chk u (.*);` and `bind dut // c\n chk u (.*);` — both
format correctly, ending their line and pushing the next token to a new
line, matching `Fmt::inline_comments_spaced`'s general rule.
- **The "already worked" claim** — a comment after the module name / before
the instance name (`checker_mod /*c3*/ c_inst /*c4*/ (.clk(clk))`) —
reconfirmed unchanged.
- **The deliberately-refused position** — a comment inside the `: instance,
list` (`bind dut : /*x*/ u_a chk u (.*);`) — still refuses cleanly: exit 2,
`verify_equivalence` catches the drop before it reaches disk, input file
untouched. Consistent with the "Still refused, deliberately" note above.
No BLOCKING findings. The round-1 gap is closed.