WIP checkpoint, §32 paused 2026-09-03 — runaway root cause fixed (list_ends on an unmoved cursor), strict parity restored; 32.1–32.5 done, 32.6 half, 32.7 + gates not run
Root cause of the 100 GB crash: a non-ANSI port loop took its trailing
comma from the element, an error element never got that far, the next
iteration failed on the same comma, consumed nothing and pushed another
empty error element - an allocating spin. Fix is structural: list_ends
ends the list whenever the cursor has not moved since the iteration
began; the two loops that read their own separator also eat it after an
error element. Truncate-anywhere + delete-any-character pass under
tools/guard.sh -m 4. Strict parity: element_or_recover declines on a
conditional-compilation directive so split.rs's verbatim rescue still
runs. cargo test -p vlog_parser 365 + 26 + 31 / 0 failed; workspace
suite NOT re-run since the last fixes. Not done: completion pin + the
three validity probes (32.6), measurements (32.7), README amendments,
coverage_gaps M10, TODO ticks, every gate. Handshake: three
vlog_linter arms (visit.rs walk_param_ports, signals.rs connection
loops) live in the earlier commit 6a15594.
Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
6a15594ae8
commit
f1d44a2a0c
12 files changed
+639
-82
No files matched your search
@@ -155,6 +155,37 @@ mod tests {
|
||||
assert_eq!(published[0].severity, Some(DiagnosticSeverity::ERROR));
|
||||
}
|
||||
|
||||
/// The user-visible contract of header recovery (TODO §32), pinned where
|
||||
/// the user meets it: a typo in a port list costs **one** diagnostic, and
|
||||
/// the module around it survives whole — its name, the ports typed before
|
||||
/// and after the typo, and its body all still in the outline.
|
||||
///
|
||||
/// Before this round the same buffer published two errors (the header, and
|
||||
/// the orphaned `endmodule`), the body re-parsed as file-scope items, and
|
||||
/// the outline had no module in it at all.
|
||||
#[test]
|
||||
fn a_broken_port_list_publishes_one_error_and_keeps_its_module() {
|
||||
let (ws, uri) = doc_of("module m (input a, , input b);\n wire ok;\nendmodule\n");
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let diags = diagnostics(doc);
|
||||
assert_eq!(diags.len(), 1, "{diags:#?}");
|
||||
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::ERROR));
|
||||
assert_eq!(diags[0].range.start.line, 0, "the header's own line");
|
||||
|
||||
// The missing-closer pass explains a *parse* failure; there is no
|
||||
// unclosed block here, so it must add nothing.
|
||||
assert!(crate::pairs::missing_end_diagnostics(doc).is_empty());
|
||||
|
||||
let symbols = crate::symbols::document_symbols(doc);
|
||||
assert_eq!(symbols.len(), 1, "the module is still in the outline");
|
||||
assert_eq!(symbols[0].name, "m");
|
||||
let children = symbols[0].children.as_ref().expect("module contents");
|
||||
let names: Vec<&str> = children.iter().map(|c| c.name.as_str()).collect();
|
||||
assert!(names.contains(&"a"), "the port before the typo: {names:?}");
|
||||
assert!(names.contains(&"b"), "the port after it: {names:?}");
|
||||
assert!(names.contains(&"ok"), "the body: {names:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lex_error_gets_a_visible_range() {
|
||||
// The lexer gives up at end of file, which a trailing newline makes
|
||||
|
||||
@@ -558,10 +558,23 @@ endmodule
|
||||
assert_eq!(hints[1], (2, 10, "clk:".to_string()), "the line before it had é and 🎉");
|
||||
}
|
||||
|
||||
/// A buffer mid-edit still hints where the *positions* are known, and
|
||||
/// stops where they are not.
|
||||
///
|
||||
/// Header recovery (TODO §32) changed the first half: `sub u1 (clk, rst_n`
|
||||
/// used to fail to parse at all, so there was nothing to hint from. Now
|
||||
/// the instantiation survives with both positional connections, and both
|
||||
/// are at the index they were written at, so both are hinted. The second
|
||||
/// half is the rule that replaces "does not parse": a list the parser
|
||||
/// *recovered* inside holds text nobody can index, so `port_sites` and
|
||||
/// `param_sites` decline the whole list rather than mislabel what follows
|
||||
/// the hole.
|
||||
#[test]
|
||||
fn a_buffer_that_does_not_parse_hints_nothing_rather_than_guessing() {
|
||||
fn a_truncated_list_hints_and_a_recovered_one_does_not() {
|
||||
let top = "module top;\n sub u1 (clk, rst_n\n";
|
||||
assert!(hints_of("broken", top).is_empty());
|
||||
assert_eq!(labels(&hints_of("truncated", top)), ["clk:", "rst_n:"]);
|
||||
let holed = "module top;\n sub u1 (clk, .\n wire w;\nendmodule\n";
|
||||
assert!(hints_of("recovered", holed).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -91,18 +91,6 @@ pub enum PortList {
|
||||
NonAnsi(Vec<ListElem<NonAnsiPort>>),
|
||||
}
|
||||
|
||||
impl PortList {
|
||||
/// True when a tolerant parse recovered from an error inside this list.
|
||||
/// Always false on a tree [`crate::parse`] built.
|
||||
pub fn has_error(&self) -> bool {
|
||||
match self {
|
||||
PortList::None | PortList::Empty => false,
|
||||
PortList::Ansi(ports) => ports.iter().any(ListElem::is_error),
|
||||
PortList::NonAnsi(ports) => ports.iter().any(ListElem::is_error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A name-only port in a non-ANSI header (`module m (a, b);`). It has no
|
||||
/// `name_span`: the port *is* its name, so `span` already is that range.
|
||||
#[derive(Debug)]
|
||||
@@ -256,17 +244,6 @@ pub enum Connections {
|
||||
Named(Vec<ListElem<Connection>>),
|
||||
}
|
||||
|
||||
impl Connections {
|
||||
/// True when a tolerant parse recovered from an error inside this list.
|
||||
/// Always false on a tree [`crate::parse`] built.
|
||||
pub fn has_error(&self) -> bool {
|
||||
match self {
|
||||
Connections::Ordered(conns) => conns.iter().any(ListElem::is_error),
|
||||
Connections::Named(conns) => conns.iter().any(ListElem::is_error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct OrderedConn {
|
||||
pub meta: Meta,
|
||||
|
||||
@@ -97,11 +97,14 @@ impl<'a> Parser<'a> {
|
||||
self.bump();
|
||||
after_hash = self.take_gap();
|
||||
self.expect_sym("(")?;
|
||||
let mark = self.diags_mark();
|
||||
let mut list = Vec::new();
|
||||
self.take_list_directives(&mut param_directives, 0);
|
||||
if !self.cur().is_sym(")") {
|
||||
loop {
|
||||
let at = self.pos;
|
||||
list.push(self.element_or_recover(|p| p.parse_connection())?);
|
||||
let recovered = list.last().is_some_and(ListElem::is_error);
|
||||
if let Some(ListElem::Ok(last)) = list.last_mut() {
|
||||
self.take_before_sep(&mut last.meta, ",");
|
||||
}
|
||||
@@ -113,7 +116,7 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
let dirs = self.take_list_directives(&mut param_directives, list.len());
|
||||
if self.list_ends(comma, dirs.any) {
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -124,7 +127,7 @@ impl<'a> Parser<'a> {
|
||||
&mut param_directives,
|
||||
n,
|
||||
);
|
||||
self.close_list(list.iter().any(ListElem::is_error))?;
|
||||
self.close_list(mark)?;
|
||||
params = Some(list);
|
||||
}
|
||||
Ok(ClassExtends {
|
||||
|
||||
@@ -256,6 +256,7 @@ impl<'a> Parser<'a> {
|
||||
Self::push_scope_segment(&mut module, &segment);
|
||||
}
|
||||
let module_span = self.span_from(module_start);
|
||||
let mark = self.diags_mark();
|
||||
let param_comments = self.take_before_open("#");
|
||||
let mut params = None;
|
||||
let mut after_hash = Vec::new();
|
||||
@@ -268,7 +269,9 @@ impl<'a> Parser<'a> {
|
||||
self.take_list_directives(&mut param_directives, 0);
|
||||
if !self.cur().is_sym(")") {
|
||||
loop {
|
||||
let at = self.pos;
|
||||
list.push(self.element_or_recover(|p| p.parse_connection())?);
|
||||
let recovered = list.last().is_some_and(ListElem::is_error);
|
||||
if let Some(ListElem::Ok(last)) = list.last_mut() {
|
||||
self.take_before_sep(&mut last.meta, ",");
|
||||
}
|
||||
@@ -285,7 +288,7 @@ impl<'a> Parser<'a> {
|
||||
// the list, and after a directive only the closing bracket
|
||||
// does — an `` `ifdef`` arm may end without a comma and
|
||||
// still be followed by an `` `else`` arm.
|
||||
if self.list_ends(comma, dirs.any) {
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -297,7 +300,7 @@ impl<'a> Parser<'a> {
|
||||
&mut param_directives,
|
||||
n,
|
||||
);
|
||||
self.close_list(list.iter().any(ListElem::is_error))?;
|
||||
self.close_list(mark)?;
|
||||
params = Some(list);
|
||||
}
|
||||
let mut instances = Vec::new();
|
||||
@@ -308,9 +311,10 @@ impl<'a> Parser<'a> {
|
||||
let dims = self.parse_dims()?;
|
||||
let conn_comments = self.take_before_open("(");
|
||||
self.expect_sym("(")?;
|
||||
let conn_mark = self.diags_mark();
|
||||
let mut conn_directives = Vec::new();
|
||||
let conns = self.parse_connections(&mut conn_directives)?;
|
||||
self.close_list(conns.has_error())?;
|
||||
self.close_list(conn_mark)?;
|
||||
let span = self.span_from(start);
|
||||
self.take_before_sep(&mut meta, ",");
|
||||
let more = self.eat_sym(",");
|
||||
@@ -332,7 +336,12 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
let before_semi = self.gap_before(";");
|
||||
self.expect_sym(";")?;
|
||||
// As in a module header (`Parser::parse_module`): once something in
|
||||
// this instantiation has been reported, a missing `;` is part of the
|
||||
// same typo, and the item is worth more than a second message. It is
|
||||
// what leaves the `wire w;` under a half-typed `sub u (.a(` an item of
|
||||
// the module.
|
||||
self.expect_after_recovery(";", self.recovered_since(mark))?;
|
||||
Ok(Instantiation {
|
||||
module,
|
||||
module_span,
|
||||
@@ -377,7 +386,9 @@ impl<'a> Parser<'a> {
|
||||
if self.at_named_connection() {
|
||||
let mut conns = Vec::new();
|
||||
loop {
|
||||
let at = self.pos;
|
||||
conns.push(self.element_or_recover(|p| p.parse_connection())?);
|
||||
let recovered = conns.last().is_some_and(ListElem::is_error);
|
||||
if let Some(ListElem::Ok(last)) = conns.last_mut() {
|
||||
self.take_before_sep(&mut last.meta, ",");
|
||||
}
|
||||
@@ -389,7 +400,7 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
let dirs = self.take_list_directives(directives, conns.len());
|
||||
if self.list_ends(comma, dirs.any) {
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -402,13 +413,18 @@ impl<'a> Parser<'a> {
|
||||
} else {
|
||||
let mut conns = Vec::new();
|
||||
loop {
|
||||
let at = self.pos;
|
||||
conns.push(self.element_or_recover(|p| p.parse_ordered_connection())?);
|
||||
let recovered = conns.last().is_some_and(ListElem::is_error);
|
||||
let comma = match conns.last() {
|
||||
Some(ListElem::Ok(last)) => last.comma,
|
||||
// A positional connection reads its own separator; an
|
||||
// error element leaves the `,` for the list, as in a
|
||||
// non-ANSI port list.
|
||||
_ => self.eat_sym(","),
|
||||
};
|
||||
let dirs = self.take_list_directives(directives, conns.len());
|
||||
if self.list_ends(comma, dirs.any) {
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,8 +91,9 @@ impl<'a> Parser<'a> {
|
||||
self.bump();
|
||||
self.expect_sym("(")?;
|
||||
let cond = self.cond_or_recover()?;
|
||||
self.expect_after_recovery(")", cond.is_error())?;
|
||||
Ok(StmtKind::While { cond, body: Box::new(self.parse_stmt()?) })
|
||||
let recovered = cond.is_error();
|
||||
self.expect_after_recovery(")", recovered)?;
|
||||
Ok(StmtKind::While { cond, body: Box::new(self.body_after_recovery(recovered)?) })
|
||||
}
|
||||
"do" => {
|
||||
self.bump();
|
||||
@@ -112,8 +113,9 @@ impl<'a> Parser<'a> {
|
||||
self.bump();
|
||||
self.expect_sym("(")?;
|
||||
let count = self.cond_or_recover()?;
|
||||
self.expect_after_recovery(")", count.is_error())?;
|
||||
Ok(StmtKind::Repeat { count, body: Box::new(self.parse_stmt()?) })
|
||||
let recovered = count.is_error();
|
||||
self.expect_after_recovery(")", recovered)?;
|
||||
Ok(StmtKind::Repeat { count, body: Box::new(self.body_after_recovery(recovered)?) })
|
||||
}
|
||||
"forever" => {
|
||||
self.bump();
|
||||
@@ -296,7 +298,7 @@ impl<'a> Parser<'a> {
|
||||
comments.before_close = self.gap_before(")");
|
||||
}
|
||||
self.expect_after_recovery(")", recovered)?;
|
||||
let body = Box::new(self.parse_stmt()?);
|
||||
let body = Box::new(self.body_after_recovery(recovered)?);
|
||||
Ok(StmtKind::For { init, cond, step, comments: Box::new(comments), body })
|
||||
}
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ impl<'a> Parser<'a> {
|
||||
imports.push(HeaderImport { meta, paths });
|
||||
}
|
||||
let param_comments = self.take_before_open("#");
|
||||
let mark = self.diags_mark();
|
||||
let ParamPortList {
|
||||
ports: param_ports,
|
||||
directives: param_directives,
|
||||
@@ -41,12 +42,10 @@ impl<'a> Parser<'a> {
|
||||
let port_comments = self.take_before_open("(");
|
||||
let (ports, port_dangling, port_directives) = self.parse_port_list()?;
|
||||
let before_semi = self.gap_before(";");
|
||||
// A header that already recovered keeps its `;` optional: the missing
|
||||
// one is part of the typo already reported, and the body behind it is
|
||||
// what the module is for.
|
||||
let recovered =
|
||||
param_ports.iter().flatten().any(|p| p.is_error()) || ports.has_error();
|
||||
self.expect_after_recovery(";", recovered)?;
|
||||
// A header that already reported something keeps its `;` optional: the
|
||||
// missing one is part of the typo already reported, and the body
|
||||
// behind it is what the module is for.
|
||||
self.expect_after_recovery(";", self.recovered_since(mark))?;
|
||||
let mut items = Vec::new();
|
||||
while !self.at_body_end(end_kw) {
|
||||
items.push(self.item_or_recover()?);
|
||||
@@ -326,11 +325,14 @@ impl<'a> Parser<'a> {
|
||||
self.bump();
|
||||
out.after_hash = self.take_gap();
|
||||
self.expect_sym("(")?;
|
||||
let mark = self.diags_mark();
|
||||
let mut list = Vec::new();
|
||||
self.take_list_directives(&mut out.directives, 0);
|
||||
if !self.cur().is_sym(")") {
|
||||
loop {
|
||||
let at = self.pos;
|
||||
list.push(self.element_or_recover(|p| p.parse_param_port())?);
|
||||
let recovered = list.last().is_some_and(ListElem::is_error);
|
||||
if let Some(ListElem::Ok(last)) = list.last_mut() {
|
||||
self.take_before_sep(&mut last.meta, ",");
|
||||
}
|
||||
@@ -348,13 +350,13 @@ impl<'a> Parser<'a> {
|
||||
// (`` `else``), or the arm may have been the tail of the list.
|
||||
// In tolerant mode the closing bracket decides on its own; see
|
||||
// [`Parser::list_ends`].
|
||||
if self.list_ends(comma, dirs.any) {
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.dangling = self.take_dangling();
|
||||
self.close_list(list.iter().any(ListElem::is_error))?;
|
||||
self.close_list(mark)?;
|
||||
out.ports = Some(list);
|
||||
Ok(out)
|
||||
}
|
||||
@@ -441,6 +443,7 @@ impl<'a> Parser<'a> {
|
||||
return Ok((PortList::None, Vec::new(), Vec::new()));
|
||||
}
|
||||
self.bump();
|
||||
let mark = self.diags_mark();
|
||||
// Directives before the first port. Harvested here rather than in the
|
||||
// loop below because both the ANSI/non-ANSI decision and the
|
||||
// written-but-empty check read the token after them.
|
||||
@@ -474,7 +477,9 @@ impl<'a> Parser<'a> {
|
||||
if ansi {
|
||||
let mut ports = Vec::new();
|
||||
loop {
|
||||
let at = self.pos;
|
||||
ports.push(self.element_or_recover(|p| p.parse_ansi_port())?);
|
||||
let recovered = ports.last().is_some_and(ListElem::is_error);
|
||||
if let Some(ListElem::Ok(last)) = ports.last_mut() {
|
||||
self.take_before_sep(&mut last.meta, ",");
|
||||
}
|
||||
@@ -486,13 +491,13 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
let dirs = self.take_list_directives(&mut directives, ports.len());
|
||||
if self.list_ends(comma, dirs.any) {
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Comments on their own lines before the `)` belong inside it.
|
||||
let dangling = self.take_dangling();
|
||||
self.close_list(ports.iter().any(ListElem::is_error))?;
|
||||
self.close_list(mark)?;
|
||||
// A trailing comment on the closing line belongs to the last
|
||||
// port — but only when the header did not write a `;` right
|
||||
// after the `)`. `module m (input a) /*c*/ ;` writes its comment
|
||||
@@ -509,18 +514,24 @@ impl<'a> Parser<'a> {
|
||||
} else {
|
||||
let mut ports = Vec::new();
|
||||
loop {
|
||||
let at = self.pos;
|
||||
ports.push(self.element_or_recover(|p| p.parse_non_ansi_port())?);
|
||||
let recovered = ports.last().is_some_and(ListElem::is_error);
|
||||
let comma = match ports.last() {
|
||||
Some(ListElem::Ok(last)) => last.comma,
|
||||
_ => false,
|
||||
// A non-ANSI port reads its own separator, so an error
|
||||
// element — which never got that far — leaves the `,` for
|
||||
// the list to take. Leaving it under the cursor was the
|
||||
// 2026-09-03 runaway: see the work log.
|
||||
_ => self.eat_sym(","),
|
||||
};
|
||||
let dirs = self.take_list_directives(&mut directives, ports.len());
|
||||
if self.list_ends(comma, dirs.any) {
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.close_list(ports.iter().any(ListElem::is_error))?;
|
||||
self.close_list(mark)?;
|
||||
Ok((PortList::NonAnsi(ports), dangling, directives))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
//!
|
||||
//! See `docs/features/header-recovery/README.md`.
|
||||
|
||||
use super::directive::{closes_conditional, continues_conditional, opens_conditional};
|
||||
use super::*;
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
@@ -35,21 +36,49 @@ impl<'a> Parser<'a> {
|
||||
self.at_eof() || t.is_sym(")") || t.is_sym(";") || self.at_sync_stop()
|
||||
}
|
||||
|
||||
/// Whether a header list's loop is over, having just read an element that
|
||||
/// was (`comma`) or was not followed by a `,`, with `dirs_any` recording
|
||||
/// whether a compiler directive was harvested after it.
|
||||
/// Whether a header list's loop is over. `start` is the cursor the
|
||||
/// iteration began at, `comma` whether a `,` followed the element just
|
||||
/// read, `dirs_any` whether a compiler directive did, and `recovered`
|
||||
/// whether that element was an error the list recovered from.
|
||||
///
|
||||
/// Strict mode asks exactly what the loops asked before this file
|
||||
/// existed. Tolerant mode asks the closing bracket instead of the comma: a
|
||||
/// missing `,` in the middle of a port list would otherwise throw away
|
||||
/// every port after it. On a list that parses the two agree — the loops
|
||||
/// all end with the cursor on their `)` — which is what keeps a tolerant
|
||||
/// parse of a good file identical to a strict one.
|
||||
pub(super) fn list_ends(&self, comma: bool, dirs_any: bool) -> bool {
|
||||
if self.tolerant {
|
||||
return self.at_list_end();
|
||||
/// Strict mode asks exactly what the loops asked before this file existed,
|
||||
/// and looks at neither `start` nor `recovered`. Tolerant mode asks four
|
||||
/// things:
|
||||
///
|
||||
/// * **progress**: an iteration that consumed no token ends the list, full
|
||||
/// stop. This is the termination guarantee, and it is structural rather
|
||||
/// than argued — no reasoning about what an element parser or a skip did
|
||||
/// can make one of these loops spin, because the loop itself refuses to
|
||||
/// go round again on an unmoved cursor. (It *was* argued before, and the
|
||||
/// argument had a hole: see the work log for 2026-09-03.)
|
||||
/// * the **closing bracket**, not the comma — a missing `,` in the middle
|
||||
/// of a port list would otherwise throw away every port after it. On a
|
||||
/// list that parses, the two agree: every one of these loops ends with
|
||||
/// the cursor on its own `)`, which is what keeps a tolerant parse of a
|
||||
/// good file identical to a strict one. Reading on past a missing comma
|
||||
/// is not silent — it is one diagnostic, recorded here.
|
||||
/// * after a **recovered** element, the comma decides again: the skip ends
|
||||
/// at the separator when there is one, so no comma means the list is not
|
||||
/// there any more and what follows belongs to the enclosing construct.
|
||||
/// That is what leaves the `wire w;` under a half-typed `sub u (.a(` as
|
||||
/// an item of the module instead of swallowing it into the list.
|
||||
pub(super) fn list_ends(
|
||||
&mut self,
|
||||
start: usize,
|
||||
comma: bool,
|
||||
dirs_any: bool,
|
||||
recovered: bool,
|
||||
) -> bool {
|
||||
if !self.tolerant {
|
||||
return (!comma && !dirs_any) || (dirs_any && self.cur().is_sym(")"));
|
||||
}
|
||||
(!comma && !dirs_any) || (dirs_any && self.cur().is_sym(")"))
|
||||
if self.pos == start || self.at_list_end() || (recovered && !comma) {
|
||||
return true;
|
||||
}
|
||||
if !comma && !dirs_any {
|
||||
self.record("expected `,`");
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Parse one element of a bracketed header list; in tolerant mode turn a
|
||||
@@ -63,26 +92,59 @@ impl<'a> Parser<'a> {
|
||||
let start = self.here();
|
||||
match parse(self) {
|
||||
Ok(value) => Ok(ListElem::Ok(value)),
|
||||
Err(e) if self.tolerant => {
|
||||
Err(e) if self.tolerant && !self.at_conditional_directive() => {
|
||||
Ok(ListElem::Error(self.recover_element(start_pos, start, e)))
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Consume the `)` that closes a header list.
|
||||
/// True on a `` `ifdef `` / `` `ifndef `` / `` `else `` / `` `elsif `` /
|
||||
/// `` `endif ``: a directive that opens, continues or closes a
|
||||
/// conditional-compilation region.
|
||||
///
|
||||
/// In tolerant mode a missing one is not a failure: with `recovered` set,
|
||||
/// the element that failed has already said what is wrong and a second
|
||||
/// message about the same typo would be noise; without it, the missing
|
||||
/// bracket is itself the news and gets one diagnostic. Strict mode fails
|
||||
/// with exactly the message [`Parser::expect_sym`] would have used.
|
||||
pub(super) fn close_list(&mut self, recovered: bool) -> PResult<()> {
|
||||
/// A list element that failed *there* is one arm of a construct written
|
||||
/// across the arms of a region — a header split by `` `ifdef `` — and the
|
||||
/// enclosing item or statement captures the whole of it verbatim
|
||||
/// (`split.rs`). Balanced directives never reach here at all;
|
||||
/// `take_list_directives` harvests those between elements. So this error
|
||||
/// is passed out untouched: recovering it would take that rescue away and
|
||||
/// give a file the strict parser reads *correctly* a different tree, which
|
||||
/// is the one thing tolerant mode may never do. Found by
|
||||
/// `tolerant_parse_equals_strict_parse_on_valid_sources` over
|
||||
/// `directive_in_statements.cases`; see the work log for 2026-09-03.
|
||||
fn at_conditional_directive(&self) -> bool {
|
||||
let t = self.cur();
|
||||
opens_conditional(t) || continues_conditional(t) || closes_conditional(t)
|
||||
}
|
||||
|
||||
/// How many diagnostics stand recorded — a mark to ask
|
||||
/// [`Parser::recovered_since`] about later. Always 0 in strict mode, which
|
||||
/// is what makes every question asked of it answer "no" there.
|
||||
pub(super) fn diags_mark(&self) -> usize {
|
||||
self.diagnostics.len()
|
||||
}
|
||||
|
||||
/// Whether anything was reported since `mark`: whether the header being
|
||||
/// parsed has already told the user what is wrong with it.
|
||||
pub(super) fn recovered_since(&self, mark: usize) -> bool {
|
||||
self.diagnostics.len() > mark
|
||||
}
|
||||
|
||||
/// Consume the `)` that closes a header list, `mark` being the diagnostic
|
||||
/// count when the list began.
|
||||
///
|
||||
/// In tolerant mode a missing one is not a failure: where the list already
|
||||
/// reported something, that message is the one about this typo and a
|
||||
/// second would be noise; where it did not, the missing bracket is itself
|
||||
/// the news and gets one diagnostic. Strict mode fails with exactly the
|
||||
/// message [`Parser::expect_sym`] would have used.
|
||||
pub(super) fn close_list(&mut self, mark: usize) -> PResult<()> {
|
||||
if self.eat_sym(")") {
|
||||
return Ok(());
|
||||
}
|
||||
if self.tolerant {
|
||||
if !recovered {
|
||||
if !self.recovered_since(mark) {
|
||||
self.record("expected `)`");
|
||||
}
|
||||
return Ok(());
|
||||
@@ -105,6 +167,23 @@ impl<'a> Parser<'a> {
|
||||
self.expect_sym(sym).map(|_| ())
|
||||
}
|
||||
|
||||
/// The body of a statement whose header was recovered.
|
||||
///
|
||||
/// Where the enclosing block or file has already ended — `for (i = 0; i <`
|
||||
/// with an `end` under it — there is no statement to read, and reading one
|
||||
/// would consume the `end` the block is waiting for. The body is then an
|
||||
/// empty error leaf: a loop with nothing typed in it yet is still a loop,
|
||||
/// and inventing a `;` would put a token in the tree the source never
|
||||
/// wrote. Reached only in tolerant mode, and only after a recovery.
|
||||
pub(super) fn body_after_recovery(&mut self, recovered: bool) -> PResult<Stmt> {
|
||||
if !(recovered && self.tolerant && (self.at_eof() || self.at_sync_stop())) {
|
||||
return self.parse_stmt();
|
||||
}
|
||||
let span = TextRange::empty(self.here());
|
||||
let raw = RawText { text: String::new(), col: self.cur().col, span };
|
||||
Ok(Stmt { meta: Meta::default(), kind: StmtKind::Error(raw), before_semi: Vec::new(), span })
|
||||
}
|
||||
|
||||
/// The condition between the brackets of an `if`, `while`, `repeat`,
|
||||
/// `case` or `do … while` header, whose `(` the caller has consumed.
|
||||
///
|
||||
|
||||
@@ -162,8 +162,9 @@ impl<'a> Parser<'a> {
|
||||
let after_kw = self.take_before_open("(");
|
||||
self.expect_sym("(")?;
|
||||
let cond = self.cond_or_recover()?;
|
||||
self.expect_after_recovery(")", cond.is_error())?;
|
||||
let then = Box::new(self.parse_stmt()?);
|
||||
let recovered = cond.is_error();
|
||||
self.expect_after_recovery(")", recovered)?;
|
||||
let then = Box::new(self.body_after_recovery(recovered)?);
|
||||
let mut else_comments = Vec::new();
|
||||
let els = if self.cur().is_kw("else") {
|
||||
// Whatever was written in the gap before `else` stays on the
|
||||
|
||||
@@ -221,8 +221,11 @@ impl<'a> Parser<'a> {
|
||||
self.bump();
|
||||
return Ok(TfPorts { args, dangling });
|
||||
}
|
||||
let mark = self.diags_mark();
|
||||
loop {
|
||||
let at = self.pos;
|
||||
args.push(self.element_or_recover(|p| p.parse_tf_arg(allow_unnamed))?);
|
||||
let recovered = args.last().is_some_and(ListElem::is_error);
|
||||
let more;
|
||||
if let Some(ListElem::Ok(last)) = args.last_mut() {
|
||||
self.take_before_sep(&mut last.meta, ",");
|
||||
@@ -231,14 +234,14 @@ impl<'a> Parser<'a> {
|
||||
} else {
|
||||
more = self.eat_sym(",");
|
||||
}
|
||||
if self.list_ends(more, false) {
|
||||
if self.list_ends(at, more, false, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let Some(ListElem::Ok(last)) = args.last_mut() {
|
||||
self.take_before_sep(&mut last.meta, ")");
|
||||
}
|
||||
self.close_list(args.iter().any(ListElem::is_error))?;
|
||||
self.close_list(mark)?;
|
||||
Ok(TfPorts { args, dangling: Vec::new() })
|
||||
}
|
||||
|
||||
|
||||
@@ -490,18 +490,199 @@ fn a_half_typed_declaration_is_one_error_node() {
|
||||
assert!(m.end_label.is_none());
|
||||
}
|
||||
|
||||
/// **Inverted by header recovery (TODO §32).** Until 2026-09-03 the unclosed
|
||||
/// `(` swallowed everything up to the next `;` and the whole instantiation was
|
||||
/// one `ItemKind::Error`, `wire w;` included. Now the instantiation keeps its
|
||||
/// name and the connection that was typed, the half-typed one is an error
|
||||
/// *element*, and the declaration under it is an item of the module again.
|
||||
#[test]
|
||||
fn a_half_typed_instantiation_is_one_error_node() {
|
||||
fn a_half_typed_instantiation_costs_one_connection() {
|
||||
let src = "module m;\n sub u0 (.a(\n wire w;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
let m = module_named(&file, "m");
|
||||
// The unclosed `(` swallows what follows it up to the sync point: a
|
||||
// bracket the skip did not open ends it, otherwise the `;`.
|
||||
assert!(matches!(&m.items[0].kind, ItemKind::Error(_)), "{}", kind_name(&m.items[0]));
|
||||
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
|
||||
panic!("expected an instantiation, got {}", kind_name(&m.items[0]))
|
||||
};
|
||||
assert_eq!(inst.module, "sub");
|
||||
assert_eq!(inst.instances[0].name, "u0");
|
||||
let Connections::Named(conns) = &inst.instances[0].conns else { panic!("named connections") };
|
||||
assert_eq!(conns.len(), 1);
|
||||
assert_eq!(conns[0].error().map(|r| r.text.as_str()), Some(".a("));
|
||||
// The line under the broken connection is the module's again, not part of
|
||||
// the list: `wire w;` is a sibling item.
|
||||
assert!(matches!(&m.items[1].kind, ItemKind::DataDecl(_)), "{}", kind_name(&m.items[1]));
|
||||
assert_eq!(error_nodes(&file).len(), 1);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Header recovery (TODO §32): one test per shape, with exact counts
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// (a) The QA shape this round was written for: a parameter with no value.
|
||||
/// One diagnostic, one item, and a module that still holds its body.
|
||||
#[test]
|
||||
fn a_half_typed_parameter_costs_one_parameter() {
|
||||
let src = "module m #(parameter W = , parameter X = 4) (input a); wire ok; endmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
assert_eq!(file.items.len(), 1, "{:?}", file.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let m = module_named(&file, "m");
|
||||
let params = m.param_ports.as_ref().expect("a parameter port list");
|
||||
assert_eq!(params.len(), 2);
|
||||
assert_eq!(params[0].error().map(|r| r.text.as_str()), Some("parameter W ="));
|
||||
assert_eq!(params[1].ok().map(|p| p.name.as_str()), Some("X"));
|
||||
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
|
||||
assert_eq!(ports.len(), 1);
|
||||
assert_eq!(ports[0].ok().map(|p| p.name.as_str()), Some("a"));
|
||||
assert_eq!(m.items.len(), 1, "the body survives the header");
|
||||
assert!(matches!(&m.items[0].kind, ItemKind::DataDecl(_)), "{}", kind_name(&m.items[0]));
|
||||
}
|
||||
|
||||
/// (b) The missing comma of a port half typed on the line above: the list
|
||||
/// reads on to the ports after it, and says once that the `,` is missing.
|
||||
#[test]
|
||||
fn a_missing_comma_in_a_port_list_keeps_the_ports_after_it() {
|
||||
let src = "module m (input logic a, inp\n output b);\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
assert!(diags[0].message.starts_with("expected `,`"), "{}", diags[0]);
|
||||
let PortList::Ansi(ports) = &module_named(&file, "m").ports else { panic!("ANSI ports") };
|
||||
let names: Vec<&str> = ports.iter().filter_map(|p| p.ok()).map(|p| p.name.as_str()).collect();
|
||||
assert_eq!(names, ["a", "inp", "b"], "the port after the typo survives");
|
||||
assert_eq!(error_nodes(&file).len(), 0, "a missing comma costs no element");
|
||||
}
|
||||
|
||||
/// (c) A parameter list truncated at end of file — the mid-edit state itself.
|
||||
/// The module keeps the parameter that was typed; the two diagnostics are the
|
||||
/// unclosed `)` and the unclosed module, one each.
|
||||
#[test]
|
||||
fn a_parameter_list_truncated_at_eof_keeps_its_module() {
|
||||
let src = "module m #(parameter W = 8,\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 2, "{diags:?}");
|
||||
assert!(diags[0].message.starts_with("expected `)`"), "{}", diags[0]);
|
||||
assert!(diags[1].message.starts_with("expected `endmodule`"), "{}", diags[1]);
|
||||
let m = module_named(&file, "m");
|
||||
let params = m.param_ports.as_ref().expect("a parameter port list");
|
||||
assert_eq!(params.len(), 1);
|
||||
assert_eq!(params[0].ok().map(|p| p.name.as_str()), Some("W"));
|
||||
}
|
||||
|
||||
/// (d) The `for` header the error-recovery README documented as costing two
|
||||
/// diagnostics: the `;`s inside it are invisible to the skip now, so it costs
|
||||
/// one, and the loop keeps its body.
|
||||
#[test]
|
||||
fn a_half_typed_for_header_keeps_the_loop_and_its_body() {
|
||||
let src = "module m;\n initial begin\n for (i = 0; i < ; i = i + 1) x = 1;\n y = 2;\n end\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
let m = module_named(&file, "m");
|
||||
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") };
|
||||
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
|
||||
assert_eq!(stmts.len(), 2, "the statement after the loop is untouched");
|
||||
let StmtKind::For { cond, body, .. } = &stmts[0].kind else { panic!("expected a for") };
|
||||
let Some(Expr { kind: ExprKind::Error(raw), .. }) = cond else {
|
||||
panic!("expected an error condition")
|
||||
};
|
||||
assert_eq!(raw.text, "i = 0; i < ; i = i + 1");
|
||||
assert!(matches!(body.kind, StmtKind::Assign { .. }), "the body is the `x = 1;`");
|
||||
assert!(matches!(stmts[1].kind, StmtKind::Assign { .. }));
|
||||
}
|
||||
|
||||
/// (d′) The same header truncated mid-condition, where the block ends right
|
||||
/// under it: the loop survives with an empty body rather than eating the
|
||||
/// `end` its block is waiting for.
|
||||
#[test]
|
||||
fn a_for_header_truncated_mid_condition_does_not_eat_the_end() {
|
||||
let src = "module m;\n initial begin\n for (int i = 0; i <\n end\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
let m = module_named(&file, "m");
|
||||
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") };
|
||||
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
|
||||
assert_eq!(stmts.len(), 1);
|
||||
let StmtKind::For { cond, body, .. } = &stmts[0].kind else { panic!("expected a for") };
|
||||
assert!(matches!(cond, Some(Expr { kind: ExprKind::Error(_), .. })));
|
||||
let StmtKind::Error(raw) = &body.kind else { panic!("expected an empty body") };
|
||||
assert_eq!(raw.text, "", "nothing was typed there, and nothing is invented");
|
||||
}
|
||||
|
||||
/// (f) A formal list left open, with the body under it: the function and the
|
||||
/// module around it both survive.
|
||||
#[test]
|
||||
fn a_half_typed_formal_list_keeps_its_function() {
|
||||
let src = "module m;\n function int f(input int a,\n f = a;\n endfunction\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 1);
|
||||
let ItemKind::Function(f) = &m.items[0].kind else {
|
||||
panic!("expected a function, got {}", kind_name(&m.items[0]))
|
||||
};
|
||||
assert_eq!(f.name, "f");
|
||||
assert_eq!(f.args.first().and_then(|a| a.ok()).map(|a| a.name.as_str()), Some("a"));
|
||||
}
|
||||
|
||||
/// (g) A condition left open, with the statements under it: the `if` keeps
|
||||
/// its shape and its then-branch.
|
||||
#[test]
|
||||
fn a_half_typed_if_condition_keeps_its_branch() {
|
||||
let src = "module m;\n initial begin\n if (a &&\n x = 1;\n y = 2;\n end\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
let m = module_named(&file, "m");
|
||||
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") };
|
||||
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
|
||||
assert_eq!(stmts.len(), 1);
|
||||
let StmtKind::If { cond, then, els, .. } = &stmts[0].kind else { panic!("expected an if") };
|
||||
assert!(matches!(cond.kind, ExprKind::Error(_)), "{:?}", cond.kind);
|
||||
assert!(els.is_none());
|
||||
assert!(matches!(then.kind, StmtKind::Assign { .. }), "the branch is the `y = 2;`");
|
||||
}
|
||||
|
||||
/// The other statement headers recover through the same helper, so one test
|
||||
/// covers them: each keeps its node, its body and exactly one diagnostic.
|
||||
#[test]
|
||||
fn the_other_statement_headers_recover_the_same_way() {
|
||||
let shapes: &[(&str, &str)] = &[
|
||||
("while", "module m;\n initial begin\n while (a &&\n x = 1;\n end\nendmodule\n"),
|
||||
("repeat", "module m;\n initial begin\n repeat (a &&\n x = 1;\n end\nendmodule\n"),
|
||||
("case", "module m;\n initial begin\n case (a &&\n x = 1;\n endcase\n end\nendmodule\n"),
|
||||
];
|
||||
for (name, src) in shapes {
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{name}: {diags:?}");
|
||||
let m = module_named(&file, "m");
|
||||
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("{name}: expected initial") };
|
||||
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("{name}: expected a block") };
|
||||
let kind = &stmts[0].kind;
|
||||
let cond = match kind {
|
||||
StmtKind::While { cond, .. } => cond,
|
||||
StmtKind::Repeat { count, .. } => count,
|
||||
StmtKind::Case { expr, .. } => expr,
|
||||
other => panic!("{name}: {:?}", std::mem::discriminant(other)),
|
||||
};
|
||||
assert!(matches!(cond.kind, ExprKind::Error(_)), "{name}: {:?}", cond.kind);
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole point, stated once: a broken header no longer costs the module.
|
||||
/// This is the shape the error-recovery README's QA finding described — three
|
||||
/// items and two diagnostics — measured again here as one and one.
|
||||
#[test]
|
||||
fn a_broken_header_no_longer_distorts_the_tree() {
|
||||
let src = "module m #(parameter W = , parameter X = 4) (input a);\n wire ok;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
assert_eq!(file.items.len(), 1, "the body no longer re-parses at file scope");
|
||||
let m = module_named(&file, "m");
|
||||
assert!(m.end_label.is_none() && !m.items.is_empty());
|
||||
// And no orphaned `endmodule` behind it.
|
||||
assert!(!file.items.iter().any(|i| matches!(i.kind, ItemKind::Error(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_between_two_modules_leaves_both_intact() {
|
||||
for garbage in ["@#!", "foo bar baz", "???", "wire", "end", "* ) ]"] {
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
# header-recovery
|
||||
|
||||
## Goal
|
||||
|
||||
`docs/features/error-recovery/README.md` recovers in item and statement
|
||||
**lists** only, so an error anywhere inside a *header* escapes to the nearest
|
||||
enclosing list and takes the whole construct with it: a typo in a port list,
|
||||
parameter list, formal list or connection list destroys the `Module`,
|
||||
`FunctionDecl` or `Instantiation` it was written in, the body then re-parses at
|
||||
the wrong scope, and the orphaned `endmodule` becomes a second error item. Two
|
||||
diagnostics and a misleading tree for one missing comma — the state an editor
|
||||
buffer is in most of the time. This feature (TODO §32) adds recovery *inside*
|
||||
those headers: a list element that does not parse becomes an
|
||||
`ListElem::Error(RawText)` element of its list, a statement header's condition
|
||||
that does not parse becomes an `ExprKind::Error(RawText)`, and the construct
|
||||
around it keeps its name, the elements that were typed and its body. Strict
|
||||
parsing is untouched — every new branch sits behind `self.tolerant` on the
|
||||
error path — so the formatter's "zero errors or nothing" contract and the
|
||||
byte-identity of every corpus file are unchanged.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A header's error element is a leaf, not a guess.** The parser does not try
|
||||
to work out what the user meant by the text it skipped; the element records
|
||||
the bytes and its span, and every consumer decides what to do with it. The
|
||||
variant exists so that consumers *must* decide: a `Vec<AnsiPort>` that
|
||||
silently hid the hole would let the LSP mislabel what follows it.
|
||||
- **The skip is list-local and bracket-seeded.** The bracket counter starts at
|
||||
one — the list's own open bracket, already consumed — so a `;` inside a
|
||||
`for (…; …; …)` header is invisible and no skip can run past the bracket that
|
||||
closes the list it is in.
|
||||
- **One line-based rule.** A skip stops at the first token of a new line. It is
|
||||
the only line-based rule in the parser, and it is what makes
|
||||
`module m (input logic a, inp⏎ output b);` cost one comma instead of the rest
|
||||
of the list.
|
||||
- **A recovered element ends its list unless a `,` follows it.** The skip stops
|
||||
at the separator when there is one; no separator means the list is not there
|
||||
any more and what follows belongs to the enclosing construct. That is what
|
||||
leaves the `wire w;` under a half-typed `sub u (.a(` an item of the module.
|
||||
- **Recovery declines on a conditional-compilation directive.** A list element
|
||||
that fails on `` `ifdef ``/`` `else ``/`` `endif `` is one arm of a construct
|
||||
written across the arms of a region, and the enclosing item or statement
|
||||
captures the whole of it verbatim (`split.rs`). Recovering it here would take
|
||||
that rescue away and give a file the strict parser reads *correctly* a
|
||||
different tree.
|
||||
- **Recovery is not silence.** Every shape still yields at least one
|
||||
diagnostic; a list read on past a missing comma says so, and a bracket or `;`
|
||||
missing behind an already-reported typo is the only thing taken silently.
|
||||
- **A recovered header may still swallow the line the failure was on.** The
|
||||
expression grammar is greedy: `for (int i = 0; i <⏎ x = 1;` reads `x` as the
|
||||
right operand of `<`, so the error node covers that line. The loop survives;
|
||||
the statement that was on the line does not.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `docs/features/error-recovery/README.md`:** the tolerant flag,
|
||||
`recover`, `skip_to_sync`, `at_sync_stop`, `at_body_end` and `expect_closer`
|
||||
are unchanged and still own item- and statement-list recovery. This feature
|
||||
adds a second, smaller mechanism beside them (`parser/recover_list.rs`) and
|
||||
does not touch the first.
|
||||
|
||||
**Promised to `vlog_formatter`:** `format_source` still calls the strict
|
||||
parser, so `ListElem::Error` and `ExprKind::Error` cannot appear in a tree the
|
||||
formatter builds. Three arms were added anyway, because the new variants make
|
||||
its exhaustive matches fail to compile: `ListItem::from_raw` (a header list's
|
||||
error element, printed verbatim), the `ExprKind::Error` arm in `format/expr.rs`
|
||||
(`raw_inline`), and `Fmt::list_elem`, the one-line adapter every header list
|
||||
now maps through. Each says at its definition that it is unreachable from
|
||||
`format_source`, exactly as `ItemKind::Error` does. `verify.rs` is untouched.
|
||||
|
||||
**Promised to `vlog_semantic`:** an error element declares nothing and binds
|
||||
nothing — `bind_param_ports`, `bind_tf_args`, the port-list arms and the new
|
||||
`bind_connections` all skip them, mirroring `bind/item.rs`'s `ItemKind::Error`
|
||||
arm.
|
||||
|
||||
**Requested of the §33 linter lane (Handshake, not a silent edit):** three
|
||||
places in `crates/vlog_linter` had to change for the new variants —
|
||||
`visit.rs`'s `walk_param_ports` (one `filter_map(ListElem::ok)`, since an error
|
||||
element has no name or type for a rule to judge) and `signals.rs`'s two
|
||||
connection loops (an error element's span joins the same opaque-span bucket a
|
||||
connection's does). The lead pre-agreed exhaustive-match arms in that crate;
|
||||
these are that, plus the two-line `match` `signals.rs` needed to keep pushing a
|
||||
span. Named here and in the report for the merge.
|
||||
|
||||
**`vlog_refactor` and `lucisv_server`:** both read tolerant trees (the server's
|
||||
`FileFacts` is `tokenize` + `parse_tolerant` + `analyze`), so both had to
|
||||
decide. Refactor skips error elements for every *name* question and keeps their
|
||||
spans where it asks where the list's text *is* (`ports/list.rs::elem_spans`).
|
||||
The server skips them in `type_def`, and `inlay` declines to hint a list that
|
||||
holds one at all: which port a position names is exactly what the skipped text
|
||||
decides, and a wrong hint is worse than none.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 32.1 `ListElem<T>` (`Ok` / `Error(RawText)`) in the five header lists —
|
||||
a module's and a class's parameter ports, ANSI and non-ANSI ports, a
|
||||
subroutine's formals, named and ordered connections — plus
|
||||
`ExprKind::Error`, with the cross-crate arms above.
|
||||
- [x] 32.2 `element_or_recover` and the list-local, bracket-seeded sync set
|
||||
(`,`, the list's own `)`, `;`, a line change) in
|
||||
`parser/recover_list.rs`.
|
||||
- [x] 32.3 headers keep their node: the four list parsers are infallible in
|
||||
tolerant mode, closers go through `close_list`, and a header that has
|
||||
already reported something takes its `;` silently
|
||||
(`expect_after_recovery`).
|
||||
- [x] 32.4 `for` / `if` / `while` / `repeat` / `case` / `do…while` conditions
|
||||
recover inside the parentheses (`cond_or_recover`, `error_expr`), with
|
||||
`body_after_recovery` so a header truncated above an `end` does not eat
|
||||
it.
|
||||
- [x] 32.5 parser pins per shape with exact counts (9 new tests in
|
||||
`tests/error_recovery.rs`, the half-typed-instantiation pin inverted as
|
||||
planned); `error_recovery.rs`'s walkers and `tests/spans.rs`'s exhaustive
|
||||
walker extended to the new shapes; the 550-source strict/tolerant
|
||||
equality test green.
|
||||
- [x] 32.6 server pins: one diagnostic, the module still in the outline with
|
||||
the ports either side of the typo, `pairs::missing_end_diagnostics`
|
||||
silent (`diagnostics.rs`), and the inlay rule (`inlay.rs`).
|
||||
- [ ] 32.6 the completion pin — `visible_symbols` at a cursor inside a broken
|
||||
header — **not written yet**.
|
||||
- [ ] 32.6 re-check of the three validity probes (`inline.rs`,
|
||||
`templates.rs`, `completion/tiers.rs`) — **not done**.
|
||||
- [ ] 32.7 measurements: `perf.rs`'s `parse_tolerant` harness before/after, and
|
||||
the truncated-corpus diagnostic census — **not run**.
|
||||
- [ ] 32.7 docs: the error-recovery README's Assumptions sentence and its
|
||||
inverted "Not done" line; `docs/coverage_gaps.md` M10; TODO §32 ticks —
|
||||
**not done**.
|
||||
- [ ] Gates: `cargo fmt -p` per crate, `cargo clippy --all-targets --workspace`,
|
||||
`cargo test --workspace` counts, corpus 814/820 byte-identical, the
|
||||
read-only opentitan sweep — **not run** (only the crate suites below).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-03 — dev agent (paused; internet outage)
|
||||
|
||||
**Where this stands.** The tree **builds** (`cargo build --workspace` clean,
|
||||
`cargo check --workspace --all-targets` silent). 32.1–32.5 are in and green;
|
||||
32.6 is half in; 32.7 (docs, measurements) is not started. Nothing is
|
||||
committed. The work sits on `wip-header-recovery` in
|
||||
`.claude/worktrees/recovery`, on top of 6a15594.
|
||||
|
||||
**The two failures the lead reported are both fixed, and both were mine.**
|
||||
|
||||
1. **The runaway (6 GB, machine down).** Root cause, found by a probe that
|
||||
printed every fuzz input before parsing it: deleting the `#` from
|
||||
`sv_features.sv:268` turns `#(parameter …)` into a *port list*, which is
|
||||
read as **non-ANSI** (it opens with the keyword `parameter`, not a type or a
|
||||
direction). `parse_non_ansi_port` reads its own trailing `,`, so I took the
|
||||
loop's `comma` from the element — and an **error** element never got that
|
||||
far, leaving the `,` under the cursor. The next iteration then failed at the
|
||||
same `,`, consumed nothing (a `,` is not a list end, so the always-advance
|
||||
bump declined it, and the skip stops before it), and pushed another empty
|
||||
error element: an allocating spin. My termination argument had assumed every
|
||||
loop ate the comma, which two of the six did not.
|
||||
**The fix is structural, not an argument.** `Parser::list_ends` now takes
|
||||
the cursor the iteration began at and ends the list whenever it has not
|
||||
moved — no reasoning about element parsers or skips can make one of these
|
||||
loops spin, because the loop refuses to go round again on an unmoved cursor.
|
||||
The two loops that read their own separator (non-ANSI ports, positional
|
||||
connections) also eat the `,` after an error element now, so recovery still
|
||||
resumes at the next element rather than merely stopping.
|
||||
2. **The strict-mode parity failure.** `tolerant_parse_equals_strict_parse_on_
|
||||
valid_sources` failed on `directive_in_statements.cases`: an instantiation
|
||||
(and, in a second case, a formal list) written across the arms of a
|
||||
`` `ifdef `` fails in strict mode *by design* and is rescued at item level by
|
||||
`split.rs`, which captures the whole construct verbatim. My list recovery
|
||||
swallowed that failure into an error element, so the rescue never ran and
|
||||
the tolerant tree held an `Instantiation` where the strict tree holds a
|
||||
`Verbatim`. Fix: `element_or_recover` declines — passes the error out
|
||||
untouched — when the cursor stands on a conditional-compilation directive.
|
||||
Balanced directives never reach it (`take_list_directives` harvests those),
|
||||
so this costs nothing else.
|
||||
|
||||
**Measured shapes (a)–(g), after both fixes.** Each is now a pin in
|
||||
`tests/error_recovery.rs`:
|
||||
|
||||
| shape | diagnostics | tree |
|
||||
|---|---|---|
|
||||
| `module m #(parameter W = , parameter X = 4) (input a); wire ok; endmodule` | 1 | one `Module m`, `param_ports` = [error, `X`], port `a`, body `wire ok;` |
|
||||
| `module m (input logic a, inp⏎ output b);` | 1 (`expected \`,\``) | ports `a`, `inp`, `b` — no error element |
|
||||
| `module m #(parameter W = 8,` at EOF | 2 (unclosed `)`, unclosed module) | `Module m` with parameter `W` |
|
||||
| `for (i = 0; i < ; i = i + 1) x = 1;` | 1 (was 2) | `For` with an `Error` condition, body `x = 1;`, the next statement intact |
|
||||
| `for (int i = 0; i <⏎ end` | 1 | `For` with an `Error` condition and an **empty** error body — the `end` its block waits for is not eaten |
|
||||
| `sub u (.a(x), .b(⏎ wire w;` | 1 | the instantiation keeps `.a(x)` and one error element; `wire w;` is a **sibling item** (the old pin inverted, as planned) |
|
||||
| `function int f(input int a,⏎ f = a;⏎ endfunction` | 1 | the function and the module both intact |
|
||||
| `if (a &&⏎ x = 1;⏎ y = 2;` | 1 | `If` with an `Error` condition and `y = 2;` as its branch |
|
||||
|
||||
**Design decisions worth the lead's attention.**
|
||||
|
||||
- **One generic `ListElem<T>` rather than four bespoke enums.** Same two
|
||||
variants in all five lists; one type means one place says what an error
|
||||
element is. Consumers read it through `ok()` / `error()` / `is_error()`.
|
||||
- **"Has this header already reported something?" is asked of the diagnostic
|
||||
count** (`diags_mark` / `recovered_since`), not of the elements. It is always
|
||||
0 in strict mode, so every question asked of it answers "no" there, and it
|
||||
covers a missing closer as well as a broken element.
|
||||
- **`body_after_recovery`** gives a recovered statement header an *empty* error
|
||||
leaf for its body where the enclosing block has already ended, rather than
|
||||
inventing a `;` the source never wrote.
|
||||
- **Cost of the shape change.** `Vec<T>` → `Vec<ListElem<T>>` in five lists
|
||||
touched ~60 sites across six crates. Most are one-line filters; the test
|
||||
churn is absorbed by an `oks()` helper in each test module (strict parses
|
||||
never build an error element, so it is the whole list).
|
||||
|
||||
**Fuzzers, under `tools/guard.sh`.** The truncate-anywhere *and*
|
||||
delete-any-character sweeps over every formatter fixture complete with
|
||||
`-m 4 -t 900` (they exceeded 3 GB before the fix, and 6 GB in the lead's run).
|
||||
`cargo test -p vlog_parser` is green: 365 unit + 26 spans + 31 error-recovery,
|
||||
0 failed. `cargo test --workspace` had one failure left when I stopped — the
|
||||
inlay test below, which I then updated and re-ran green in isolation; the
|
||||
workspace run has **not** been repeated since.
|
||||
|
||||
**Server pins.** `diagnostics.rs` gained
|
||||
`a_broken_port_list_publishes_one_error_and_keeps_its_module` (one diagnostic,
|
||||
`missing_end_diagnostics` silent, the module and the ports either side of the
|
||||
typo in the outline). `inlay.rs`'s
|
||||
`a_buffer_that_does_not_parse_hints_nothing_rather_than_guessing` was replaced
|
||||
by `a_truncated_list_hints_and_a_recovered_one_does_not`: a truncated list now
|
||||
parses, and every position in it is where it was written, so it is hinted; a
|
||||
list with a *hole* is declined whole. `completion/module.rs`'s
|
||||
`a_module_with_an_attribute_near_its_header_is_not_indexed_at_all` split in
|
||||
two — an attribute on a **port** is now one error element and the module is
|
||||
indexed and its header slices, which is the re-audit that test's old message
|
||||
asked for; an attribute between the name and the `#(` is inside no list and is
|
||||
unchanged.
|
||||
|
||||
**Next steps, in order:** the completion pin and the three validity probes
|
||||
(32.6); the `parse_tolerant` timing and the truncated-corpus census (32.7); the
|
||||
error-recovery README amendments, `coverage_gaps.md` M10 and the TODO ticks;
|
||||
then the full gates — `cargo fmt -p` per touched crate,
|
||||
`cargo clippy --all-targets --workspace`, `cargo test --workspace` with counts,
|
||||
the corpus byte-identity run against `/tmp/lucisv-0.35.0-baseline`, and the
|
||||
read-only opentitan sweep. All of them through `tools/guard.sh`.
|
||||
|
||||
## QA log
|
||||
|
||||
*(empty — QA has not run)*
|
||||
|
||||
## Review
|
||||
|
||||
*(reserved for the lead)*
|
||||
Reference in new issue
Block a user