Escaped identifiers: the terminating space, written once at fifty sites

coverage_gaps H3. An escaped identifier ends at whitespace (IEEE 1800
5.6.1) and the lexer stops the token before it; the formatter emitted
every name bare or through a format! splice, so \my-signal; re-lexed
as one token and the safety net refused the whole file - netlists and
generated RTL could not be formatted at all. One choke point
(format::named / name_doc, predicate ends_escaped because parser-joined
composites like a.\b end inside an escaped name) now terminates the
name; the space is unconditional and the printer's trailing trim
removes it before a break, so doc.rs and printer.rs are untouched.
verify.rs untouched; eight masked-corruption attack pairs; corpus
byte-identical by construction (every corpus backslash is inside a
string or a comment). Ran in its own worktree in parallel with member
completion. Open, filed as topo 2.9-21: a scoped name whose segment is
escaped is refused, never corrupted, until the parser keeps segments.

docs/features/escaped-identifiers/README.md; TODO.md section 19.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-09-02 02:17:43 -07:00
1 parent df85fd3b54
commit 7d637323a5
6 files changed
+966 -89

No files matched your search

+78 -35
View File
@@ -2120,44 +2120,87 @@ position" sentence; the stale five-row tier table), TODO.md §18.
always `isIncomplete`, so the client comes back instead of caching the
emptiness.
## 19. Escaped identifiers wave (2026-09-02) — coverage_gaps H3
## 19. Escaped identifiers wave (2026-09-02) — owner report
`wire \my-signal ;` is unformattable: the lexer stops an escaped
identifier BEFORE its terminating whitespace (lexer.rs:303-317, the
token is `\my-signal`), the formatter emits every name as bare
`Doc::Text` or a `format!` splice (`"{name};"`, `".{}("`, `"{kw} : {l}"`
…, ~30 sites in format.rs), so `\my-signal;` re-lexes as ONE identifier
and `verify.rs` refuses the file (invariant 1 holding). Netlists and
generated RTL are full of escaped names. Precedent:
`vlog_refactor/src/instantiate.rs::terminate` appends the space. Runs
in its own worktree in parallel with §18's QA (disjoint files, no topo
edge). Files: crates/vlog_formatter/src/format.rs (+ doc.rs/printer.rs
only if a trailing-space-before-newline rule needs it),
`wire \my-signal ;` was rejected outright: *verification failed: token
stream diverges … input has identifier `\my-signal` … output has
identifier `\my-signal;`*. An escaped identifier ends at the next
whitespace and at nothing else (IEEE 1800-2017 §5.6.1); the lexer stops
the token before that whitespace (correct), and the formatter then
printed every name bare, so the following `;`, `(`, `,` or `:` was
swallowed into the name on re-lex. Nothing was ever corrupted — the
safety net refused the file — but no design carrying an escaped
identifier could be formatted at all, which is every Vivado netlist
(`\u_x/y_reg[3] `, `\gen[0].u `). Zero formatter or lexer tests
existed with an escaped identifier. Single lane; `verify.rs` untouched
(invariant 4). Files: crates/vlog_formatter/src/format.rs,
crates/vlog_formatter/tests/cases/escaped_identifiers.cases (new),
crates/vlog_formatter/tests/verification.rs, crates/vlog_parser/src/
lexer.rs tests only (pin the token extent), docs/features/
escaped-identifiers/README.md (new), TODO.md §19.
- [ ] **One choke point**: a `Fmt::name(&str) -> Doc` (or equivalent)
that appends the IEEE 1800 §5.6.1 terminating space when the name
starts with `\`, used at EVERY name emission site incl. the
`format!` splices (`.\my-port (x)`, `\m ;`, `end : \lbl `,
`a.\b `, `\pkg ::x`). No site left bare — grep-pinned.
- [ ] **Idempotent + verified**: `\a ;` stays `\a ;`; a name at end of
line is terminated by the newline (no trailing space needed —
decide and pin, mind any trailing-whitespace trim);
`verify.rs` untouched; attack pairs: an output that glues `\a;`,
one that drops the space before `(`, one that merges two escaped
names — all rejected.
- [ ] **Cases**: declarators, ANSI/non-ANSI ports, module/interface/
package/class names + end labels, instance names, port
connections, hierarchical paths, `::` paths, typedef/enum/genvar/
let/disable/labels, tf args, clocking signals, `extends`,
imports; a netlist-shaped file (Vivado-style `\u_x/y[3]`).
Corpus byte-identical (no corpus file has one — assert).
- [ ] **QA**: the survey's two refused files now format; a synthetic
netlist round-trips; opentitan sweep unchanged (read-only).
crates/vlog_formatter/tests/verification.rs,
crates/vlog_parser/src/lexer.rs (tests only),
docs/features/escaped-identifiers/README.md (new), TODO.md §19.
- [x] **One choke point**: `format::named(&str) -> String` (plus
`name_doc`, its `Doc` twin) appends the terminating space when the
string ends inside an escaped name; every name emission in
`format.rs` — 50 sites, declarators through end labels, including
each `format!` splice, `join_names` and `join_paths` — goes
through it. The audit list lives in the helper's doc comment. The
predicate is `ends_escaped`, not `starts_with('\')`, because
several names arrive as already-joined composites (`a.\b`,
`pkg::\x`, a `bind` head) — the same rule
`vlog_refactor::instantiate` already carries.
- [x] **End of line**: the helper always writes the space; the
printer's existing trailing-space trim (`newline`, `BlankLine`,
`render` at EOF) removes it before a break, which terminates the
name by itself. No `printer.rs` / `doc.rs` change. Both shapes
pinned idempotent.
- [x] **Attack pairs** in `tests/verification.rs`, `verify.rs`
untouched: `\a;` glued, the space before a connection's `(`
dropped, two escaped names merged (`\a \b` → `\a\b`), the same
glue inside a class body, a label glued to what follows it — all
rejected; plus the flip side, that writing the space is a
whitespace-only difference.
- [x] **Cases**: `escaped_identifiers.cases`, 18 live cases —
declarators, ANSI/non-ANSI ports, package/interface/class/module
names with end labels, typedefs, enum members, struct fields,
instances and connections, hierarchical and scoped expressions,
generate/block/fork/statement labels, `disable`, `foreach`,
modport, clocking, imports, `let`, `defparam`, case labels, an
aligned group, a broken connection list, an out-of-class method,
a Vivado-style netlist fragment, and an escaped type name inside an
aligned port group.
- [x] **Lexer pin**: the token extent excludes the terminating
whitespace (`src[span] == text`), a tab terminates, `\a;` is one
identifier, and a name may end the file.
- [x] **Corpus**: 813/820 held, and neutral by construction — every
backslash in the 860 corpus files is inside a string literal or a
comment, so no corpus file reaches the new branch. Same for the
read-only opentitan sweep (13 failures, all parse/lex, zero
verification errors).
- [ ] **Follow-up for a parser lane**: `Parser::parse_scoped_name`
joins `pkg::name` into one `String`, losing the boundary, so a
`\my-pkg ::\state-t` type (or instantiated module, or `bind`
target) is still rejected by the net — an error, never a
corruption. Keep the segments. Recorded as the file's one `#SKIP`
case and as
`an_escaped_name_in_a_scoped_type_is_rejected_rather_than_corrupted`.
- [x] **QA (2026-09-02)**: gates clean (fmt, clippy 0, tests 2819/0 after
one QA-added attack pair, corpus 813/820 unchanged); scope matches
the file list above exactly, `verify.rs` confirmed absent from the
diff; 23 additional corruption-hunt shapes beyond the `.cases` file
(punctuation after a name, adjacent names, EOF, comments, `` `define
``/macro args, `bind`, `defparam`, `import`, struct/enum members,
implicit connections, instance arrays, hierarchical paths, CRLF) all
formatted correctly and idempotently, with the one rejection being
exactly the filed scoped-name gap; added
`a_space_dropped_before_a_scope_operator_is_rejected` to
`verification.rs` to close a gap in the attack-pair coverage
(dropped space before `::`, confirmed rejected); opentitan `--check
--no-cache` failure/would-reformat/unchanged sets byte-identical
between this worktree and a trunk `v0.25.0` build (3869/97/13, same
13 files); opentitan `git status` unchanged (3 pre-existing owner
files only). **QA verdict: SHIP.** Full log in the feature README's
QA log.
## 20. Constraint bodies wave (2026-09-02) — coverage_gaps C1, round 1
Constraints (`constraint c { … }`, `constraint C::c { … }`,
+107 -54
View File
@@ -321,7 +321,7 @@ impl<'a> Fmt<'a> {
/// Matches the `endmodule : m` spelling used for module footers.
fn closing(kw: &str, label: &Option<String>) -> Doc {
match label {
Some(l) => text(format!("{kw} : {l}")),
Some(l) => text(format!("{kw} : {}", named(l))),
None => text(kw),
}
}
@@ -1077,7 +1077,7 @@ impl<'a> Fmt<'a> {
fn head_doc(&self, kind: &ItemKind, depth: usize) -> Option<Doc> {
match kind {
ItemKind::Module(m) => Some(self.module_head(m, depth)),
ItemKind::Package { kw, name, .. } => Some(text(format!("{kw} {name};"))),
ItemKind::Package { kw, name, .. } => Some(text(format!("{kw} {};", named(name)))),
_ => None,
}
}
@@ -1095,7 +1095,7 @@ impl<'a> Fmt<'a> {
match kind {
ItemKind::Module(m) => self.module(m, depth),
ItemKind::Package { kw, name, items, dangling, end_label, .. } => {
let mut docs = vec![text(format!("{kw} {name};"))];
let mut docs = vec![text(format!("{kw} {};", named(name)))];
let mut body = Vec::new();
if !items.is_empty() {
body.push(Doc::HardLine);
@@ -1188,7 +1188,7 @@ impl<'a> Fmt<'a> {
/// Split out from the body so a range run can keep one and lay out the
/// other (`range.rs`); a whole-file run always emits both.
fn module_head(&self, m: &Module, depth: usize) -> Doc {
let mut docs = vec![text(format!("{} {}", m.kw, m.name))];
let mut docs = vec![text(format!("{} {}", m.kw, named(&m.name)))];
let has_imports = !m.imports.is_empty();
if has_imports {
// One line per `import` statement the header wrote: folding two of
@@ -1246,7 +1246,7 @@ impl<'a> Fmt<'a> {
PortList::NonAnsi(ports) => ports
.iter()
.map(|p| {
ListItem::from_meta(&p.meta, text(p.name.clone())).with_comma(p.comma)
ListItem::from_meta(&p.meta, name_doc(&p.name)).with_comma(p.comma)
})
.collect(),
_ => Vec::new(),
@@ -1281,7 +1281,7 @@ impl<'a> Fmt<'a> {
docs.push(t);
docs.push(text(" "));
}
docs.push(text(p.name.clone()));
docs.push(name_doc(&p.name));
docs.extend(self.unpacked_dims(&p.unpacked));
if let Some(d) = &p.default {
docs.push(text(" = "));
@@ -1317,7 +1317,7 @@ impl<'a> Fmt<'a> {
last.pop();
}
}
let mut docs = vec![text(p.name.clone())];
let mut docs = vec![name_doc(&p.name)];
docs.extend(self.unpacked_dims(&p.unpacked));
if let Some(d) = &p.default {
docs.push(text(" = "));
@@ -1349,7 +1349,7 @@ impl<'a> Fmt<'a> {
if need_space {
docs.push(text(" "));
}
docs.push(text(ty.name.clone()));
docs.push(name_doc(&ty.name));
need_space = true;
}
// `uvm_analysis_port #(bit [31:0]) port;` — spaced before the `#(`,
@@ -1466,7 +1466,7 @@ impl<'a> Fmt<'a> {
let items: Vec<ListItem> = decls
.iter()
.map(|d| {
let mut docs = vec![text(d.name.clone())];
let mut docs = vec![name_doc(&d.name)];
docs.extend(self.unpacked_dims(&d.unpacked));
if let Some(init) = &d.init {
docs.push(text(" ="));
@@ -1561,7 +1561,7 @@ impl<'a> Fmt<'a> {
prefix.push(text(" "));
prefix.push(t);
}
let mut name = vec![text(decl.name.clone())];
let mut name = vec![name_doc(&decl.name)];
name.extend(self.unpacked_dims(&decl.unpacked));
vec![
concat(prefix),
@@ -1606,24 +1606,28 @@ impl<'a> Fmt<'a> {
fn typedef(&self, t: &Typedef) -> Doc {
match &t.kind {
TypedefKind::ForwardClass => text(format!("typedef class {};", t.name)),
TypedefKind::ForwardClass => text(format!("typedef class {};", named(&t.name))),
TypedefKind::Alias(ty) => {
let mut docs = vec![text("typedef ")];
if let Some(d) = self.data_type(ty) {
docs.push(d);
docs.push(text(" "));
}
docs.push(text(t.name.clone()));
docs.push(name_doc(&t.name));
docs.extend(self.unpacked_dims(&t.unpacked));
docs.push(text(";"));
concat(docs)
}
TypedefKind::Enum(e) => {
concat(vec![text("typedef "), self.enum_type(e), text(format!(" {};", t.name))])
}
TypedefKind::Struct(s) => {
concat(vec![text("typedef "), self.struct_type(s), text(format!(" {};", t.name))])
}
TypedefKind::Enum(e) => concat(vec![
text("typedef "),
self.enum_type(e),
text(format!(" {};", named(&t.name))),
]),
TypedefKind::Struct(s) => concat(vec![
text("typedef "),
self.struct_type(s),
text(format!(" {};", named(&t.name))),
]),
}
}
@@ -1643,7 +1647,7 @@ impl<'a> Fmt<'a> {
.members
.iter()
.map(|m| {
let mut d = vec![text(m.name.clone())];
let mut d = vec![name_doc(&m.name)];
// Tight against the name: `OtbnDmem[16]` is one enum name
// range, not a name with a dimension beside it.
d.extend(m.range.iter().map(|r| self.dim(r)));
@@ -1773,9 +1777,9 @@ impl<'a> Fmt<'a> {
/// instantiation written on its own would be.
fn bind(&self, b: &BindDirective, depth: usize) -> Doc {
let head = if b.instances.is_empty() {
b.target.clone()
named(&b.target)
} else {
format!("{} : {}", b.target, join_names(&b.instances))
format!("{} : {}", named(&b.target), join_names(&b.instances))
};
// The comments around the head have no node of their own; each prints
// back between the two tokens it was written between.
@@ -1788,7 +1792,7 @@ impl<'a> Fmt<'a> {
}
fn instantiation(&self, inst: &Instantiation, depth: usize) -> Doc {
let mut docs = vec![text(inst.module.clone())];
let mut docs = vec![name_doc(&inst.module)];
let mut on_fresh_line = self.bracket_comments(&inst.param_comments, &mut docs, false);
// An empty `#()` was written by hand and is reprinted as `#()`; a
// missing one stays missing.
@@ -1847,7 +1851,7 @@ impl<'a> Fmt<'a> {
/// One instance of a module instantiation: `u0 [3:0] (.a(x))`.
fn instance(&self, instance: &Instance, depth: usize) -> Doc {
let mut docs = vec![text(instance.name.clone())];
let mut docs = vec![name_doc(&instance.name)];
if !instance.dims.is_empty() {
docs.push(text(" "));
for d in &instance.dims {
@@ -1922,7 +1926,7 @@ impl<'a> Fmt<'a> {
let ends_line = self.inline_comments(&c.close_comments, &mut inner);
let close = if ends_line { Doc::HardLine } else { Doc::SoftLine };
vec![
text(format!(".{}", c.name)),
text(format!(".{}", named(&c.name))),
concat(vec![text("("), group(vec![indent(inner), close]), text(")")]),
]
}
@@ -1957,9 +1961,9 @@ impl<'a> Fmt<'a> {
};
}
match &c.expr {
None => text(format!(".{}", c.name)),
None => text(format!(".{}", named(&c.name))),
Some(Expr { kind: ExprKind::Empty(comments), .. }) => {
let mut docs = vec![text(format!(".{}(", c.name))];
let mut docs = vec![text(format!(".{}(", named(&c.name)))];
let mut ends_line = false;
for cm in comments {
if ends_line {
@@ -1979,7 +1983,7 @@ impl<'a> Fmt<'a> {
let ends_line = self.inline_comments(&c.close_comments, &mut inner);
let close = if ends_line { Doc::HardLine } else { Doc::SoftLine };
concat(vec![
text(format!(".{}(", c.name)),
text(format!(".{}(", named(&c.name))),
group(vec![indent(inner), close]),
text(")"),
])
@@ -2010,7 +2014,7 @@ impl<'a> Fmt<'a> {
for (i, inst) in g.instances.iter().enumerate() {
docs.push(if i > 0 { text(", ") } else { text(" ") });
if let Some(name) = &inst.name {
docs.push(text(name.clone()));
docs.push(name_doc(name));
docs.push(text(" "));
}
docs.push(self.expr_list("(", &inst.args, ")"));
@@ -2060,7 +2064,7 @@ impl<'a> Fmt<'a> {
fn gen_block(&self, docs: &mut Vec<Doc>, b: &GenBlock, depth: usize) -> bool {
if b.is_block {
match &b.label {
Some(l) => docs.push(text(format!(" begin : {l}"))),
Some(l) => docs.push(text(format!(" begin : {}", named(l)))),
None => docs.push(text(" begin")),
}
let mut body = Vec::new();
@@ -2141,7 +2145,7 @@ impl<'a> Fmt<'a> {
docs.push(t);
docs.push(text(" "));
}
docs.push(text(a.name.clone()));
docs.push(name_doc(&a.name));
docs.extend(self.unpacked_dims(&a.unpacked));
if let Some(d) = &a.default {
docs.push(text(" = "));
@@ -2167,7 +2171,7 @@ impl<'a> Fmt<'a> {
head.push_str(lifetime);
head.push(' ');
}
head.push_str(&c.name);
head.push_str(&named(&c.name));
let mut docs = vec![text(head)];
let on_fresh_line = self.bracket_comments(&c.param_comments, &mut docs, false);
if let Some(params) = &c.param_ports {
@@ -2181,7 +2185,7 @@ impl<'a> Fmt<'a> {
docs.push(self.delimited_dangling("(", items, &c.param_dangling, ")", broken));
}
if let Some(ext) = &c.extends {
docs.push(text(format!(" extends {}", ext.name)));
docs.push(text(format!(" extends {}", named(&ext.name))));
let fresh = self.bracket_comments(&ext.param_comments, &mut docs, false);
if let Some(params) = &ext.params {
let items: Vec<ListItem> = params
@@ -2225,7 +2229,7 @@ impl<'a> Fmt<'a> {
docs.push(text(" "));
}
docs.extend(self.leading(&d.meta));
docs.push(text(format!("{} ", d.name)));
docs.push(text(format!("{} ", named(&d.name))));
let items: Vec<ListItem> = d
.ports
.iter()
@@ -2265,7 +2269,7 @@ impl<'a> Fmt<'a> {
let mut head = String::from(if c.is_default { "default clocking" } else { "clocking" });
if let Some(n) = &c.name {
head.push(' ');
head.push_str(&n.text);
head.push_str(&named(&n.text));
}
let mut docs = vec![text(head)];
// `default clocking cb;` selects an existing block: no event, no body.
@@ -2322,7 +2326,7 @@ impl<'a> Fmt<'a> {
if i > 0 {
docs.push(text(", "));
}
docs.push(text(sig.name.text.clone()));
docs.push(name_doc(&sig.name.text));
if let Some(value) = &sig.value {
docs.push(text(" = "));
docs.push(self.expr(value));
@@ -2340,10 +2344,10 @@ impl<'a> Fmt<'a> {
ExportDecl::Dpi(d) => {
let mut head = format!("export {} ", d.spec);
if let Some(c) = &d.c_identifier {
head.push_str(&c.text);
head.push_str(&named(&c.text));
head.push_str(" = ");
}
text(format!("{head}{} {};", d.kw, d.name.text))
text(format!("{head}{} {};", d.kw, named(&d.name.text)))
}
ExportDecl::Package(paths) => text(format!("export {};", join_paths(paths))),
}
@@ -2352,7 +2356,7 @@ impl<'a> Fmt<'a> {
/// `let max(a, b) = (a > b) ? a : b;` (IEEE 1800 §11.12) — a name, an
/// optional port list laid out like a function's, and one expression.
fn let_decl(&self, l: &LetDecl) -> Doc {
let mut docs = vec![text(format!("let {}", l.name))];
let mut docs = vec![text(format!("let {}", named(&l.name)))];
if l.has_parens {
docs.push(self.tf_args(&l.ports));
}
@@ -2380,9 +2384,9 @@ impl<'a> Fmt<'a> {
}
}
if let Some(scope) = &f.scope {
header.push(text(format!("{scope}::")));
header.push(text(format!("{}::", named(scope))));
}
header.push(text(f.name.clone()));
header.push(name_doc(&f.name));
if f.has_parens {
header.push(self.tf_args(&f.args));
}
@@ -2420,9 +2424,9 @@ impl<'a> Fmt<'a> {
header.push(text(format!("{q} ")));
}
if let Some(scope) = &t.scope {
header.push(text(format!("{scope}::")));
header.push(text(format!("{}::", named(scope))));
}
header.push(text(t.name.clone()));
header.push(name_doc(&t.name));
if t.has_parens {
header.push(self.tf_args(&t.args));
}
@@ -2499,7 +2503,7 @@ impl<'a> Fmt<'a> {
end_label: &Option<String>,
) -> Doc {
let mut docs = vec![match label {
Some(l) => text(format!("begin : {l}")),
Some(l) => text(format!("begin : {}", named(l))),
None => text("begin"),
}];
let mut body = Vec::new();
@@ -2600,7 +2604,7 @@ impl<'a> Fmt<'a> {
}
StmtKind::ForkJoin { label, join_kw, stmts, dangling, end_label, .. } => {
let mut docs = vec![match label {
Some(l) => text(format!("fork : {l}")),
Some(l) => text(format!("fork : {}", named(l))),
None => text("fork"),
}];
let mut body = Vec::new();
@@ -2771,13 +2775,13 @@ impl<'a> Fmt<'a> {
},
StmtKind::Break => text("break;"),
StmtKind::Continue => text("continue;"),
StmtKind::Disable(name) => text(format!("disable {name};")),
StmtKind::Disable(name) => text(format!("disable {};", named(name))),
StmtKind::WaitFork => text("wait fork;"),
StmtKind::Import(paths) => text(format!("import {};", join_paths(paths))),
// A statement label prints tight against its `:`, the way a case
// label does: `check_decode: assert (...)`.
StmtKind::Labeled { name, stmt, .. } => {
concat(vec![text(format!("{name}: ")), self.stmt(stmt)])
concat(vec![text(format!("{}: ", named(name))), self.stmt(stmt)])
}
StmtKind::Directive(d) => self.raw_text(d),
// See `ItemKind::Error`: unreachable from `format_source`, present
@@ -2968,7 +2972,7 @@ impl<'a> Fmt<'a> {
fn expr(&self, e: &Expr) -> Doc {
match &e.kind {
ExprKind::Ident(s) => text(s.clone()),
ExprKind::Ident(s) => name_doc(s),
ExprKind::Number(s) => text(s.clone()),
ExprKind::Str(s) => text(s.clone()),
// Only reachable through `connection`, which handles the comments.
@@ -3023,10 +3027,10 @@ impl<'a> Fmt<'a> {
text("]"),
]),
ExprKind::Member { base, name } => {
concat(vec![self.expr(base), text(format!(".{name}"))])
concat(vec![self.expr(base), text(format!(".{}", named(name)))])
}
ExprKind::Scope { base, name } => {
concat(vec![self.expr(base), text(format!("::{name}"))])
concat(vec![self.expr(base), text(format!("::{}", named(name)))])
}
// Written tight, like the `::` it almost always precedes.
ExprKind::Parameterized { base, params } => {
@@ -3104,7 +3108,7 @@ impl<'a> Fmt<'a> {
// `.name(value)`, tight, with a break opportunity inside.
ExprKind::NamedArg { name, value, close_comments, .. } => match &value.kind {
ExprKind::Empty(comments) => {
let mut docs = vec![text(format!(".{name}("))];
let mut docs = vec![text(format!(".{}(", named(name)))];
let mut ends_line = false;
for cm in comments {
if ends_line {
@@ -3124,7 +3128,7 @@ impl<'a> Fmt<'a> {
let ends_line = self.inline_comments(close_comments, &mut inner);
let close = if ends_line { Doc::HardLine } else { Doc::SoftLine };
concat(vec![
text(format!(".{name}(")),
text(format!(".{}(", named(name))),
group(vec![indent(inner), close]),
text(")"),
])
@@ -3230,16 +3234,65 @@ fn drive_strength(s: &DriveStrength) -> String {
}
}
/// A name, plus the space that terminates it when it is an escaped identifier.
///
/// An escaped identifier runs from its `\` to the next **whitespace**
/// character and to nothing else (IEEE 1800-2017 §5.6.1), so `\my-signal;`
/// lexes as one identifier that swallows the `;`, and `.\my-port(x)` as one
/// that swallows the rest of the line. Every name this file writes goes
/// through here (or through [`name_doc`], its `Doc` twin): declarators,
/// ANSI and non-ANSI ports, parameters and their aligned cells, type names,
/// typedef/enum/genvar/`let` names, module, package, class, function, task,
/// modport and clocking names, instance and module-instance names, port
/// connections and named call arguments, `extends`, scopes, hierarchical
/// members, tf arguments, block/fork/statement labels, every `end : label`,
/// `disable`, and the `join_names`/`join_paths` lists. The audit that built
/// that list is a grep of `text(` and `format!(` over this file; a site that
/// grows a name later belongs on it.
///
/// The space is unconditional. Where the layout already writes a separator
/// the output carries two (`logic \a = 1;`) — legal, a fixed point under
/// re-formatting, and cheaper than a second rule about what comes next.
fn named(s: &str) -> String {
if ends_escaped(s) {
format!("{s} ")
} else {
s.to_string()
}
}
/// [`named`] as a `Doc`.
fn name_doc(s: &str) -> Doc {
text(named(s))
}
/// Whether `s` ends *inside* an escaped identifier, and so cannot be followed
/// directly by punctuation.
///
/// Whitespace is the only terminator, so the question is exactly whether a
/// `\` survives in the run of characters after the last whitespace — which
/// also answers it for the composites the AST hands over already joined
/// (`a.\b`, `pkg::\x`). Conservative by construction: a false positive
/// writes one harmless extra space. `vlog_refactor::instantiate` carries the
/// same two-line rule for the skeletons it splices.
fn ends_escaped(s: &str) -> bool {
s.rsplit(char::is_whitespace).next().unwrap_or(s).contains('\\')
}
/// A comma-separated list of names, as the source wrote them. The parser
/// keeps each name's byte range alongside its text, so the joined spelling is
/// rebuilt here rather than stored.
fn join_names(names: &[Name]) -> String {
names.iter().map(|n| n.text.as_str()).collect::<Vec<_>>().join(", ")
names.iter().map(|n| named(&n.text)).collect::<Vec<_>>().join(", ")
}
/// The same for a list of `pkg::item` import paths.
fn join_paths(paths: &[ImportPath]) -> String {
paths.iter().map(ImportPath::text).collect::<Vec<_>>().join(", ")
paths
.iter()
.map(|p| format!("{}::{}", named(&p.pkg.text), named(&p.item.text)))
.collect::<Vec<_>>()
.join(", ")
}
/// `import "DPI-C" [context|pure ][c_name = ]` — the linkage prefix a DPI
@@ -3251,7 +3304,7 @@ fn dpi_import_prefix(d: &DpiImport) -> String {
s.push(' ');
}
if let Some(c) = &d.c_identifier {
s.push_str(&c.text);
s.push_str(&named(&c.text));
s.push_str(" = ");
}
s
@@ -0,0 +1,309 @@
# An escaped identifier (IEEE 1800-2017 5.6.1) runs from its backslash to the
# next whitespace character and to nothing else, so every name the formatter
# writes next to punctuation carries a terminating space. Where the layout
# already writes a separator the output has two spaces (`logic \x = 1;`):
# deliberate, and a fixed point on the next pass.
# escaped declarators: net, variable, list, unpacked, parameter
module m;
wire \my-signal ;
logic \x = 1'b0;
reg [7:0] \r-a , \r-b [0:3];
parameter int \P-WIDTH = 8;
localparam \Q = 1;
endmodule
----
module m;
wire \my-signal ;
logic \x = 1'b0;
reg [7:0] \r-a , \r-b [0:3];
parameter int \P-WIDTH = 8;
localparam \Q = 1;
endmodule
====
# escaped ANSI ports, module name and end label
module \my-mod (input logic \a-in , output wire [7:0] \b-out , input \c = 1);
endmodule : \my-mod
----
module \my-mod (input logic \a-in , output wire [7:0] \b-out , input \c = 1);
endmodule : \my-mod
====
# escaped non-ANSI ports, declared in the body
module \m2 (\a-p , \b-p );
input \a-p ;
output \b-p ;
endmodule
----
module \m2 (\a-p , \b-p );
input \a-p ;
output \b-p ;
endmodule
====
# escaped package, typedefs, enum members and struct fields
package \my-pkg ;
typedef logic [7:0] \byte-t ;
typedef enum logic [1:0] {\A-0 , \B-1 = 2'd2} \state-t ;
typedef struct packed {logic \f-a ; logic [3:0] \f-b ;} \s-t ;
typedef class \fwd-c ;
endpackage : \my-pkg
----
package \my-pkg ;
typedef logic [7:0] \byte-t ;
typedef enum logic [1:0] {\A-0 , \B-1 = 2'd2} \state-t ;
typedef struct packed {
logic \f-a ;
logic [3:0] \f-b ;
} \s-t ;
typedef class \fwd-c ;
endpackage : \my-pkg
====
# escaped class, extends, members, tf arguments and end labels
class \base-c ;
endclass : \base-c
class \my-c extends \base-c ;
int \fld ;
extern function void \do-it (input int \arg-a , output bit \arg-b );
function void \f2 (int \q );
this.\fld = \q ;
endfunction : \f2
task \tsk ();
endtask : \tsk
endclass : \my-c
----
class \base-c ;
endclass : \base-c
class \my-c extends \base-c ;
int \fld ;
extern function void \do-it (input int \arg-a , output bit \arg-b );
function void \f2 (int \q );
this.\fld = \q ;
endfunction : \f2
task \tsk ();
endtask : \tsk
endclass : \my-c
====
# escaped instance, overrides, instance array and port connections
module m;
\sub-mod #(.\P-A (2), .P_B(3)) \u-inst [3:0] (.\p-in (a), .\p-out (\w ), .*);
sub \u2 (.\c-in );
endmodule
----
module m;
\sub-mod #(.\P-A (2), .P_B(3)) \u-inst [3:0] (.\p-in (a), .\p-out (\w ), .*);
sub \u2 (.\c-in );
endmodule
====
# escaped names in expressions: member, index, scope, named argument
module m;
assign \b-out = \iface .\vld [3] & \my-pkg ::\A-0 ;
initial begin
$display("%d", \q .\r );
\f (.\arg-a (1), .b(2));
end
endmodule
----
module m;
assign \b-out = \iface .\vld [3] & \my-pkg ::\A-0 ;
initial begin
$display("%d", \q .\r );
\f (.\arg-a (1), .b(2));
end
endmodule
====
# escaped genvar and generate block label
module m;
genvar \i ;
generate
for (\i = 0; \i < 4; \i = \i + 1) begin : \gen-blk
wire \w ;
end : \gen-blk
endgenerate
endmodule
----
module m;
genvar \i ;
generate
for (\i = 0; \i < 4; \i = \i + 1) begin : \gen-blk
wire \w ;
end : \gen-blk
endgenerate
endmodule
====
# escaped block, fork and statement labels, disable, foreach
module m;
initial begin : \blk-1
\lbl-1 : assert (\st == 0);
disable \blk-1 ;
foreach (\w2 [\i ]) $display("%d", \w2 [\i ]);
fork : \frk-1
join : \frk-1
end : \blk-1
endmodule
----
module m;
initial begin : \blk-1
\lbl-1 : assert (\st == 0);
disable \blk-1 ;
foreach (\w2 [\i ]) $display("%d", \w2 [\i ]);
fork : \frk-1
join : \frk-1
end : \blk-1
endmodule
====
# escaped interface, modport and clocking block
interface \my-if (input \clk );
logic \vld ;
modport \mp-a (input \vld , output \clk );
clocking \cb-1 @(posedge \clk );
input \vld ;
output \drv = \vld ;
endclocking : \cb-1
endinterface : \my-if
----
interface \my-if (input \clk );
logic \vld ;
modport \mp-a (input \vld , output \clk );
clocking \cb-1 @(posedge \clk );
input \vld ;
output \drv = \vld ;
endclocking : \cb-1
endinterface : \my-if
====
# escaped import and export paths
package p;
import \my-pkg ::\thing ;
import \my-pkg ::*;
export \my-pkg ::*;
endpackage
----
package p;
import \my-pkg ::\thing ;
import \my-pkg ::*;
export \my-pkg ::*;
endpackage
====
# a Vivado-style netlist fragment: brackets and dots inside the name
module \netlist-top (\clk );
input \clk ;
wire \u_x/y_reg[3] ;
wire \gen[0].u/z ;
FDRE #(.INIT(1'b0)) \u_x/y_reg[3]_i_1 (.C(\clk ), .D(\gen[0].u/z ), .Q(\u_x/y_reg[3] ));
and \g-1 (\u_x/y_reg[3] , \clk , \gen[0].u/z );
endmodule
----
module \netlist-top (\clk );
input \clk ;
wire \u_x/y_reg[3] ;
wire \gen[0].u/z ;
FDRE #(.INIT(1'b0)) \u_x/y_reg[3]_i_1 (.C(\clk ), .D(\gen[0].u/z ), .Q(\u_x/y_reg[3] ));
and \g-1 (\u_x/y_reg[3] , \clk , \gen[0].u/z );
endmodule
====
# an escaped name inside an aligned port, parameter and connection group
module m (
input logic \clk-i ,
input logic [7:0] \data-i ,
output logic q
);
parameter int \P-A = 1;
parameter int LONGER_NAME = 2;
sub u0 (
.\a-in (\clk-i ),
.bbbb (\data-i ),
.c (q)
);
endmodule
----
module m (
input logic \clk-i ,
input logic [7:0] \data-i ,
output logic q
);
parameter int \P-A = 1;
parameter int LONGER_NAME = 2;
sub u0 (
.\a-in (\clk-i ),
.bbbb (\data-i ),
.c (q)
);
endmodule
====
# escaped let declaration, defparam target and call
module m;
let \max-2 (\a , \b ) = (\a > \b ) ? \a : \b ;
defparam \u-inst .\P-A = 4;
initial \x = \max-2 (1, 2);
endmodule
----
module m;
let \max-2 (\a , \b ) = (\a > \b ) ? \a : \b ;
defparam \u-inst .\P-A = 4;
initial \x = \max-2 (1, 2);
endmodule
====
# escaped case labels
module m;
always_comb begin
case (\st )
\A-0 , \B-1 : \st = 1;
default: \st = 0;
endcase
end
endmodule
----
module m;
always_comb begin
case (\st )
\A-0 , \B-1 : \st = 1;
default: \st = 0;
endcase
end
endmodule
====
# escaped connections keep their terminator when the list breaks
module m;
sub u0 (.\a-in (\some-long-signal-name-here ), .\b-in (\another-long-signal-name ), .\c-in (\third-long-signal-name ));
endmodule
----
module m;
sub u0 (
.\a-in (\some-long-signal-name-here ),
.\b-in (\another-long-signal-name ),
.\c-in (\third-long-signal-name )
);
endmodule
====
# an out-of-class method definition scoped by an escaped class name
function void \my-c ::\do-it ();
endfunction
----
function void \my-c ::\do-it ();
endfunction
====
# SKIP a `pkg::type` chain is joined into one string by the parser, so the
# SKIP boundary between the two escaped names is lost and the safety net
# SKIP rejects the file (no output, no corruption). Fixing it needs
# SKIP `parse_scoped_name` to keep its segments — see the Handshakes section
# SKIP of docs/features/escaped-identifiers/README.md.
module m;
\my-pkg ::\state-t \st ;
endmodule
----
module m;
\my-pkg ::\state-t \st ;
endmodule
====
# an escaped type name widens the alignment column by its terminator
module m (
input \my-t \a-in-with-a-long-name ,
input logic [31:0] bbbb_long_name_here,
output \other-type-t \c-out-long-name
);
endmodule
----
module m (
input \my-t \a-in-with-a-long-name ,
input logic [31:0] bbbb_long_name_here,
output \other-type-t \c-out-long-name
);
endmodule
+119
View File
@@ -1558,3 +1558,122 @@ fn a_null_item_moved_from_one_ifdef_arm_to_the_other_is_rejected() {
"module m;\n`ifdef A\n`else\n wire x;\n ;\n`endif\nendmodule\n",
);
}
// ----------------------------------------------------------------------
// Escaped identifiers (2026-09-02)
// ----------------------------------------------------------------------
//
// An escaped identifier is ended by whitespace and by nothing else (IEEE
// 1800-2017 §5.6.1), so dropping the space the formatter writes after one
// does not just move layout around: the next character is swallowed into the
// name and the token stream changes shape. These are the corruptions the
// choke point in `format.rs` exists to prevent, asserted rejected — the net
// is what stands behind it if a name emission is ever added without going
// through `named`.
#[test]
fn a_semicolon_glued_onto_an_escaped_name_is_rejected() {
// The original bug: `wire \my-signal ;` printed as `wire \my-signal;`,
// whose second token is the identifier `\my-signal;`.
expect_divergence(
"module m;\n wire \\my-signal ;\nendmodule\n",
"module m;\n wire \\my-signal;\nendmodule\n",
);
// The same glue one scope down, where a class body's declaration is laid
// out by a different path than a module item's.
expect_divergence("class c;\n int \\fld ;\nendclass\n", "class c;\n int \\fld;\nendclass\n");
}
#[test]
fn a_connection_that_loses_the_space_before_its_paren_is_rejected() {
// `.\my-port (x)` is three tokens; `.\my-port(x)` is two, the second one
// being the identifier `\my-port(x)` — the whole connection eaten.
expect_divergence(
"module m;\n sub u0 (.\\my-port (x));\nendmodule\n",
"module m;\n sub u0 (.\\my-port(x));\nendmodule\n",
);
}
#[test]
fn two_escaped_names_merged_into_one_are_rejected() {
// `\a \b` are two identifiers; `\a\b` is one.
expect_divergence(
"module m;\n wire \\a \\b ;\nendmodule\n",
"module m;\n wire \\a\\b ;\nendmodule\n",
);
// And the instance-name form of the same merge.
expect_divergence(
"module m;\n \\sub-mod \\u-0 ();\nendmodule\n",
"module m;\n \\sub-mod\\u-0 ();\nendmodule\n",
);
}
#[test]
fn an_escaped_label_glued_to_what_follows_it_is_rejected() {
// A block label shares its line with the first statement, so the
// terminator is the only thing between `\blk` and `x`.
expect_divergence(
"module m;\n initial begin : \\blk x = 1; end\nendmodule\n",
"module m;\n initial begin : \\blkx = 1; end\nendmodule\n",
);
// An end label is terminated by the line break; a layout that folds the
// next keyword onto its line without a space swallows the keyword.
expect_divergence(
"module m;\n initial begin : \\blk\n end : \\blk\nendmodule\n",
"module m;\n initial begin : \\blk\n end : \\blkendmodule\n",
);
}
#[test]
fn the_terminating_space_itself_is_only_whitespace() {
// The flip side: writing the space (or two, where the layout also writes
// one) is a whitespace-only difference, which is what lets the formatter
// add it at all.
verify_equivalence(
"module m;wire \\a ;assign \\a =\\b ;endmodule",
"module m;\n wire \\a ;\n assign \\a = \\b ;\nendmodule\n",
)
.expect("only whitespace between the same tokens");
}
#[test]
fn a_space_dropped_before_a_scope_operator_is_rejected() {
// `join_paths` writes `named(pkg) + "::" + named(item)`; if that first
// `named` call were ever lost, `\a-pkg ::\b-item` (three tokens) would
// print as `\a-pkg::\b-item` — one token, since `::` is not whitespace
// and so does not terminate the escaped name on its own. QA-added
// (2026-09-02): no existing pair attacked this specific position.
expect_divergence(
"package p;\n import \\a-pkg ::\\b-item ;\nendpackage\n",
"package p;\n import \\a-pkg::\\b-item ;\nendpackage\n",
);
}
#[test]
fn an_escaped_name_in_a_scoped_type_is_rejected_rather_than_corrupted() {
// `\my-pkg ::\state-t` is joined into one string by `parse_scoped_name`,
// so the formatter reprints it without the space it cannot know was
// there. The net catches it: an error, never a corrupted file. See the
// Handshakes section of docs/features/escaped-identifiers/README.md.
let src = "module m;\n \\my-pkg ::\\state-t \\st ;\nendmodule\n";
match format_source(src, &Config::default()) {
Err(FormatError::Verification(_)) => {}
other => panic!("expected the net to reject the scoped name, got {other:?}"),
}
}
#[test]
fn escaped_identifiers_survive_a_real_format_run() {
let src = "module \\my-mod (input logic \\a-in , output \\b-out );\n\
wire \\my-signal ;\n\
assign \\b-out = \\my-signal & \\a-in ;\n\
sub \\u-0 (.\\p-in (\\my-signal ), .b(1'b0));\n\
endmodule : \\my-mod\n";
let out = format_source(src, &Config::default()).expect("escaped identifiers format");
assert!(out.contains("wire \\my-signal ;"), "{out}");
assert!(out.contains(".\\p-in (\\my-signal )"), "{out}");
// A name that ends the line needs no space: the newline terminates it,
// and the printer trims the trailing space it was given.
assert!(out.ends_with("endmodule : \\my-mod\n"), "{out}");
assert!(!out.contains(" \n"), "no trailing whitespace: {out}");
}
+23
View File
@@ -1030,6 +1030,29 @@ mod tests {
assert_eq!((err.line, err.col), (1, 15));
}
/// IEEE 1800-2017 §5.6.1: an escaped identifier runs from its `\` to the
/// next whitespace character, which is *not* part of the token. Everything
/// downstream depends on this split — the formatter has to write that
/// terminator back itself, because the token it is handed does not carry
/// it (see `docs/features/escaped-identifiers/README.md`).
#[test]
fn an_escaped_identifier_ends_before_its_terminating_whitespace() {
let toks = kinds("wire \\my-signal ;");
assert_eq!(toks[1], (TokenKind::Ident, "\\my-signal".to_string()));
assert_eq!(toks[2], (TokenKind::Symbol, ";".to_string()));
// Any whitespace ends it, and punctuation ends nothing: `\a;` is one
// identifier that has swallowed the semicolon.
let texts: Vec<String> = kinds("\\a\tb \\c\n\\d ;").into_iter().map(|(_, t)| t).collect();
assert_eq!(texts, ["\\a", "b", "\\c", "\\d", ";", ""]);
assert_eq!(kinds("wire \\a;")[1], (TokenKind::Ident, "\\a;".to_string()));
// A name may end the file: there is nothing left to terminate it.
assert_eq!(kinds("wire \\a")[1], (TokenKind::Ident, "\\a".to_string()));
// The span stops with the text, so `src[span] == text`.
let toks = tokenize("wire \\my-signal ;").unwrap();
let span = toks[1].span;
assert_eq!(&"wire \\my-signal ;"[span.start as usize..span.end as usize], "\\my-signal");
}
#[test]
fn operators() {
let toks = kinds("a <<< b === c !== d <= e");
+330
View File
@@ -0,0 +1,330 @@
# escaped-identifiers
## Goal
Make the formatter safe on escaped identifiers. IEEE 1800-2017 §5.6.1: an
escaped identifier starts at a `\` and runs to the next **whitespace**
character — and to nothing else. The lexer gets this right (the token's text
and span stop before the terminating whitespace, which is then consumed as
ordinary trivia), but every name the formatter printed was emitted bare, so
`wire \my-signal ;` came back as `wire \my-signal;`, whose second token is
the single identifier `\my-signal;`. The safety net caught it every time —
`verification failed: token stream diverges` — so nothing was ever corrupted,
but no file containing an escaped identifier could be formatted at all. That
is the whole class of input Vivado writes (`\u_x/y_reg[3] `,
`\gen[0].u/z `), and lucisv refused all of it.
The fix is one choke point: `format::named` (and its `Doc` twin `name_doc`)
appends the space an escaped name needs, and every name emission in
`format.rs` goes through it.
## Assumptions
- **The lexer's split is the contract.** A name in the AST never carries its
terminating whitespace, so writing it back is the formatter's job, not the
parser's. Pinned by
`lexer::tests::an_escaped_identifier_ends_before_its_terminating_whitespace`.
- **A name never contains whitespace.** `ends_escaped` therefore answers
"does this end inside an escaped identifier?" by looking for a `\` in the
run after the last whitespace, which also answers it for the composites the
AST hands over already joined (`a.\b`, `pkg::\x`, a `bind` head).
- **The space is unconditional.** Where the surrounding layout already writes
a separator, the output carries two (`logic \x = 1'b0;`,
`module \m (…)`). That is legal SystemVerilog, it is a fixed point on the
next pass (whitespace is not in the token stream, so pass 2 rebuilds exactly
the same text), and it is much cheaper than a second rule about what the
next `Doc` happens to be. Escaped identifiers are rare enough that the
cosmetics do not earn the lookahead: zero of the 820 corpus files and zero
of the ~4000 opentitan files contain one.
- **A name at end of line needs no space.** The line break terminates it, and
the printer already trims trailing spaces before every newline it writes
(`Printer::newline`, `BlankLine`, `Verbatim`) as does `render` at EOF — so
`endmodule : \m` prints with no trailing whitespace and stays a fixed
point. This is why no `printer.rs`/`doc.rs` change was needed.
- **`Doc::Verbatim` is only ever emitted right after a line break** (its own
documented contract). It strips trailing spaces before copying source bytes
in, so a name emitted directly in front of one would lose its terminator;
today no such site exists, and the contract is what keeps it that way.
## Handshakes
**Consumed from `vlog_parser`.** `TokenKind::Ident` text for an escaped
identifier is the `\` and everything up to (not including) the terminating
whitespace. Unchanged by this work; now pinned by a lexer test.
**Promised to nobody.** `named`/`name_doc`/`ends_escaped` are private to
`format.rs`. `vlog_refactor::instantiate` carries its own two-line copy of
the same rule (`terminate`/`ends_escaped`, the precedent this followed); the
duplication is deliberate — a shared helper would be a cross-crate public API
with two callers and no third in sight.
**Requested from `vlog_parser` (open, not done here — parser.rs is not this
lane's file).** `Parser::parse_scoped_name` joins a `pkg::name` chain into one
`String`, which erases the boundary between the segments. When a segment is
escaped (`\my-pkg ::\state-t`) the formatter cannot know a space belonged
between them, reprints `\my-pkg::\state-t`, and the safety net rejects the
file — an error, never a corruption. The fix is for the AST to keep the
segments (a `Vec<Name>`, or the per-segment spans) for `DataType::name`,
`Instantiation::module` and `BindDirective::target`; `FunctionDecl::scope`
already works because `parse_method_name` keeps the method's own name apart.
Recorded as a `#SKIP` case in
`crates/vlog_formatter/tests/cases/escaped_identifiers.cases` (the house
mechanism: it must keep failing until the parser fix lands, at which point the
marker has to go) and as
`verification::an_escaped_name_in_a_scoped_type_is_rejected_rather_than_corrupted`.
**`verify.rs` untouched** (invariant 4). Nothing about the safety net was
widened, softened or normalized; the new tests only add attack pairs it
already rejects.
## Status / TODO
- [x] `named` / `name_doc` / `ends_escaped` in `format.rs`, with the audit
list in the doc comment.
- [x] Every name emission routed through it: declarators; ANSI, non-ANSI and
parameter ports; type names; typedef (alias/enum/struct/forward-class)
names; enum members; module, package, interface, class, function, task,
modport, clocking, `let` and genvar names; instance, gate-instance and
instantiated-module names; port connections (`.p`, `.p(x)`, `.p()`) and
named call arguments; `extends`; method scopes; hierarchical `.member`
and `::member`; tf arguments; clocking signals; block, fork and
statement labels; every `end : label` through `Fmt::closing`;
`disable`; `bind` heads; DPI linkage names; `join_names`/`join_paths`.
- [x] `join_paths` rebuilds `pkg::item` from its two `Name`s instead of
`ImportPath::text()`, so an escaped package name keeps its terminator
before the `::`.
- [x] End-of-line ruling: the helper always writes the space; the printer's
existing trailing-space trim removes it before a break. No `printer.rs`
or `doc.rs` change.
- [x] `tests/cases/escaped_identifiers.cases` — 18 live cases + 1 `#SKIP`.
- [x] Attack pairs in `tests/verification.rs` (7 tests).
- [x] Lexer pin in `lexer.rs` tests.
- [x] Corpus proven neutral: no corpus file contains an escaped identifier.
- [ ] (parser lane, not this one) keep `parse_scoped_name`'s segments — see
Handshakes.
## Work log
### 2026-09-02 — dev agent
**The bug.** `wire \my-signal ;` → `verification failed: token stream
diverges … input has identifier "\my-signal" … output has identifier
"\my-signal;"`. Reproduced first, then fixed.
**The choke point.** One private helper in `format.rs`:
```rust
fn named(s: &str) -> String // s, plus a space when it ends escaped
fn name_doc(s: &str) -> Doc // text(named(s))
fn ends_escaped(s: &str) -> bool
```
`ends_escaped` (not a bare `starts_with('\\')`) because several names arrive
as composites the parser already joined — `a.\b` from a `Member`, an
`ImportPath`, a `bind` head — and the question that matters is whether the
*end* of the string is inside an escaped name. It is the same two-line rule
`vlog_refactor::instantiate::ends_escaped` uses for its skeletons.
The audit was a grep of `text(` and `format!(` over `format.rs`, and the
resulting site list lives in the helper's doc comment so the next person
grows it in the same place. 50 emission sites now go through it; the ~25
`format!` splices were rewritten to put the name through `named` rather than
interpolate it (`"{kw} {};"`, `".{}("`, `" extends {}"`, `"{}::"`,
`"disable {};"`, `"{}: "`, `"begin : {}"`, `"{kw} : {}"`, …).
**Deviations from the brief.** Two, both argued above:
1. No `vlog_parser::token::is_escaped` helper was added. The predicate the
formatter actually needs is `ends_escaped`, which is about a *string that
may be a joined path*, not about a token; exporting a `starts_with('\\')`
one-liner from the parser would have been a public API with no user.
2. The `pkg::\type` limitation (Handshakes) is left as a `#SKIP` case plus a
safety-net test rather than fixed here: the fix belongs in `parser.rs`,
which this lane does not own.
**What the output looks like.**
```systemverilog
module \my-mod (input logic \a-in , output \b-out );
wire \my-signal ;
logic \x = 1'b0;
assign \b-out = \my-signal & \a-in ;
sub \u-0 (.\p-in (\my-signal ), .b(\x ));
endmodule : \my-mod
```
Two spaces wherever the layout writes its own separator on top of the
terminator; a single space everywhere the terminator is the only thing
holding two tokens apart; none at end of line.
**Alignment.** The aligned paths (`align::render` for ANSI ports, parameter
declarations and named connections) needed no change: the terminator is part
of the cell text, so the columns are computed with it and the group still
converges. Pinned by the `aligned port, parameter and connection group` case,
which the table harness re-formats a second time; an escaped *type* name
widens the column by its terminator, pinned by a case of its own.
**Gates.** `cargo fmt -p vlog_formatter -p vlog_parser -- --check` clean;
`cargo clippy --all-targets --workspace` zero warnings; `cargo test
--workspace` green (2818 tests, 0 failed — formatter 138 verification, 199
snapshot/fences/ranges and the case tables included);
`scripts/corpus_gate.sh` 813/820 = the baseline, 0 verification errors, 0
crashes. The corpus number is neutral *by construction*: every backslash in
the 860 corpus files is inside a string literal or a comment (`\n`, `\"`, and
ASCII art), so no corpus file exercises the new branch at all. The same holds
for the read-only opentitan sweep: 3869 would-reformat, 97 unchanged, 13
failures — all 13 parse/lex errors, zero verification errors, so nothing in
this change can have moved it.
## QA log
### 2026-09-02 — QA agent
**Gates.** All three green in the worktree:
- `cargo fmt -p vlog_formatter -p vlog_parser -- --check` — clean.
- `cargo clippy --all-targets --workspace` — zero warnings (verified after
`touch`-ing `format.rs`/`lexer.rs` to rule out a stale cache hit).
- `cargo test --workspace` — 2818/0/0 before my addition below, 2819/0/0
after (every `test result:` line summed).
- `scripts/corpus_gate.sh <main-tree corpus>` — `{"passing":813,"total":820,
"pct":99.1,"failures_by_category":{"invalid-or-fragment":3,
"directive-split":1,"macro-items":1,"not-verilog":1,"other":1}}`. Same
baseline, 0 verification errors. (The worktree has no `corpus/` of its own;
ran against the main tree's read-only, as intended — it is data, not code
under test.)
**Scope.** `git status --porcelain` in the worktree matches the README's
file list exactly: `TODO.md`, `format.rs`, `verification.rs`, `lexer.rs`
(tests only, confirmed by diff), plus the two new files (`.cases`, feature
README). `verify.rs` confirmed absent from the diff. `doc.rs`/`printer.rs`
untouched. No `unwrap()`/`expect()`/`panic!` introduced in `format.rs`
(grepped the diff's added lines).
**Corruption hunt.** Built `target/debug/lucisv` in the worktree and
attacked it with 23 scratch files under this session's own scratchpad
(never the worktree's `corpus/` or opentitan) covering every shape in the
brief beyond the 18 cases already in the `.cases` file: punctuation
directly after a name in expressions (`;`, `,`, `)`, `]`, `.`, `::`, `#`,
`=`, `<=`, `(`, `[`), two adjacent escaped names in a port list, EOF with no
trailing newline right after a name, a name before a line comment and
before a block comment, a name with `$`/`{`/`}`/`\` inside, a name spelled
like a keyword/a number, a lone `\ `, a CRLF file, an escaped name inside a
`` `define `` body and inside a multi-line macro call, `bind`, `defparam`,
`import pkg::\x`, a struct member, an enum member, `.\p(\s)` /`.\p()`/
`.\p` (implicit) connections, an instance array, and a hierarchical
`a.\b[1].c`. Every shape formatted successfully (exit 0), reproduced with
`--stdout` piped back through `--stdout` a second time to confirm
byte-identical idempotency, and none of them show any glued token, dropped
space, or merged pair. The one and only rejection (exit 2, no output) was
`\my-pkg ::\state-t` — the filed `parse_scoped_name` gap, exactly as
documented, with the expected diagnostic (`token stream diverges … output
has identifier "\my-pkg::\state-t"`). No other refusals.
| shape | output | safety net verdict |
|---|---|---|
| `;` `,` `)` `]` `.` `::` `#` `=` `<=` `(` `[` after a name in expr/decl context | space kept before each | accepted, idempotent |
| two adjacent escaped names in a port list (`module m(\a , \b )`) | both terminators kept | accepted, idempotent |
| escaped name last thing before EOF, no trailing newline | printer adds final `\n`, no stray space | accepted, idempotent |
| name before `// comment` | space kept, comment intact | accepted, idempotent |
| name before `/* c */;` | space kept, comment and `;` intact | accepted, idempotent |
| `\a$b{c}\d ` | passed through unchanged | accepted, idempotent |
| `\module ` (keyword-shaped) | treated as ordinary escaped ident | accepted, idempotent |
| `\123 ` (number-shaped) | treated as ordinary escaped ident | accepted, idempotent |
| `\ ` (lone backslash) | kept as a one-char escaped ident | accepted, idempotent |
| CRLF file | normalized, content correct | accepted, idempotent |
| name inside `` `define `` body / multi-line macro call | opaque, passed through byte-for-byte | accepted, idempotent |
| `bind \m : \u \c \i (.\p (1));` | every terminator kept | accepted, idempotent |
| `defparam \u .\P = 4;` | terminators kept before `.` and `=` | accepted, idempotent |
| `import \pkg ::\x ;` | terminator kept before `::` | accepted, idempotent |
| escaped struct/enum member, `\sv.\f-a = 1` | terminators kept | accepted, idempotent |
| `.\p (\s )`, `.\p ()`, `.\p` implicit | all three kept correctly | accepted, idempotent |
| instance array `\u [3:0]` | terminator kept before `[` | accepted, idempotent |
| hierarchical `a.\b [1].c` | terminator kept before `[` | accepted, idempotent |
| `\my-pkg ::\state-t \st ;` (scoped type) | **rejected**, no output | matches the filed handshake gap exactly |
**Attack pairs.** Read all 7 tests in `verification.rs`; each is a
plausible corruption (the exact glue `named`/`ends_escaped` exists to
prevent) and each is asserted rejected via `expect_divergence`, plus one
flip-side test confirming the terminator itself is whitespace-only. Found
one gap the brief specifically flagged as worth checking: no existing pair
attacked a **dropped space before `::`** in isolation (the scoped-name test
covers a different failure mode — a parser limitation that makes the file
unformattable, not a masked corruption in already-working code). Added
`a_space_dropped_before_a_scope_operator_is_rejected` in `verification.rs`
(QA-added, noted here): `\a-pkg ::\b-item` vs. the corrupted
`\a-pkg::\b-item`, confirmed rejected. `cargo test -p vlog_formatter --test
verification` now reports 139/0 (was 138/0); full workspace run after the
addition: 2819/0.
**Double-space consequence.** Every case in the `.cases` file that pairs an
escaped name with the layout's own separator gets two spaces, as designed
(`logic \x = 1'b0;`, `module \m (…)`, the aligned type-name case). Checked
specifically for a *third* space or a misaligned column: read `align.rs`'s
`wants_alignment`/`plan` — cell width is measured off the already-terminated
string, so the extra character is baked into the width computation before
alignment ever runs, not added on top of it; confirmed with a 3-connection
aligned group forced to wrap (equal-length escaped port names) — the
existing "nothing to align, widths already equal" short-circuit (predates
this feature) kept it flush, byte-identical on a second pass. No third
space, no misalignment, found in any construction attempted.
**Opentitan (read-only).** Built a second binary from a throwaway
`git worktree add --detach` at `bbf8797` (trunk `v0.25.0`; the main tree's
own `target/release/lucisv` was stale at 0.24.0, so did not use it, and did
not build in the main tree). Ran both binaries with `--check --no-cache`
over `/Users/guoliangchen/repo/opentitan` (first pass without `--no-cache`
showed the worktree run picking up 97 cache hits written by the trunk run
against the *same* `.lucisv_cache` — re-ran both with `--no-cache` to rule
that out as a confound). Results identical in every respect: 3869 would-reformat,
97 unchanged, 13 failed for both; `diff` of the sorted stdout listings is
empty; the 14 stderr lines (13 errors + the summary line) are byte-identical
between trunk and worktree. Of the 13 failures, only one
(`hw/top_darjeeling/ip/ast/rtl/ast.sv`) is among the repo's 3 pre-existing
owner-modified files (`git status` before and after: unchanged, only those
3 files) — the other two owner edits (`hw/ip/aes/dv/tb/tb.sv`,
`hw/top_earlgrey/ip/ast/rtl/ast.sv`) don't fail to parse. Since trunk and
worktree fail on the exact same 13 files for the exact same reasons, the
13-vs-11 gap the dev flagged is not something this feature moved — whatever
caused it predates and is independent of this change. Cleaned up the
throwaway worktree afterward (`git worktree remove --force`); opentitan's
`git status` is exactly the 3 pre-existing owner files, both before and
after.
**Findings.** None that block shipping. One test gap found and fixed
directly (see Attack pairs). No corruption, no scope violation, no gate
regression.
**Verdict: SHIP.**
## Review
## Review
**2026-09-02 — lead.** Approved; merged onto trunk after §18 (the two lanes
ran in parallel per CLAUDE.md — disjoint files, no topo edge).
- The fix is where the lead's map said it had to be: one choke point
(`named`/`name_doc`/`ends_escaped`) with every `format!` splice rewritten
to go through it — fifty sites, audited in the helper's doc comment. The
predicate being `ends_escaped` rather than `starts_with('\\')` is the dev's
correct catch: composites the parser already joined (`a.\b`, import
paths, bind heads) end inside an escaped name without starting with one.
- End-of-line ruling accepted: the space is unconditional and the printer's
existing trim removes it before a break, so no `doc.rs`/`printer.rs`
change. The double space where the layout writes its own separator
(`logic \x = 1'b0;`) is legal, idempotent and — QA checked — never a
third space nor an alignment-column drift; a lookahead rule to make it
prettier is not worth a second code path for a shape hand-written code
almost never contains.
- `verify.rs` untouched; eight attack pairs (seven from the dev, QA's
dropped-space-before-`::`) all rejected. Corpus neutral by construction —
every backslash in the 860 files is inside a string or comment. QA's
opentitan set comparison (trunk vs worktree binaries, `--no-cache` after
spotting the shared-cache confound) is identical file-for-file.
- Open handshake carried forward, honestly stated: `parse_scoped_name` joins
`\my-pkg ::\state-t` into one string, so such a file is *refused* (exit 2),
never corrupted — pinned by the cases file's `#SKIP` and a verification
test that must keep failing-to-format until the parser keeps the
segments. Filed as `docs/topo.md` §2.9-21.
- Gates in the worktree: fmt clean, clippy zero warnings, 2 819 passed /
0 failed, corpus 813/820.