Files

540 lines
31 KiB
Markdown

# spans
## Goal
Give every token, every comment and every AST node a byte range into the
source text, plus a utility that converts byte offsets to and from
line:column. This is pure data plumbing — no formatter behavior changes — but
it is the prerequisite TODO.md §6 names for the whole LSP effort (semantic
tokens, hover, go-to-definition, diagnostics all speak in ranges) and for the
two §2 formatter features that must splice original source by position:
`// verilog_format: off` fences and `--lines M-N` range formatting. Today the
parser records only 1-based line/col on tokens, which is enough to *print* a
diagnostic and useless for going the other way: from a node back to its bytes,
or from an editor position into the tree.
## The span convention
> **A node's span is its code extent: the first byte of its first token
> through the last byte of its last token. Comments are not part of it.**
Rationale, since the alternative (span includes attached trivia) is what some
formatters do:
- Every LSP request is about code. `textDocument/definition` on a signal must
highlight the declaration, not the paragraph of comment above it; range
formatting on "lines 10-20" must not drag in a doc comment that happens to
sit on line 9 because it is attached to the item on line 10.
- Trivia is *not* lost by this choice: `Comment` carries its own `span`, and
a comment is always reachable — it is attached to the node (`Meta.leading`,
`Meta.trailing`) or to a token (`Token.leading` / `Token.trailing`). A
consumer that wants "node plus its comments" takes the union; a consumer
that wants the code cannot recover it from a trivia-inclusive span.
- It composes: with trivia excluded, a child's span always nests inside its
parent's, which is asserted for every node type in
`every_node_span_nests_inside_its_parent`. Trivia-inclusive spans overlap
between siblings as soon as a comment sits between them.
Two consequences worth stating explicitly:
- **Attribute instances `(* ... *)` are inside the span.** They are real
tokens, not comments, so an `Item`/`Stmt` span starts at the `(*`. This
matters for format-off/range splicing: emitting the original bytes of an
item must reproduce its attributes.
- **A span is a byte range, never a char range.** `source[span.as_range()]`
is exact for multi-byte UTF-8 (tested: `λ`/`ü`/`✓` in comments, strings and
identifiers-adjacent positions).
## Where spans live
| carrier | span covers |
|---|---|
| `Token` | the token; `source[span] == text` for every kind but `Number` |
| `Comment` | `//` or `/* */` including the markers, excluding trailing whitespace |
| `RawText` | a directive, an attribute, or a macro invocation, verbatim |
| `SourceFile` | `0..len` — the whole text |
| `Item`, `Stmt`, `Expr` | the construct, attributes included, comments excluded |
| `GenIf`, `GenBlock`, `Dim` | as written, brackets/`begin`…`end` included |
| the 16 `Meta`-carrying element structs | the element, its separator comma excluded |
The "element structs" are `NonAnsiPort`, `AnsiPort`, `ParamPort`,
`EnumMember`, `StructMember`, `Declarator`, `AssignPair`, `Instance`,
`OrderedConn`, `Connection`, `GateInstance`, `GenCaseItem`, `CaseItem`,
`TfArg`, `PatternItem`, `ExprItem` — i.e. exactly the nodes that already
carry a `Meta`, which is this codebase's existing notion of "an addressable
thing on its own line or list slot".
### `Expr` became a wrapper struct
`Expr` was an enum; it is now `Expr { kind: ExprKind, span: TextRange }` with
the old enum renamed to `ExprKind`. The alternatives considered:
1. **A `span` field on each of the 22 variants.** Rejected: "the span of this
expression" would be a 22-arm match at every call site, and every new
variant is a new place to forget it.
2. **`Spanned<Expr>` at every use site.** Rejected: it turns `Box<Expr>` into
`Box<Spanned<Expr>>` in ~30 places, reads worse, and is a third shape in a
tree that already uses `{ meta, kind }` twice.
3. **The wrapper struct (shipped).** One field access for any expression,
the same shape `Item` and `Stmt` already have, and the compiler finds
every construction site. Cost: 62 mechanical edits (33 in `parser.rs`, 29
in `format.rs`), all of them `Expr::X` → `ExprKind::X` plus `match e` →
`match &e.kind`.
### Nodes deliberately *without* a span, and why
- **The payload structs of `ItemKind` / `StmtKind` / `TypedefKind` variants**
— `Module`, `Typedef`, `ParamDecl`, `DataDecl`, `PortDecl`, `ContAssign`,
`Instantiation`, `GateInstantiation`, `GenFor`, `GenCase`, `FunctionDecl`,
`TaskDecl`, `MacroCall`, `EnumType`, `StructType`. Each is the sole payload
of one wrapping `Item`/`Stmt`, so its extent is *by construction* that
node's span; storing it twice would be two fields to keep in sync and one
more way to be subtly wrong. Take the enclosing `Item`/`Stmt` span.
(`GenIf` is the exception that proves the rule: a nested `else if` lives in
`GenElse::If(Meta, GenIf)` with no `Item` around it, so it needs its own.)
- **`DataType`** — an implicit type (`input [7:0] x`) has *no tokens of its
own*; a span would have to be a lie (`0..0`) or an `Option`, and `DataType`
is `Default`-constructed in five places where a default `TextRange` would
silently mean "byte 0". Its packed dimensions are `Dim`s, which do carry
spans. Known gap: hover over a type keyword resolves to the enclosing
declarator's span, not to the type alone. Revisit when `vlog_semantic`
needs it — the fix is a real `Option<TextRange>`, not a default.
- **Glue enums and helper structs** — `SensList`, `SensItem`,
`TimingControl`, `SimpleAssign`, `ForInit`, `ForStep`, `GenElse`,
`Connections`, `PortList`, `Meta`. They hold nodes that carry spans and are
not things an editor request addresses on its own.
Nothing was found where a span is *impossible*; the list above is all
"redundant" or "would have to be a lie".
## The two normalizations that break `source[span] == text`
The lexer rewrites token text in exactly two places, both pre-existing, both
whitespace-only, and both now documented and pinned by the losslessness test:
1. **A sized literal's tick spacing.** `8 'h FF` lexes as one `Number` whose
text is `8'hFF`. The span is the real extent (`8 'h FF`), so the span is
right and the text is normalized.
2. **Two same-line trailing comments merge into one `Comment`**, joined by a
single space (`/* a */ /* b */` → `/* a */ /* b */`). The merged node's
span covers both, so no byte is left unaccounted for.
The test asserts that any piece whose text differs from its slice (a) is one
of those two kinds and (b) differs *only* in whitespace.
## Losslessness
`crates/vlog_parser/tests/spans.rs` asserts, over 24 hand-written sources and
every `.sv`/`.v` fixture in `crates/vlog_formatter/tests/fixtures/`:
1. tokens and comments come out in source order and never overlap;
2. every byte not inside one of them is whitespace;
3. concatenating them with the whitespace between them reproduces the input
byte-for-byte;
4. each piece's `text` is its own source slice, modulo the two normalizations
above.
That is the token-level half of TODO.md §6's `reconstruct(tree) == input`.
The AST-level half is not claimed: it needs a tree walker that emits nodes and
trivia in order, which does not exist yet. What this round establishes is that
no source byte is unreachable from the token stream — so if the AST-level
walker ever finds a gap, the gap is in the *tree*, not in the lexer.
Both assertions were mutation-tested rather than assumed: giving `Number`
tokens the trimmed-text span makes assertion 4 fail (`"8'h"` vs `"8'hFF"`),
and starting a postfix segment's span at the segment instead of at the base
makes the nesting assertion fail (`$display` escaping `("%d", i)`).
## LineIndex
`vlog_parser::line_index::LineIndex` — built once from the source text, then
`line_col(offset) -> (line, col)` and `offset(line, col) -> Option<u32>`,
1-based, columns in **UTF-8 bytes** (the same unit as everything else here,
and what the lexer's existing `col` already counts). `line_range(line)` gives
a line's extent for range formatting. Nothing consumes it yet — it is the
half of the conversion that diagnostics don't need and every LSP request
does.
Decisions, all unit-tested:
- A trailing newline opens a last, empty line, so `"a\n"` has two lines. This
is what ruff and every editor do, and it is what makes `offset(2, 1)` at
end-of-file addressable.
- `\r` is an ordinary byte of the line it ends; only `\n` breaks a line. So a
CRLF line's last column is the `\r`. Anything else would make columns
disagree with byte offsets.
- Out-of-range input is clamped, not panicked: an offset past the end gives
the position at the end, and a column past the end of its line stops at the
line's end rather than wrapping onto the next one. A line number out of
range is `None` — that one is a caller error, not a rounding.
- Round-tripping every byte offset of a multi-byte file back through
`offset(line_col(o))` returns `o`.
## Assumptions
- **Files are under 4 GiB.** Offsets are `u32`, as in ruff and
rust-analyzer. A 4 GiB Verilog file is not a use case; `u32` halves the
size cost of putting a span on every node. Nothing enforces this: a larger
file would truncate offsets rather than fail, which is worth a guard if
lucisv ever grows an entry point that does not read the whole file into a
`String` first (today `usize`→`u32` conversion happens only in the lexer,
from offsets into a `&str` the CLI already read whole).
- **One file, no virtual sources.** A `TextRange` has no file identity;
cross-file navigation (TODO.md §6's workspace index) will need
`(FileId, TextRange)` pairs, which is the index's job, not this type's.
- **Spans are only meaningful for the exact text they were lexed from.** The
parser never rewrites source, so this holds trivially today.
- **The formatter does not read spans.** It is span-oblivious after this
change, which is what makes "no behavior change" checkable rather than
argued.
## Handshakes
**Consumed from `vlog_parser::lexer`:** nothing new. The lexer already
tracked `pos` while lexing; a span is that position pair recorded, and
line/col are untouched (still used by `LexError`/`ParseError` and by the
formatter's raw-text dedent).
**Promised to `vlog_formatter`:**
- Every AST node listed above carries `span: TextRange`. The formatter is not
required to use them and does not: this round changed exactly two things in
`format.rs`, both mechanical (`Expr::X` → `ExprKind::X`, and `match e` →
`match &e.kind` in `expr`, `expr_compact` and `binary_chain`'s `walk`).
- **`RawText.col` is unchanged and still load-bearing.** The macro-items
contract (`docs/features/macro-items/README.md`) — `raw.col` is what
`Fmt::raw_lines` dedents continuation lines by — is untouched; `RawText`
gained a `span` *alongside* `col`, it did not replace it. A span cannot
replace `col` in that role: `col` is a column, and the dedent needs the
column, not the offset.
- **`verify.rs` is untouched.** No normalization was added, broadened, or
weakened, so CLAUDE.md hard invariant #4 does not apply to this round —
and the corpus TSV being byte-identical is the evidence that the safety net
sees exactly what it saw before.
**Recursion/chain budgets
(`docs/features/recursion-limit/README.md`):** no new budget is charged and
none is needed. `TextRange` is a `Copy` pair of `u32`s stored *inside*
existing nodes — it adds no root-to-leaf depth, no `Box`, and no new
recursion. The `Expr` wrapper adds one struct layer to the *type*, not to the
tree: `ExprKind::Binary` still holds `Box<Expr>`, so the walk depth per
operator is what it was. The deep-nesting tests (`deep_nesting.rs`, the
parser's boundary tests at 62/63 and 256/257) pass unchanged, which is the
check that matters.
**Requested of nobody.** No other module needs a change for this feature.
## Status / TODO
- [x] `span.rs`: `TextRange { start, end }` with `new`/`empty`/`len`/
`is_empty`/`contains`/`as_range`, and nothing else.
- [x] Lexer: `span` on `RawTok`, `Token` and `Comment`; line/col kept.
- [x] Trimmed tokens (line comments, directives) span only their kept text.
- [x] Merged trailing comments span both comments.
- [x] AST: `Expr` → `Expr { kind: ExprKind, span }`; `span` on `SourceFile`,
`Item`, `Stmt`, `RawText`, `GenIf`, `GenBlock`, `Dim` and the 16
`Meta`-carrying element structs.
- [x] Parser: `here()` / `last_end()` / `span_from()` / `expr_at()`, one
pattern used everywhere; separator commas excluded from element spans.
- [x] `line_index.rs`: `LineIndex` with both directions + `line_range`.
- [x] `tests/spans.rs`: token-stream losslessness (24 sources + the
formatter fixtures), node-span slicing, trivia exclusion, attribute
inclusion, multi-byte, CRLF, parent/child nesting over every node type.
- [x] Formatter untouched in behavior: full `.cases`/fixture/idempotency
suite green with zero snapshot churn.
- [x] Corpus TSV byte-identical before/after.
- [x] TODO.md §6 spans item checked.
- [ ] **Not done, deliberately:** AST-level `reconstruct(tree) == input`.
Needs a tree walker that emits nodes and trivia in order; the token
level is what spans alone can prove. Left as the open half of §6's
"keep the CST lossless" item.
- [ ] **Not done:** spans on `DataType` (see the gap list above) and on the
glue enums. Both are one-line additions if a consumer appears; adding
them now would be building for a second user that does not exist.
## Work log
### 2026-08-19 — dev agent
- Read `CLAUDE.md`, `README.md`, TODO.md §2/§6, and the Handshakes of
`recursion-limit` and `macro-items` before touching code. Baseline:
`cargo test --workspace` **111 passed**, clippy silent, fmt clean, corpus
TSV md5 `3fab114f4f00626b254259e9dafe0ed7` (820 files, 468 parsed, 0
verification errors, 0 crashes).
- **Chose "span = code extent" over "span includes attached trivia" before
writing anything**, because the choice is expensive to reverse once
consumers exist. The deciding argument is the nesting property: with
trivia excluded, a child's span always sits inside its parent's, so
`every_node_span_nests_inside_its_parent` is a total invariant over the
tree. With trivia included it is not even *true* — a comment between two
siblings belongs to one of them and the spans overlap — so there would be
nothing to assert.
- **Attributes go the other way** (inside the span) for the same practical
reason range formatting exists: they are tokens, and splicing an item's
source without its `(* keep *)` would drop code.
- **`Expr` wrapper vs. per-variant span**: went with the wrapper. Recorded
the three options and the reasoning above; the deciding factor was that a
per-variant span makes "span of this expression" a 22-arm match, which is
the operation every future consumer performs most.
- **The span/text divergences were found by the test, not predicted.** The
first run of the losslessness test failed on `8 'h FF` (number
normalization) and on two block comments on one line (the merge in the
attachment phase). Both are pre-existing lexer behavior that the formatter
depends on, so the fix was to make the *spans* right — the real extent for
the number, the union for the merged comment — and to state the divergence
in the test's assertion rather than paper over it. Line comments and
directives went the other way: they are `trim_end`-ed, so their span stops
where their text does and the dropped whitespace counts as inter-token
gap.
- **Mutation-tested both halves of the test** rather than trusting a green
first run: gave `Number` the trimmed span (assertion 4 fails as designed),
and started a postfix segment's span at the segment rather than at its base
(`$display` escapes `("%d", i)`). Reverted both; the working tree is clean
of them.
- **Element spans deliberately stop before the separator comma.** In the
parser the comma is eaten in the same loop iteration that builds the
element, so the naive placement of `span_from` would have swallowed it.
Every list site now takes the span *before* `eat_sym(",")`. An omitted
ordered connection (`u (a, , c)`) consumes no token at all and gets the
empty span where it would have started — `TextRange::new` clamps rather
than producing an inverted range.
- **`LineIndex` has no consumer yet**, so its semantics are fixed by tests
instead of by a caller: trailing newline opens an empty last line, `\r`
belongs to its line, offsets clamp and line numbers don't, and every byte
offset of a multi-byte file round-trips.
- Did not touch `verify.rs`, `tools/`, `corpus/`, or the formatter's
behavior. Did not run `git commit`/`git push`.
- **Concurrency note:** another agent's `config-discovery` work landed in the
same working tree during this round (`crates/lucisv/src/config.rs`,
`crates/lucisv/tests/cli.rs`, `args.rs`, `main.rs`, `README.md`, TODO.md §3).
Mid-round its `a_config_file_is_found_by_searching_upward` was failing at
`cli.rs:317` (with `indent = 4` in the config it expected `WIDE_SPLIT`, a
constant written with 2-space indent). Confirmed it was theirs and not this
feature's — reproduced end-to-end with the release binary, which correctly
emits 4-space indent for that config — and left it alone per CLAUDE.md's
"do not touch files outside your feature's stated scope". It was fixed on
their side before this round ended; the workspace is green as of the final
run below.
**Results:** `cargo test --workspace` **158 passed, 0 failed** — of which
this feature's two crates are **99 passed** (up from 80: +3 unit tests in
`span.rs`, +6 in `line_index.rs`, +10 in `tests/spans.rs`; no existing test
changed, no snapshot or `.cases` churn). `cargo clippy
--workspace --all-targets` silent (0 warnings). `cargo fmt --all --check`
clean. Corpus: `tools/corpus_check.sh corpus` (read-only) produced a TSV with
md5 `3fab114f4f00626b254259e9dafe0ed7` — **byte-identical** to the
pre-change baseline; 820 files, 466 would-reformat, 2 ok-unchanged, 352
parse-error, **0 verification errors, 0 crashes**. All four corpus repos
`git status --porcelain` clean apart from the pre-existing untracked
`.lucisv-corpus-rev` stamps. Files touched:
`crates/vlog_parser/src/{span,line_index}.rs` (new),
`crates/vlog_parser/src/{lib,token,lexer,ast,parser}.rs`,
`crates/vlog_parser/tests/spans.rs` (new),
`crates/vlog_formatter/src/format.rs` (mechanical only), `TODO.md` (§6
checkbox), this README.
## QA log
### 2026-08-19 — QA agent
Read `CLAUDE.md`, this README, and the diff (`span.rs`, `line_index.rs`,
`token.rs`, `lexer.rs`, `ast.rs`, `parser.rs`, `tests/spans.rs`, and the
`format.rs` renames) before probing. All probe files were written to
`crates/vlog_parser/tests/qa_*.rs` and deleted before this entry; none are
part of the final diff. No commits made.
**Tool results — all green:**
- `cargo test --workspace`: **158 passed, 0 failed** at the time of this
round (later observed at 160 as the concurrent `config-discovery` agent's
work landed two more `lucisv` unit tests in the same tree — unrelated to
this feature, confirmed by re-diffing; this feature's own crates stayed at
47 (`vlog_parser` unit) + 10 (`tests/spans.rs`) throughout).
- `cargo clippy --workspace --all-targets`: 0 warnings.
- `cargo fmt --all --check`: clean.
- `git diff --stat` on `format.rs`: read every hunk (68 lines). All of it is
`Expr::X` → `ExprKind::X` / `match e` → `match &e.kind`, plus one
struct-pattern change (`Some(Expr::Empty(comments))` →
`Some(Expr { kind: ExprKind::Empty(comments), .. })`) that is the same
mechanical substitution in pattern-match form. **Confirmed genuinely
mechanical, no behavior hunks found.**
**Claim 1 (nesting is a total invariant) — PASS, independently verified.**
Wrote a from-scratch recursive checker (not copied from the dev's
`tests/spans.rs`) over 8 adversarial sources the dev's `SOURCES`/nesting test
does not use: a 10-way generate `if`/`else if` chain, 4-deep labeled
`begin`/`end` nesting, multi-line macro invocations with commas and parens
*inside* string arguments, a non-ANSI header with mixed port kinds and
stacked attributes, instance arrays (`u_arr [3:0]`) and multi-instance
statements, 8-deep parenthesized/cast expression nesting, a labeled
generate-for containing a nested case, and attributes on a statement inside
a function. All nested correctly. Also asserted an invariant the dev's test
does not check — **sibling spans within the same list are non-overlapping
and in non-decreasing source order** (ports, declarators, connections,
instances, gen-case items, block statements, case items, call args) — passed
on all 8 sources. `ItemKind`/`StmtKind`/`ExprKind` matches in both the dev's
checker and mine are compiler-enforced exhaustive (no wildcard arms), so no
variant is silently unchecked.
**Claim 2 (coverage) — PASS.** Cross-checked the 16-element-struct list and
the "deliberately without a span" list against `ast.rs` mechanically: wrote
a small script that extracts each named struct/enum's full body text and
searches for a `span` field. Confirmed all 16 claimed element structs carry
`span`, and all of `DataType`, the payload structs (`Module`, `Typedef`,
`ParamDecl`, `DataDecl`, `PortDecl`, `ContAssign`, `Instantiation`,
`GateInstantiation`, `GenFor`, `GenCase`, `FunctionDecl`, `TaskDecl`,
`MacroCall`, `EnumType`, `StructType`) and the glue enums/structs
(`SensList`, `SensItem`, `TimingControl`, `SimpleAssign`, `ForInit`,
`ForStep`, `GenElse`, `Connections`, `PortList`, `Meta`) do **not**. Matches
the README's table and gap list exactly.
**Claim 3 (LineIndex) — PASS, independently probed beyond the dev's own
unit tests.** Wrote 6 adversarial cases not in `line_index.rs`'s own
`#[cfg(test)]`: offset landing mid-multi-byte-character (byte 1 of `λ`) —
does not panic, returns a byte-precise column, and round-trips via
`offset()`; a file of only `\n\n\n` (4 lines, all empty, matches the
"trailing newline opens an empty line" rule applied recursively); a lone
`\r` not followed by `\n` — confirmed treated as an ordinary byte of its
line, only `\n` breaks (`"a\rb\n"` is one line, 4 columns); `line == 0` on a
real (non-empty) file still `None`; `line_range` on the file's last,
newline-less partial line excludes nothing extra; full round-trip over
every byte offset of a CRLF + multi-byte file. All 6 passed as documented.
**Claim 4 (losslessness) — PASS, independently probed.** Wrote 6 additional
sources (CRLF plus multi-byte comment/string/identifier text together, a
lone mid-file `\r`, a sized literal with an unusual base-letter case and
underscores adjacent to a leading multi-byte comment, a multi-byte comment
glued directly to a token with no whitespace, two merged block comments both
containing multi-byte text, and an escaped identifier next to a `\u`-escaped
string) and asserted `token.text == source[span]` for every token/comment
except the two documented normalizations, and that those two differ only in
whitespace. All passed — no third divergence found.
**Claim 5 (zero behavior change) — PASS, re-verified independently rather
than trusted from the work log.**
- Re-ran `tools/corpus_check.sh corpus`: TSV md5 **`3fab114f4f00626b254259e9dafe0ed7`**
— byte-identical to the dev's reported baseline. (Built from the current
tree, which also includes the now-committed `config-discovery` change;
the match confirms neither feature altered corpus-visible output.)
- Built a second `lucisv` release binary from a `git worktree` at `HEAD`
(`481cce2`, i.e. immediately pre-spans, config-discovery already
committed) and diffed its `--stdin-filename f - < f` output against the
working-tree binary (spans included) over **all 820 `.sv`/`.v` corpus
files**, not just 3-4: **0 differences**. Worktree removed after.
- Corpus repos' `git status --porcelain`: clean apart from the pre-existing
untracked `.lucisv-corpus-rev` stamps, confirmed again.
- No `.cases`/fixture/snapshot files under `crates/vlog_formatter/tests/`
show as modified in `git status`.
**Claim 6 (mutation testing) — one additional claim mutation-tested beyond
the dev's two, with a genuine finding.** Mutated `parse_gen_if_inner` in
`parser.rs` (line ~1327) to compute `GenIf.span`'s `start` **after**
consuming the `if` keyword instead of before it (`let start = self.here();`
moved past `self.expect_kw("if")?;`), so the span would start at the `(`
instead of the `if`. Ran `cargo test -p vlog_parser`: **all 57 tests
(47 unit + 10 `tests/spans.rs`) still passed** — the mutation is
**undetected**. Reverted; `git diff crates/vlog_parser/src/parser.rs`
confirmed byte-identical to the dev's diff before and after (diffed the two
patches directly, exit 0).
- **Why this isn't a nesting-invariant violation (not BLOCKING under the
stated rule):** `every_node_span_nests_inside_its_parent` (and my
independent version) only assert *containment*, and a `GenIf` span
truncated at the front still nests fully inside its parent `Item`
span, and its children (`cond`, `then`) still nest inside the
(now-narrower) `GenIf` span, since they all start at or after `(`.
Containment survives; the total-nesting claim itself is not falsified
by this mutation.
- **What it does expose:** none of the existing tests slice-check
`GenIf.span`'s literal *content* (no test asserts
`slice(src, gi.span)` starts with `"if"` or matches the whole `if (...)
then [else ...]` construct the way `node_spans_slice_back_to_the_construct`
does for `Item`/`Declarator`/`Stmt` spans). The "as written, brackets/
`begin`…`end` included" convention for `GenIf` (README's span table) is
therefore asserted by inspection and by the containment test, but not
by a test that would catch *this specific class* of off-by-one-token
start bug the way the dev's two mutation tests (`Number` trimmed span,
postfix segment start) do for their respective claims.
- **Severity: low, non-blocking.** Not a nesting violation, not a
formatting-behavior change (the formatter is span-oblivious), and the
actual shipped code is correct (`start = self.here()` before
`expect_kw("if")`, verified by reading `parser.rs:1327-1329` and by
`node_spans_slice_back_to_the_construct`-style spot checks in my own
probe). Recommend, as a follow-up and not a blocker: add one assertion
to `tests/spans.rs` that slices `gi.span` and checks it equals the
source text of the `if (...) ... [else ...]` construct verbatim (the
same style already used for `Item`/`Declarator`/`Stmt` in
`node_spans_slice_back_to_the_construct`), which would have caught this
mutation and gives the same content-level confidence the dev already
has for the node types that test covers.
**Claim 7 (CLAUDE.md compliance) — PASS.**
- `u32`/4 GiB assumption: documented explicitly in README's Assumptions
section, including the "nothing enforces this" caveat and where a guard
would need to go.
- No `unwrap()`/`expect()`/`panic!` in the new library code: grepped
`span.rs`, `line_index.rs` (outside `#[cfg(test)]`), and every `+` line of
the `lexer.rs`/`parser.rs`/`ast.rs`/`token.rs` diffs — none found.
- Public items documented: every `pub fn`/`pub struct` in `span.rs` and
`line_index.rs` carries a doc comment (scripted check). New `pub span:
TextRange` fields on existing structs each carry a one-line doc comment
in the diff. `Expr.kind` has none, but this matches pre-existing style —
`Item.meta`/`Item.kind` and `Stmt.meta`/`Stmt.kind` were undocumented
fields before this change too (checked `git show HEAD:.../ast.rs`), so
this is "match the style of the surrounding code," not a new gap.
- README sections: all seven required sections present and non-empty
(Goal, Assumptions, Handshakes, Status/TODO, Work log, QA log, Review).
- `TODO.md` §6 spans checkbox: checked, with an honest annotation pointing
at the exact deliverables and explicitly not overclaiming
("token-level losslessness is a test") — matches the README's own
"AST-level reconstruct not done" caveat. Not dishonest.
- `verify.rs` / `tests/verification.rs`: confirmed untouched by this diff
(`git status`/`git diff --stat` show no changes relative to `HEAD`,
which already includes the unrelated, separately-committed
`config-discovery` change) — matches the Handshakes claim that CLAUDE.md
invariant #4 does not apply to this round.
**Overall: no BLOCKING findings.** One low-severity, non-blocking test-
coverage gap found and documented above (Claim 6). All other claims verified
independently and pass, including two claims (losslessness sources and
LineIndex edge cases) probed with adversarial inputs disjoint from the
dev's own test list, and the full 820-file corpus diffed byte-for-byte
against a pre-spans binary rather than sampled.
## Review
**2026-08-19 — lead. Verdict: accepted and committed, with one lead-added
test. This is the LSP track's cornerstone, done the boring way.**
The three design calls are all right, and all for stated reasons:
1. **Code-extent spans (trivia excluded)** because it makes child-nests-
in-parent a *total, assertable* invariant — the argument that decided
it is exactly the kind of reasoning these READMEs exist to record.
Attributes inside the span (they're tokens), comments outside with
their own spans: correct on both counts.
2. **`Expr { kind, span }`** over per-variant spans or `Spanned<T>` —
least invasive shape that answers "span of any node" in one field
access; 62 mechanical edits was the honest price.
3. **Skipping payload structs whose extent equals their wrapper's** —
storing a fact twice is two things to desync. The `DataType`
implicit-type gap is real and correctly documented rather than
papered over with a lying span.
The losslessness test earning its keep before the feature even shipped —
surfacing the sized-literal and merged-trailing-comment normalizations
nobody had written down — is the pattern to notice: invariant tests find
facts, not just bugs. QA's verification was thorough where it counted
(all-820-file output diff, from-scratch nesting checker with an extra
sibling-ordering invariant, mutation tests both directions).
Lead addition on acceptance: QA's mutation test proved `GenIf.span`'s
content was unpinned (containment held, content didn't) — added
`a_gen_if_span_slices_back_to_its_text` to `tests/spans.rs` so the
mutation now fails. The remaining mutation-coverage question (which
other node spans are content-pinned only transitively?) can ride along
whenever the next spans consumer (fences, range formatting, LSP) starts
exercising them for real.
Unblocked by this feature: format-off fences and `--lines` range
formatting (TODO §2), and every §6 LSP capability. Next foundations:
error-tolerant parsing, then the `` `define`` table.