Merge branch 'wip-header-recovery'

# Conflicts:
#	crates/vlog_linter/src/visit.rs
This commit is contained in:
lucio committed 2026-09-04 03:01:49 -05:00
commit 4ba6eafa2d
64 files changed
+2270 -483

No files matched your search

+14 -11
View File
@@ -3454,21 +3454,24 @@ only), crates/lucisv_server/src/perf.rs (measurement only), docs/
features/header-recovery/README.md (new), amendments in error-recovery
README, docs/coverage_gaps.md M10, TODO §32. Runs after §31 (parser +
formatter collide with §30's tf.rs/module.rs at merge; sequential).
- [ ] 32.1 error elements in the four list types + `ExprKind::Error`;
cross-crate arms pre-agreed
- [ ] 32.2 `element_or_recover` with the list-local, bracket-seeded
- [x] 32.1 error elements in the four list types + `ExprKind::Error`;
cross-crate arms pre-agreed — one generic `ListElem<T>` over five
lists (a class's parameter ports are the fifth)
- [x] 32.2 `element_or_recover` with the list-local, bracket-seeded
sync set (`,` `)` `;` line change)
- [ ] 32.3 headers keep their node (port, param, tf-port, connection
- [x] 32.3 headers keep their node (port, param, tf-port, connection
lists infallible in tolerant mode; closers via `expect_closer`)
- [ ] 32.4 `for`/`if`/`while`/`case` conditions recover inside the
parentheses
- [ ] 32.5 parser pins per shape with exact counts; walkers extended;
- [x] 32.4 `for`/`if`/`while`/`case` conditions recover inside the
parentheses (`repeat` and `do…while` too, same helper)
- [x] 32.5 parser pins per shape with exact counts; walkers extended;
550-source equality and the fuzzers green
- [ ] 32.6 server pins: symbols survive, completion scope survives, one
- [x] 32.6 server pins: symbols survive, completion scope survives, one
diagnostic, validity probes unchanged
- [ ] 32.7 docs + measurements (parse_tolerant timing, truncated-corpus
diagnostic census)
- [ ] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
- [x] 32.7 docs + measurements (parse_tolerant timing, truncated-corpus
diagnostic census — error nodes 622 → 555, diagnostics 1 702 →
1 826: the constructs that now survive report their own missing
closers)
- [x] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
byte-identical (strict path untouched); opentitan read-only sweep
unchanged
- [ ] QA: type each of the (a)–(f) shapes into the real server against
+41 -31
View File
@@ -528,39 +528,49 @@ mod tests {
}
}
/// QA finding (performance wave Lane B, 2026-08-28), not a regression this
/// QA finding (performance wave Lane B, 2026-08-28), not a regression that
/// round introduced: a module with an attribute instance (`(* ... *)`)
/// anywhere near its header — right after its name, or on one of its
/// ports — is not indexed as a `Module` unit **at all**.
/// `WorkspaceIndex::units` comes back empty, so [`module_header`] declines
/// at the very first line (no `[def]` to anchor on) before the whitelist
/// walk ever runs, and completion's module tier — which sources its
/// candidate names from the same table — never offers the module in the
/// first place. This is a `vlog_semantic`/`vlog_parser` parsing gap, not a
/// completion-core one: it is filed in `docs/features/completion-core/
/// README.md`'s QA log rather than fixed here, because `vlog_semantic` is
/// outside this round's touched files. The two "attribute" shapes this QA
/// round added to [`SHAPES`] (`attributed`, `port_attributed`) still pass
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] — but only
/// because both sides of that comparison fall back to the same whole-file
/// parse, which this test makes explicit rather than leaving it as an
/// unremarked side effect of the pin.
/// **between its name and its `#(`** is not indexed as a `Module` unit at
/// all. `WorkspaceIndex::units` comes back empty, so [`module_header`]
/// declines at the very first line (no `[def]` to anchor on) before the
/// whitelist walk ever runs, and completion's module tier — which sources
/// its candidate names from the same table — never offers the module in
/// the first place. That attribute sits inside no list, so no recovery
/// reaches it; it is still filed in `docs/features/completion-core/
/// README.md`'s QA log.
///
/// **The `port_attributed` half of the finding was fixed by header
/// recovery** (TODO §32, `docs/features/header-recovery/README.md`): an
/// attribute on a *port* now costs that one port and nothing else — the
/// list keeps a `ListElem::Error` where `(* keep *) output logic q` was
/// written, and the module keeps its name, its other ports and its body,
/// so it is indexed and its header slices for real rather than by
/// whole-file fallback. That is the re-audit the old message asked for,
/// and it is the second half of this test;
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] covers the
/// same shape from the other side.
#[test]
fn a_module_with_an_attribute_near_its_header_is_not_indexed_at_all() {
for module in ["attributed", "port_attributed"] {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
index.units(module).is_empty(),
"{module}: if this starts finding a unit, module_header should be re-audited \
for whether it now slices attributes correctly rather than by lucky fallback"
);
assert!(
module_header(&index, module, text).is_none(),
"{module}: no unit to anchor on"
);
}
fn an_attribute_before_the_parameter_list_still_costs_the_whole_module() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
index.units("attributed").is_empty(),
"if this starts finding a unit, module_header should be re-audited \
for whether it now slices attributes correctly rather than by lucky fallback"
);
assert!(module_header(&index, "attributed", text).is_none(), "no unit to anchor on");
}
#[test]
fn an_attribute_on_a_port_costs_that_port_only() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "port_attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert_eq!(index.units("port_attributed").len(), 1, "the module survives its broken port");
let header = module_header(&index, "port_attributed", text).expect("a sliced header");
assert!(header.starts_with("module port_attributed ("), "{header:?}");
assert!(header.contains("(* keep *) output logic q"), "the port list is kept whole");
}
/// The guard is not decoration: a non-ANSI module really does plan
@@ -513,6 +513,20 @@ endmodule
);
}
/// The premise the probe above rests on, stated as a test: the probe is
/// *discriminating*. Header recovery (TODO §32) widened what a tolerant
/// parse can read, so the question "did this insertion parse?" is only
/// worth asking while text that does **not** parse still says so.
#[test]
fn the_insertion_probe_still_reports_text_that_does_not_parse() {
let broken = "if (cond begin\n\n end";
let probe = format!("module p;\n always_comb begin\n {broken}\n end\nendmodule\n");
assert!(
!vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"recovery must not make a broken insertion look clean: {probe}"
);
}
#[test]
fn a_templates_documentation_shows_what_it_expands_to() {
let top = "module top;\n alw\nendmodule\n";
@@ -896,6 +910,30 @@ endmodule
drop(tree);
}
/// Header recovery (TODO §32) pinned where completion meets it: with a
/// half-typed parameter *above* the cursor, the module still has a scope,
/// so [`visible_symbols`] still answers from it — the parameters and ports
/// already typed are offered inside the very header being edited.
///
/// Before this round the broken header took the whole `Module` node with
/// it, the body re-parsed at file scope, and the scope chain covering this
/// offset held nothing at all.
#[test]
fn a_broken_header_still_completes_from_the_modules_scope() {
let top = "\
module top #(parameter W = , parameter DEPTH = 4) (
input logic clk_i,
output logic DE
);
logic w_local;
endmodule
";
let (_tree, ws, uri, position) = asking("brokenheader", top, "output logic DE");
let found = items(completions(&ws, &uri, position, true));
let item = find(&found, "DEPTH").expect("the parameter typed after the broken one");
assert_eq!(tier(item), TIER_SCOPE, "answered from the module's own scope");
}
/// The scope tier goes fuzzy too, with no mask table behind it — it is
/// the one tier computed per request.
#[test]
+31
View File
@@ -156,6 +156,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
+34 -4
View File
@@ -22,7 +22,7 @@
use std::collections::HashMap;
use lsp_types::{InlayHint, InlayHintKind, InlayHintLabel, Range, Uri};
use vlog_parser::ast::{Connections, Expr, Instance, Instantiation};
use vlog_parser::ast::{Connection, Connections, Expr, Instance, Instantiation, ListElem};
use vlog_parser::TextRange;
use vlog_refactor::InstantiationPlan;
use vlog_semantic::instantiations;
@@ -84,6 +84,13 @@ enum Kind {
/// name is written somewhere in the same list.
fn param_sites(inst: &Instantiation) -> Vec<Site> {
let Some(params) = &inst.params else { return Vec::new() };
// A list a tolerant parse recovered inside gets no hints either: which
// parameter a position names is exactly what the skipped text decides, so
// any hint here would be a guess, and a wrong hint is worse than none.
if params.iter().any(ListElem::is_error) {
return Vec::new();
}
let params: Vec<&Connection> = params.iter().filter_map(ListElem::ok).collect();
if params.iter().any(|param| !param.name.is_empty()) {
return Vec::new();
}
@@ -99,7 +106,16 @@ fn param_sites(inst: &Instantiation) -> Vec<Site> {
/// instance: the connections are the module's ports either way.
fn port_sites(instance: &Instance) -> Vec<Site> {
let Connections::Ordered(conns) = &instance.conns else { return Vec::new() };
conns.iter().enumerate().filter_map(|(index, conn)| site(index, conn.expr.as_ref())).collect()
// As in `param_sites`: a recovered list's positions are a guess.
if conns.iter().any(ListElem::is_error) {
return Vec::new();
}
conns
.iter()
.filter_map(ListElem::ok)
.enumerate()
.filter_map(|(index, conn)| site(index, conn.expr.as_ref()))
.collect()
}
/// A site at the start of `expr`, or nothing for an omitted position
@@ -542,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]
@@ -563,6 +592,7 @@ endmodule
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let insts = instantiations::sites(&tree.items);
let params = insts[0].inst.params.as_ref().expect("a `#( ... )`");
let params: Vec<_> = params.iter().filter_map(ListElem::ok).collect();
assert_eq!(params[0].name, "", "`8` names nothing");
assert_eq!(params[1].name, "DEPTH", "`.DEPTH(16)` does");
}
+14
View File
@@ -1894,6 +1894,20 @@ sub #(
}
}
/// The premise the "the accepted text must parse" probe above rests on:
/// the probe can still fail. Header recovery (TODO §32) widened what a
/// tolerant parse reads — a half-typed connection list is now a recovered
/// instantiation rather than a dead item — so the probe is only worth
/// asking while text that does not parse still says so.
#[test]
fn the_accepted_text_probe_still_reports_text_that_does_not_parse() {
let probe = "module lucisv_probe;\n logic clk;\n sub u_sub (.clk(\nendmodule\n";
assert!(
!vlog_parser::parse_source_tolerant(probe).1.is_empty(),
"recovery must not make a broken instantiation look clean"
);
}
#[test]
fn a_module_with_no_ports_ghosts_a_sane_instantiation() {
let top = "module top;\n bare \nendmodule\n";
+11
View File
@@ -456,6 +456,17 @@ mod tests {
}
}
/// The premise [`every_untouched_expansion_parses`] rests on: the probe
/// can still fail. Header recovery (TODO §32) widened what a tolerant
/// parse reads, and a probe that answered "clean" for everything would
/// pass that test while proving nothing.
#[test]
fn the_expansion_probe_still_reports_text_that_does_not_parse() {
let probe = "module p;\n always_comb begin\n case (sel\n end\nendmodule\n";
let (_, diagnostics) = vlog_parser::parse_source_tolerant(probe);
assert!(!diagnostics.is_empty(), "recovery must not make a broken expansion look clean");
}
#[test]
fn every_hole_is_a_tabstop_the_snippet_grammar_reads() {
// The editor-snippets lesson, restated for generated text: VS Code
+9 -7
View File
@@ -41,7 +41,7 @@
use lsp_types::{Location, Uri};
use vlog_parser::ast::{
AnsiPort, DataType, Declarator, GenBlock, GenElse, GenIf, Instantiation, Item, ItemKind,
Module, ParamPort, PortList, Stmt, StmtKind, StructType, TfArg, TypeExtra, Typedef,
ListElem, Module, ParamPort, PortList, Stmt, StmtKind, StructType, TfArg, TypeExtra, Typedef,
TypedefKind,
};
use vlog_parser::TextRange;
@@ -250,18 +250,20 @@ fn module_site(m: &Module, offset: u32) -> Option<Site<'_>> {
.or_else(|| site_at(&m.items, offset))
}
fn ansi_port_site(ports: &[AnsiPort], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().find(|p| p.span.contains(offset))?;
// The three header lists below skip their error elements: text a tolerant
// parse could not read names no type, so there is no definition to go to.
fn ansi_port_site(ports: &[ListElem<AnsiPort>], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().filter_map(ListElem::ok).find(|p| p.span.contains(offset))?;
site(&port.ty.name, TextRange::new(port.span.start, port.name_span.start))
}
fn param_port_site(ports: &[ParamPort], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().find(|p| p.span.contains(offset))?;
fn param_port_site(ports: &[ListElem<ParamPort>], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().filter_map(ListElem::ok).find(|p| p.span.contains(offset))?;
site(&port.ty.name, TextRange::new(port.span.start, port.name_span.start))
}
fn tf_arg_site(args: &[TfArg], offset: u32) -> Option<Site<'_>> {
let arg = args.iter().find(|a| a.span.contains(offset))?;
fn tf_arg_site(args: &[ListElem<TfArg>], offset: u32) -> Option<Site<'_>> {
let arg = args.iter().filter_map(ListElem::ok).find(|a| a.span.contains(offset))?;
site(&arg.ty.name, TextRange::new(arg.span.start, arg.name_span.start))
}
+10 -2
View File
@@ -38,7 +38,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &c.param_ports {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma))
.map(|p| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma)
})
})
.collect();
let items = self.list_entries(items, &c.param_directives);
let broken = !c.param_directives.is_empty();
@@ -52,7 +56,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &ext.params {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.connection(p)).with_comma(p.comma))
.map(|p| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.connection(p)).with_comma(p.comma)
})
})
.collect();
let items = self.list_entries(items, &ext.param_directives);
let broken = !ext.param_directives.is_empty();
+5
View File
@@ -305,6 +305,11 @@ impl<'a> Fmt<'a> {
// region never begins its own line, so a dedent-by-column would
// drift instead of reaching a fixed point.
ExprKind::Verbatim(raw) => self.raw_inline(raw),
// Unreachable from `format_source`, as `ItemKind::Error` is: only
// a tolerant parse builds this leaf, and the formatter parses
// strictly. Printed verbatim so nothing is lost if that ever
// changes — see `ListItem::from_raw`.
ExprKind::Error(raw) => self.raw_inline(raw),
ExprKind::MinTypMax { min, typ, max } => {
concat(vec![self.expr(min), text(":"), self.expr(typ), text(":"), self.expr(max)])
}
+22 -12
View File
@@ -28,7 +28,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &inst.params {
let items: Vec<ListItem> = params
.iter()
.map(|c| ListItem::from_meta(&c.meta, self.connection(c)).with_comma(c.comma))
.map(|c| {
self.list_elem(c, |c| {
ListItem::from_meta(&c.meta, self.connection(c)).with_comma(c.comma)
})
})
.collect();
let items = self.list_entries(items, &inst.param_directives);
let broken = !inst.param_directives.is_empty() || holds_verbatim_value(params);
@@ -109,19 +113,23 @@ impl<'a> Fmt<'a> {
list.iter()
.zip(&aligns)
.map(|(c, a)| {
ListItem::from_meta(&c.meta, self.connection_aligned(c, a.as_ref()))
.with_comma(c.comma)
self.list_elem(c, |c| {
ListItem::from_meta(&c.meta, self.connection_aligned(c, a.as_ref()))
.with_comma(c.comma)
})
})
.collect()
}
Connections::Ordered(list) => list
.iter()
.map(|c| {
let d = match &c.expr {
Some(e) => self.expr(e),
None => text(""),
};
ListItem::from_meta(&c.meta, d).with_comma(c.comma)
self.list_elem(c, |c| {
let d = match &c.expr {
Some(e) => self.expr(e),
None => text(""),
};
ListItem::from_meta(&c.meta, d).with_comma(c.comma)
})
})
.collect(),
};
@@ -132,18 +140,20 @@ impl<'a> Fmt<'a> {
/// The alignment plan for an instance's named connection list.
fn connection_aligns(
&self,
conns: &[Connection],
conns: &[ListElem<Connection>],
directives: &[ListDirective],
depth: usize,
) -> Vec<Option<Align>> {
let rows: Vec<Option<Row>> = conns
.iter()
.map(|c| {
// An error element has no cells to align, so it has no row.
let c = c.ok()?;
let paren = self.open_paren_offset(c.name_span.end)?;
Self::row_of(&self.connection_cells(c), vec![paren], usize::from(c.comma))
})
.collect();
let breaks = Self::list_breaks(conns.iter().map(|c| &c.meta), directives);
let breaks = Self::list_breaks(conns.iter().map(|c| c.ok().map(|c| &c.meta)), directives);
self.align_groups(&rows, &breaks, CONNECTION_COLS, depth)
}
@@ -369,8 +379,8 @@ impl<'a> Fmt<'a> {
/// be measured as one short line and flattened around a value that is
/// twenty lines tall. It is exactly the reason a list holding a
/// [`ListDirective`] is broken, for exactly the same construct.
fn holds_verbatim_value(list: &[Connection]) -> bool {
list.iter().any(|c| match &c.expr {
fn holds_verbatim_value(list: &[ListElem<Connection>]) -> bool {
list.iter().filter_map(ListElem::ok).any(|c| match &c.expr {
Some(Expr { kind: ExprKind::Verbatim(raw), .. }) => raw.text.contains('\n'),
_ => false,
})
+40 -2
View File
@@ -38,6 +38,27 @@ pub(super) struct ListItem {
}
impl ListItem {
/// The entry an error element of a header list prints as: the text a
/// tolerant parse skipped, verbatim, carrying no comments of its own —
/// they are bytes of that text.
///
/// **Unreachable from `format_source`**, exactly as `ItemKind::Error` is:
/// the formatter parses strictly, and only [`vlog_parser::parse_tolerant`]
/// builds a [`ListElem::Error`]. Printing the bytes rather than nothing
/// means that if some future entry point ever did hand one over,
/// `verify.rs`'s token-equivalence check would see the tokens instead of
/// silently losing them.
pub(super) fn from_raw(doc: Doc) -> Self {
ListItem {
leading: Vec::new(),
doc,
before_sep: Vec::new(),
trailing: None,
comma: None,
directive: false,
}
}
pub(super) fn from_meta(meta: &Meta, doc: Doc) -> Self {
ListItem {
leading: meta.leading.clone(),
@@ -58,6 +79,20 @@ impl ListItem {
}
impl<'a> Fmt<'a> {
/// One entry of a **header** list: the element as `entry` prints it, or —
/// for an error element — its bytes; see [`ListItem::from_raw`] for why
/// the second case cannot be reached from `format_source`.
pub(super) fn list_elem<T>(
&self,
elem: &ListElem<T>,
entry: impl FnOnce(&T) -> ListItem,
) -> ListItem {
match elem {
ListElem::Ok(v) => entry(v),
ListElem::Error(raw) => ListItem::from_raw(self.raw_text(raw)),
}
}
/// A bracketed expression list (concatenation, call arguments, `inside`
/// set). Comments on an element ride along and break the list open.
pub(super) fn expr_list(&self, open: &str, items: &[ExprItem], close: &str) -> Doc {
@@ -316,15 +351,18 @@ impl<'a> Fmt<'a> {
/// with a comment or an attribute of their own — both print on their own
/// line — and those a compiler directive was written in front of.
///
/// A `None` meta is an error element, which has none; it always starts a
/// group, being raw bytes of a width no other row shares.
///
/// A blank line is deliberately *not* a boundary here: `delimited` drops
/// blank lines between list elements, so a boundary drawn at one would
/// vanish from the output and the next pass would group differently.
pub(super) fn list_breaks<'m>(
metas: impl Iterator<Item = &'m Meta>,
metas: impl Iterator<Item = Option<&'m Meta>>,
directives: &[ListDirective],
) -> Vec<bool> {
let mut breaks: Vec<bool> =
metas.map(|m| !m.leading.is_empty() || !m.attrs.is_empty()).collect();
metas.map(|m| m.is_none_or(|m| !m.leading.is_empty() || !m.attrs.is_empty())).collect();
for d in directives {
if let Some(b) = breaks.get_mut(d.before) {
*b = true;
+16 -6
View File
@@ -67,7 +67,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &m.param_ports {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma))
.map(|p| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma)
})
})
.collect();
let items = self.list_entries(items, &m.param_directives);
let broken = !m.param_directives.is_empty();
@@ -94,15 +98,19 @@ impl<'a> Fmt<'a> {
.iter()
.zip(&aligns)
.map(|(p, a)| {
ListItem::from_meta(&p.meta, self.ansi_port(p, a.as_ref()))
.with_comma(p.comma)
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.ansi_port(p, a.as_ref()))
.with_comma(p.comma)
})
})
.collect()
}
PortList::NonAnsi(ports) => ports
.iter()
.map(|p| {
ListItem::from_meta(&p.meta, name_doc(&p.name)).with_comma(p.comma)
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, name_doc(&p.name)).with_comma(p.comma)
})
})
.collect(),
_ => Vec::new(),
@@ -223,13 +231,15 @@ impl<'a> Fmt<'a> {
/// The alignment plan for a module header's ANSI port list.
fn ansi_port_aligns(
&self,
ports: &[AnsiPort],
ports: &[ListElem<AnsiPort>],
directives: &[ListDirective],
depth: usize,
) -> Vec<Option<Align>> {
let rows: Vec<Option<Row>> = ports
.iter()
.map(|p| {
// An error element has no cells to align, so it has no row.
let p = p.ok()?;
Self::row_of(
&self.ansi_port_cells(p),
vec![p.name_span.start],
@@ -237,7 +247,7 @@ impl<'a> Fmt<'a> {
)
})
.collect();
let breaks = Self::list_breaks(ports.iter().map(|p| &p.meta), directives);
let breaks = Self::list_breaks(ports.iter().map(|p| p.ok().map(|p| &p.meta)), directives);
self.align_groups(&rows, &breaks, ANSI_PORT_COLS, depth)
}
+6 -4
View File
@@ -27,7 +27,7 @@ pub(super) struct TfHeader<'h> {
name: &'h str,
has_parens: bool,
before_args: &'h [Comment],
args: &'h [TfArg],
args: &'h [ListElem<TfArg>],
args_dangling: &'h [Comment],
}
@@ -119,9 +119,11 @@ impl<'a> Fmt<'a> {
}
}
pub(super) fn tf_args(&self, args: &[TfArg], dangling: &[Comment]) -> Doc {
let items: Vec<ListItem> =
args.iter().map(|a| ListItem::from_meta(&a.meta, self.tf_arg(a))).collect();
pub(super) fn tf_args(&self, args: &[ListElem<TfArg>], dangling: &[Comment]) -> Doc {
let items: Vec<ListItem> = args
.iter()
.map(|a| self.list_elem(a, |a| ListItem::from_meta(&a.meta, self.tf_arg(a))))
.collect();
self.delimited_dangling("(", items, dangling, ")", false)
}
+8 -8
View File
@@ -9,8 +9,8 @@
//! becoming "everything a rule might want to walk".
use vlog_parser::ast::{
DataType, Dim, EnumType, FunctionDecl, ItemKind, SourceFile, StmtKind, StructType, TaskDecl,
TfArg, TypeExtra, TypedefKind,
DataType, Dim, EnumType, FunctionDecl, ItemKind, ListElem, SourceFile, StmtKind, StructType,
TaskDecl, TfArg, TypeExtra, TypedefKind,
};
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
@@ -34,7 +34,7 @@ pub(crate) fn walk_data_types(file: &SourceFile, f: &mut dyn FnMut(&DataType)) {
walk_items(file, &mut |item| match &item.kind {
ItemKind::Module(module) => {
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
for port in ports {
for port in ports.iter().filter_map(ListElem::ok) {
visit(&port.ty);
}
}
@@ -77,7 +77,7 @@ fn walk_unpacked(file: &SourceFile, f: &mut dyn FnMut(Packing, &Dim)) {
walk_items(file, &mut |item| match &item.kind {
ItemKind::Module(module) => {
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
for port in ports {
for port in ports.iter().filter_map(ListElem::ok) {
unpacked(&port.unpacked);
}
}
@@ -105,8 +105,8 @@ fn declarator_dims(declarators: &[vlog_parser::ast::Declarator], unpacked: &mut
}
}
fn arg_dims(args: &[TfArg], unpacked: &mut dyn FnMut(&[Dim])) {
for arg in args {
fn arg_dims(args: &[ListElem<TfArg>], unpacked: &mut dyn FnMut(&[Dim])) {
for arg in args.iter().filter_map(ListElem::ok) {
unpacked(&arg.unpacked);
}
}
@@ -124,13 +124,13 @@ fn function_types(decl: &FunctionDecl, visit: &mut dyn FnMut(&DataType)) {
if let Some(ret) = &decl.ret {
visit(ret);
}
for arg in &decl.args {
for arg in decl.args.iter().filter_map(ListElem::ok) {
visit(&arg.ty);
}
}
fn task_types(decl: &TaskDecl, visit: &mut dyn FnMut(&DataType)) {
for arg in &decl.args {
for arg in decl.args.iter().filter_map(ListElem::ok) {
visit(&arg.ty);
}
}
+8 -4
View File
@@ -10,7 +10,7 @@
//! whole is reported as **unknowable** rather than as a short list, because a
//! short list is what turns a legal connection into an accusation.
use vlog_parser::ast::{ItemKind, Module, ParamPort, PortList, SourceFile};
use vlog_parser::ast::{ItemKind, ListElem, Module, ParamPort, PortList, SourceFile};
use crate::context::ModuleInterface;
use crate::visit::walk_items;
@@ -49,8 +49,12 @@ fn interface_of(module: &Module) -> Option<ModuleInterface> {
/// to it by name.
fn ports_of(module: &Module) -> Vec<String> {
match &module.ports {
PortList::Ansi(ports) => ports.iter().map(|port| port.name.clone()).collect(),
PortList::NonAnsi(ports) => ports.iter().map(|port| port.name.clone()).collect(),
PortList::Ansi(ports) => {
ports.iter().filter_map(ListElem::ok).map(|port| port.name.clone()).collect()
}
PortList::NonAnsi(ports) => {
ports.iter().filter_map(ListElem::ok).map(|port| port.name.clone()).collect()
}
PortList::None | PortList::Empty => Vec::new(),
}
}
@@ -67,7 +71,7 @@ fn ports_of(module: &Module) -> Vec<String> {
fn parameters_of(module: &Module) -> Vec<String> {
let mut out = Vec::new();
let mut overridable = true;
for port in module.param_ports.iter().flatten() {
for port in module.param_ports.iter().flatten().filter_map(ListElem::ok) {
overridable = is_parameter(port, overridable);
if overridable {
out.push(port.name.clone());
@@ -5,7 +5,7 @@ use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::{ItemKind, TfArg};
use vlog_parser::ast::{ItemKind, ListElem, TfArg};
/// See [`Rule::doc`].
pub struct ExplicitFunctionTaskParameterType;
@@ -63,10 +63,10 @@ impl Rule for ExplicitFunctionTaskParameterType {
/// writes a direction keyword opens a new declaration (and so a new type,
/// implicit until written), and a formal that writes neither inherits whatever
/// is in force.
fn untyped(kw: &'static str, args: &[TfArg]) -> Vec<Violation> {
fn untyped(kw: &'static str, args: &[ListElem<TfArg>]) -> Vec<Violation> {
let mut out = Vec::new();
let mut opened = false;
for arg in args {
for arg in args.iter().filter_map(ListElem::ok) {
let opens = !opened || arg.dir.is_some() || !arg.ty.is_implicit();
opened = true;
if !opens || !arg.ty.is_implicit() || arg.name.is_empty() {
@@ -5,6 +5,7 @@ use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_instantiations;
use vlog_parser::ast::ListElem;
/// See [`Rule::doc`].
pub struct ModuleParameter;
@@ -41,7 +42,8 @@ impl Rule for ModuleParameter {
let mut out = Vec::new();
walk_instantiations(ctx.file(), &mut |inst| {
let Some(params) = &inst.params else { return };
let positional = params.iter().filter(|conn| conn.name.is_empty()).count();
let positional =
params.iter().filter_map(ListElem::ok).filter(|conn| conn.name.is_empty()).count();
if positional < 2 {
return;
}
@@ -5,6 +5,7 @@ use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_instantiations;
use vlog_parser::ast::ListElem;
/// See [`Rule::doc`].
pub struct UnknownParameter;
@@ -62,7 +63,7 @@ impl Rule for UnknownParameter {
}
let Some(params) = &inst.params else { return };
let Some(interface) = ctx.module_interface(&inst.module) else { return };
for param in params {
for param in params.iter().filter_map(ListElem::ok) {
if param.name == "*" || param.name_span.is_empty() {
continue;
}
+2 -1
View File
@@ -6,6 +6,7 @@ use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_instantiations;
use vlog_parser::ast::Connections;
use vlog_parser::ast::ListElem;
/// See [`Rule::doc`].
pub struct UnknownPort;
@@ -65,7 +66,7 @@ impl Rule for UnknownPort {
let Some(interface) = ctx.module_interface(&inst.module) else { return };
for instance in &inst.instances {
let Connections::Named(conns) = &instance.conns else { continue };
for conn in conns {
for conn in conns.iter().filter_map(ListElem::ok) {
if conn.name == "*" || conn.name_span.is_empty() {
continue;
}
+16 -2
View File
@@ -18,7 +18,7 @@ use std::collections::{HashMap, HashSet};
use vlog_parser::ast::{
ClockingItemKind, Connections, Expr, ExprKind, ForStep, GenElse, Instantiation, Item, ItemKind,
SourceFile, Stmt, StmtKind,
ListElem, SourceFile, Stmt, StmtKind,
};
use vlog_parser::span::TextRange;
use vlog_parser::token::TokenKind;
@@ -483,11 +483,25 @@ impl Scanner {
match &instance.conns {
Connections::Ordered(conns) => {
for conn in conns {
self.unknown.push(conn.span);
// An error element is text a tolerant parse could not
// read; whatever signals it mentions are unknown, so
// its span joins the same opaque bucket.
match conn {
ListElem::Ok(conn) => self.unknown.push(conn.span),
ListElem::Error(raw) => self.unknown.push(raw.span),
}
}
}
Connections::Named(conns) => {
for conn in conns {
let conn = match conn {
ListElem::Ok(conn) => conn,
// Opaque, as above.
ListElem::Error(raw) => {
self.unknown.push(raw.span);
continue;
}
};
match (conn.name.as_str(), &conn.expr) {
// `.*` connects every same-named signal without
// writing any of their names down.
+5 -3
View File
@@ -5,8 +5,8 @@
//! text and no children, so they are visited and matched by nothing.
use vlog_parser::ast::{
Fragment, GenBlock, GenElse, Instantiation, Item, ItemKind, ParamPort, SourceFile, Stmt,
StmtKind,
Fragment, GenBlock, GenElse, Instantiation, Item, ItemKind, ListElem, ParamPort, SourceFile,
Stmt, StmtKind,
};
/// Calls `f` on every item in the file, nested items included.
@@ -151,7 +151,9 @@ pub(crate) fn walk_param_ports(file: &SourceFile, f: &mut dyn FnMut(&ParamPort))
ItemKind::Class(class) => &class.param_ports,
_ => return,
};
for port in ports.iter().flatten() {
// An error element is a parameter a tolerant parse could not read: it
// has no name and no type, so there is nothing for a rule to judge.
for port in ports.iter().flatten().filter_map(ListElem::ok) {
f(port);
}
});
+2 -2
View File
@@ -28,7 +28,7 @@ pub struct ClassDecl {
pub param_after_hash: Vec<Comment>,
/// `None` when the header wrote no `#( ... )`; an empty `Some` is a
/// written-but-empty `#()`.
pub param_ports: Option<Vec<ParamPort>>,
pub param_ports: Option<Vec<ListElem<ParamPort>>>,
/// Directives written between the parameter ports, in source order.
pub param_directives: Vec<ListDirective>,
/// Comments written after the last parameter port and before its `)`.
@@ -75,7 +75,7 @@ pub struct ClassExtends {
/// Comments written between the base-class name and the `#`.
pub param_comments: Vec<Comment>,
/// `None` when no `#( ... )` was written.
pub params: Option<Vec<Connection>>,
pub params: Option<Vec<ListElem<Connection>>>,
/// Directives written between the overrides, in source order.
pub param_directives: Vec<ListDirective>,
/// Code extent of the clause, from `extends` through its last token.
+2 -2
View File
@@ -19,7 +19,7 @@ pub struct CovergroupDecl {
/// The `(bit [3:0] a)` formal argument list. `None` when the source wrote
/// no parens at all — printing an empty `()` back would be a token-stream
/// change the safety net refuses.
pub args: Option<Vec<TfArg>>,
pub args: Option<Vec<ListElem<TfArg>>>,
/// The `coverage_event` of the header. IEEE 1800 §19.3 makes the two
/// spellings alternatives, so one field holds whichever was written.
pub event: Option<CoverageEvent>,
@@ -73,7 +73,7 @@ pub struct SampleFn {
pub before_args: Vec<Comment>,
/// True when the source wrote `( ... )` at all.
pub has_parens: bool,
pub args: Vec<TfArg>,
pub args: Vec<ListElem<TfArg>>,
}
/// One `coverage_spec_or_option` of a covergroup body.
+5 -5
View File
@@ -306,7 +306,7 @@ pub struct FunctionDecl {
pub has_parens: bool,
/// Comments written between the name and the `(` of the port list.
pub before_args: Vec<Comment>,
pub args: Vec<TfArg>,
pub args: Vec<ListElem<TfArg>>,
/// Comments written inside an argument list with no argument to carry
/// them (`function void f( /*c*/ );`).
pub args_dangling: Vec<Comment>,
@@ -349,7 +349,7 @@ pub struct TaskDecl {
pub has_parens: bool,
/// Comments written between the name and the `(` of the port list.
pub before_args: Vec<Comment>,
pub args: Vec<TfArg>,
pub args: Vec<ListElem<TfArg>>,
/// Comments written inside an empty argument list; see
/// [`FunctionDecl::args_dangling`].
pub args_dangling: Vec<Comment>,
@@ -381,7 +381,7 @@ pub struct LetDecl {
/// False for the port-less spelling `let x = expr;` — an empty `()` was
/// written when this is true and [`LetDecl::ports`] is empty.
pub has_parens: bool,
pub ports: Vec<TfArg>,
pub ports: Vec<ListElem<TfArg>>,
pub value: Expr,
}
@@ -423,7 +423,7 @@ pub struct TfArg {
/// a pair of parentheses that hold no argument to carry them (`f( /*c*/ )`).
#[derive(Debug, Default)]
pub struct TfPorts {
pub args: Vec<TfArg>,
pub args: Vec<ListElem<TfArg>>,
pub dangling: Vec<Comment>,
}
@@ -477,7 +477,7 @@ pub struct TfPrototype {
pub has_parens: bool,
/// Comments written between the name and the `(` of the port list.
pub before_args: Vec<Comment>,
pub args: Vec<TfArg>,
pub args: Vec<ListElem<TfArg>>,
/// Comments written inside an argument list with no argument to carry
/// them (`task drive( /*c*/ )`).
pub args_dangling: Vec<Comment>,
+17
View File
@@ -15,6 +15,14 @@ pub struct Expr {
pub span: TextRange,
}
impl Expr {
/// True for the leaf a tolerant parse leaves where a statement header's
/// condition did not parse; see [`ExprKind::Error`].
pub fn is_error(&self) -> bool {
matches!(self.kind, ExprKind::Error(_))
}
}
#[derive(Debug, Clone)]
pub enum ExprKind {
Ident(String),
@@ -235,6 +243,15 @@ pub enum ExprKind {
/// the whole *item* became [`ItemKind::Verbatim`]. The region itself
/// records nothing and is re-emitted exactly as written.
Verbatim(RawText),
/// Text a **tolerant** parse could not read as an expression, kept
/// verbatim: the `i <` of a half-typed `for (int i = 0; i <` header.
///
/// Built only inside a statement header's brackets, and only by
/// [`crate::parse_tolerant`] — the strict parser fails on the typo
/// instead, exactly as it does for [`ItemKind::Error`] — so the statement
/// keeps its shape and its body while the broken condition is one leaf.
/// See `docs/features/header-recovery/README.md`.
Error(RawText),
/// A type used in expression position (`parameter type T = logic [7:0]`).
Type(DataType),
/// `(min : typ : max)` delay expression.
+54
View File
@@ -169,6 +169,60 @@ pub struct RawText {
pub span: TextRange,
}
/// One element of a header list: the element as written, or — in a tolerant
/// parse only — the text of one that did not parse.
///
/// The five header lists (a module's ports and parameter ports, a
/// subroutine's formals, an instance's named and ordered connections) share
/// this one wrapper rather than each growing a two-variant enum of its own:
/// the shape is the same in all of them, and one type means one place says
/// what an error element is. [`crate::parse`] never builds an
/// [`ListElem::Error`] — the strict parser fails on the typo instead — so a
/// consumer of a strictly parsed tree sees only [`ListElem::Ok`]. A consumer
/// of [`crate::parse_tolerant`]'s tree must decide what to do with the other
/// variant, which is the point of making it a variant; see
/// `docs/features/header-recovery/README.md`.
#[derive(Debug)]
pub enum ListElem<T> {
/// An element that parsed.
Ok(T),
/// Text a tolerant parse could not read as an element, kept verbatim.
Error(RawText),
}
impl<T> ListElem<T> {
/// The element, or `None` for an error element — the filter a consumer
/// that only wants the well-formed elements reads the list through.
pub fn ok(&self) -> Option<&T> {
match self {
ListElem::Ok(v) => Some(v),
ListElem::Error(_) => None,
}
}
/// The element as a mutable reference, or `None` for an error element:
/// what the parser's list loops hang a separator's comments on.
pub fn ok_mut(&mut self) -> Option<&mut T> {
match self {
ListElem::Ok(v) => Some(v),
ListElem::Error(_) => None,
}
}
/// The skipped text of an error element, or `None` for one that parsed.
pub fn error(&self) -> Option<&RawText> {
match self {
ListElem::Ok(_) => None,
ListElem::Error(raw) => Some(raw),
}
}
/// True for an element a tolerant parse recovered from.
pub fn is_error(&self) -> bool {
matches!(self, ListElem::Error(_))
}
}
/// A compiler directive written *between* the elements of a port,
/// parameter-port, enum-member, parameter-override or instance-connection
/// list (`` `ifdef``/`` `else``/`` `elsif``/`` `endif``, `` `define``,
+6 -6
View File
@@ -31,7 +31,7 @@ pub struct Module {
pub param_after_hash: Vec<Comment>,
/// `None` when the header wrote no `#( ... )` at all; an empty `Some` is a
/// written-but-empty `#()`, which must be printed back.
pub param_ports: Option<Vec<ParamPort>>,
pub param_ports: Option<Vec<ListElem<ParamPort>>>,
/// Directives written between the parameter ports, in source order.
pub param_directives: Vec<ListDirective>,
/// Comments written after the last parameter port and before the `)`.
@@ -86,9 +86,9 @@ pub enum PortList {
/// Empty parens: `module m();`
Empty,
/// ANSI-style declarations in the header.
Ansi(Vec<AnsiPort>),
Ansi(Vec<ListElem<AnsiPort>>),
/// Non-ANSI: just names in the header, declared in the body.
NonAnsi(Vec<NonAnsiPort>),
NonAnsi(Vec<ListElem<NonAnsiPort>>),
}
/// A name-only port in a non-ANSI header (`module m (a, b);`). It has no
@@ -208,7 +208,7 @@ pub struct Instantiation {
/// The parameter override list, `None` when the source wrote no `#(...)`
/// at all. An empty `Some` is a written-but-empty `#()`, which must be
/// printed back: dropping it would lose two tokens.
pub params: Option<Vec<Connection>>,
pub params: Option<Vec<ListElem<Connection>>>,
/// Directives written between the parameter overrides, in source order.
/// They live here rather than inside `params` because a `#( ... )` whose
/// whole body is one `` `include`` has no override to hang them on.
@@ -240,8 +240,8 @@ pub struct Instance {
#[derive(Debug)]
pub enum Connections {
Ordered(Vec<OrderedConn>),
Named(Vec<Connection>),
Ordered(Vec<ListElem<OrderedConn>>),
Named(Vec<ListElem<Connection>>),
}
#[derive(Debug)]
+9 -6
View File
@@ -97,34 +97,37 @@ 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 {
list.push(self.parse_connection()?);
if let Some(last) = list.last_mut() {
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, ",");
}
let comma = self.eat_sym(",");
if let Some(last) = list.last_mut() {
if let Some(ListElem::Ok(last)) = list.last_mut() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
let dirs = self.take_list_directives(&mut param_directives, list.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
if self.list_ends(at, comma, dirs.any, recovered) {
break;
}
}
}
let n = list.len();
self.take_last_entry_before_close(
list.last_mut().map(|c| &mut c.meta),
list.last_mut().and_then(|c| c.ok_mut()).map(|c| &mut c.meta),
&mut param_directives,
n,
);
self.expect_sym(")")?;
self.close_list(mark)?;
params = Some(list);
}
Ok(ClassExtends {
+59 -31
View File
@@ -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,12 +269,14 @@ impl<'a> Parser<'a> {
self.take_list_directives(&mut param_directives, 0);
if !self.cur().is_sym(")") {
loop {
list.push(self.parse_connection()?);
if let Some(last) = list.last_mut() {
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, ",");
}
let comma = self.eat_sym(",");
if let Some(last) = list.last_mut() {
if let Some(ListElem::Ok(last)) = list.last_mut() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
@@ -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 (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
if self.list_ends(at, comma, dirs.any, recovered) {
break;
}
}
@@ -293,11 +296,11 @@ impl<'a> Parser<'a> {
// Comments before the `)` of the override list belong inside it.
let n = list.len();
self.take_last_entry_before_close(
list.last_mut().map(|c| &mut c.meta),
list.last_mut().and_then(|c| c.ok_mut()).map(|c| &mut c.meta),
&mut param_directives,
n,
);
self.expect_sym(")")?;
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.expect_sym(")")?;
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,58 +386,77 @@ impl<'a> Parser<'a> {
if self.at_named_connection() {
let mut conns = Vec::new();
loop {
conns.push(self.parse_connection()?);
if let Some(last) = conns.last_mut() {
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, ",");
}
let comma = self.eat_sym(",");
if let Some(last) = conns.last_mut() {
if let Some(ListElem::Ok(last)) = conns.last_mut() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
let dirs = self.take_list_directives(directives, conns.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
if self.list_ends(at, comma, dirs.any, recovered) {
break;
}
}
// Comments before the closing `)` belong to the last entry: after
// it they would sit outside the connection list entirely.
let n = conns.len();
self.take_last_entry_before_close(conns.last_mut().map(|c| &mut c.meta), directives, n);
let last = conns.last_mut().and_then(|c| c.ok_mut()).map(|c| &mut c.meta);
self.take_last_entry_before_close(last, directives, n);
Ok(Connections::Named(conns))
} else {
let mut conns = Vec::new();
loop {
let start = self.here();
let meta = self.take_meta();
let expr = if self.cur().is_sym(",") || self.cur().is_sym(")") {
None
} else {
Some(self.parse_expr()?)
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(","),
};
// An omitted connection (`u (a, , c)`) consumed no token, so
// this is the empty span where it would have started.
let span = self.span_from(start);
let mut meta = meta;
self.take_before_sep(&mut meta, ",");
let comma = self.eat_sym(",");
if comma {
meta.trailing = self.take_trailing();
}
conns.push(OrderedConn { meta, expr, comma, span });
let dirs = self.take_list_directives(directives, conns.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
if self.list_ends(at, comma, dirs.any, recovered) {
break;
}
}
let n = conns.len();
self.take_last_entry_before_close(conns.last_mut().map(|c| &mut c.meta), directives, n);
let last = conns.last_mut().and_then(|c| c.ok_mut()).map(|c| &mut c.meta);
self.take_last_entry_before_close(last, directives, n);
Ok(Connections::Ordered(conns))
}
}
/// One positional connection (`u (a, , c)`), its separator included: an
/// omitted one writes no token at all, so the `,` is the only thing that
/// says it was there.
fn parse_ordered_connection(&mut self) -> PResult<OrderedConn> {
let start = self.here();
let mut meta = self.take_meta();
let expr = if self.cur().is_sym(",") || self.cur().is_sym(")") {
None
} else {
Some(self.parse_expr()?)
};
// An omitted connection consumed no token, so this is the empty span
// where it would have started.
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let comma = self.eat_sym(",");
if comma {
meta.trailing = self.take_trailing();
}
Ok(OrderedConn { meta, expr, comma, span })
}
/// True when the connection list starts with a named connection. The
/// leading `(* ... *)` attributes of the first entry are looked past:
/// they belong to the connection, not to the list.
+105 -74
View File
@@ -86,78 +86,14 @@ impl<'a> Parser<'a> {
}
"if" => self.parse_if_stmt(None),
"case" | "casex" | "casez" => self.parse_case_stmt(None),
"for" => {
self.bump();
let mut comments = ForComments { after_kw: self.take_gap(), ..Default::default() };
self.expect_sym("(")?;
comments.after_open = self.take_gap();
let mut init = Vec::new();
if !self.cur().is_sym(";") {
loop {
// Each init may introduce its own variable, and its
// type may be a keyword or a typedef'd name:
// `for (int i = 0, StateEnumT t = t.first(); ...)`
// (prim_sparse_fsm_flop.sv:48). An identifier only
// counts as a type when another identifier follows it
// — `for (i = 0; ...)` assigns to an existing `i`.
let ty = {
let t = self.cur();
let kw_type = t.kind == TokenKind::Keyword
&& TYPE_KEYWORDS.contains(&t.text.as_str());
if kw_type || (t.kind == TokenKind::Ident && self.at_typed_declarator())
{
Some(self.parse_opt_data_type()?)
} else {
None
}
};
let before_name = self.take_gap();
let lhs = self.parse_unary()?;
let mut op_comments =
BinaryComments { before: self.gap_before("="), after: Vec::new() };
self.expect_sym("=")?;
op_comments.after = self.take_gap();
let rhs = self.parse_expr()?;
init.push(ForInit {
ty,
before_name,
assign: SimpleAssign {
lhs,
op: "=".to_string(),
op_comments: Box::new(op_comments),
rhs,
},
});
if !self.eat_sym(",") {
break;
}
}
}
comments.before_first_semi = self.gap_before(";");
self.expect_sym(";")?;
comments.after_first_semi = self.take_gap();
let cond = if self.cur().is_sym(";") { None } else { Some(self.parse_expr()?) };
comments.before_second_semi = self.gap_before(";");
self.expect_sym(";")?;
comments.after_second_semi = self.take_gap();
let mut step = Vec::new();
if !self.cur().is_sym(")") {
step.push(self.parse_for_step()?);
while self.eat_sym(",") {
step.push(self.parse_for_step()?);
}
}
comments.before_close = self.gap_before(")");
self.expect_sym(")")?;
let body = Box::new(self.parse_stmt()?);
Ok(StmtKind::For { init, cond, step, comments: Box::new(comments), body })
}
"for" => self.parse_for_stmt(),
"while" => {
self.bump();
self.expect_sym("(")?;
let cond = self.parse_expr()?;
self.expect_sym(")")?;
Ok(StmtKind::While { cond, body: Box::new(self.parse_stmt()?) })
let cond = self.cond_or_recover()?;
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();
@@ -167,18 +103,19 @@ impl<'a> Parser<'a> {
HeaderComments { after_kw: self.take_before_open("("), ..Default::default() };
self.expect_sym("(")?;
comments.after_open = self.take_gap();
let cond = self.parse_expr()?;
let cond = self.cond_or_recover()?;
comments.before_close = self.gap_before(")");
self.expect_sym(")")?;
self.expect_after_recovery(")", cond.is_error())?;
self.expect_stmt_semi()?;
Ok(StmtKind::DoWhile { body, cond, comments: Box::new(comments) })
}
"repeat" => {
self.bump();
self.expect_sym("(")?;
let count = self.parse_expr()?;
self.expect_sym(")")?;
Ok(StmtKind::Repeat { count, body: Box::new(self.parse_stmt()?) })
let count = self.cond_or_recover()?;
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();
@@ -334,4 +271,98 @@ impl<'a> Parser<'a> {
_ => self.error(format!("unsupported statement starting with keyword `{kw}`")),
}
}
/// `for ( init ; cond ; step ) statement` (IEEE 1800 §12.7.1).
///
/// The three sections live inside one bracket, so in tolerant mode they
/// recover as one: whatever failed is reported once, the rest of the
/// header becomes the loop's [`ExprKind::Error`] condition, and the body
/// is parsed as usual. The init entries read before the failure are kept
/// — they are what declares the loop variable the body uses.
fn parse_for_stmt(&mut self) -> PResult<StmtKind> {
self.bump();
let mut comments = ForComments { after_kw: self.take_gap(), ..Default::default() };
self.expect_sym("(")?;
comments.after_open = self.take_gap();
let mut init = Vec::new();
let mut step = Vec::new();
let start_pos = self.pos;
let start = self.here();
let cond = match self.parse_for_header(&mut comments, &mut init, &mut step) {
Ok(cond) => cond,
Err(e) if self.tolerant => Some(self.error_expr(start_pos, start, e)),
Err(e) => return Err(e),
};
let recovered = cond.as_ref().is_some_and(Expr::is_error);
if !recovered {
comments.before_close = self.gap_before(")");
}
self.expect_after_recovery(")", recovered)?;
let body = Box::new(self.body_after_recovery(recovered)?);
Ok(StmtKind::For { init, cond, step, comments: Box::new(comments), body })
}
/// The three sections between a `for` header's brackets, filling `init`
/// and `step` as it goes so a failure keeps what was read before it.
fn parse_for_header(
&mut self,
comments: &mut ForComments,
init: &mut Vec<ForInit>,
step: &mut Vec<ForStep>,
) -> PResult<Option<Expr>> {
if !self.cur().is_sym(";") {
loop {
// Each init may introduce its own variable, and its type may
// be a keyword or a typedef'd name:
// `for (int i = 0, StateEnumT t = t.first(); ...)`
// (prim_sparse_fsm_flop.sv:48). An identifier only counts as a
// type when another identifier follows it — `for (i = 0; ...)`
// assigns to an existing `i`.
let ty = {
let t = self.cur();
let kw_type =
t.kind == TokenKind::Keyword && TYPE_KEYWORDS.contains(&t.text.as_str());
if kw_type || (t.kind == TokenKind::Ident && self.at_typed_declarator()) {
Some(self.parse_opt_data_type()?)
} else {
None
}
};
let before_name = self.take_gap();
let lhs = self.parse_unary()?;
let mut op_comments =
BinaryComments { before: self.gap_before("="), after: Vec::new() };
self.expect_sym("=")?;
op_comments.after = self.take_gap();
let rhs = self.parse_expr()?;
init.push(ForInit {
ty,
before_name,
assign: SimpleAssign {
lhs,
op: "=".to_string(),
op_comments: Box::new(op_comments),
rhs,
},
});
if !self.eat_sym(",") {
break;
}
}
}
comments.before_first_semi = self.gap_before(";");
self.expect_sym(";")?;
comments.after_first_semi = self.take_gap();
let cond = if self.cur().is_sym(";") { None } else { Some(self.parse_expr()?) };
comments.before_second_semi = self.gap_before(";");
self.expect_sym(";")?;
comments.after_second_semi = self.take_gap();
if !self.cur().is_sym(")") {
step.push(self.parse_for_step()?);
while self.eat_sym(",") {
step.push(self.parse_for_step()?);
}
}
Ok(cond)
}
}
+3 -1
View File
@@ -26,7 +26,8 @@
//! | file | holds |
//! |---|---|
//! | `cursor` | the token cursor, spans, `expect`/`eat`, the comment plumbing |
//! | `recover` | tolerant-mode error recovery |
//! | `recover` | tolerant-mode error recovery in item and statement lists |
//! | `recover_list` | tolerant-mode error recovery inside a header's lists and brackets |
//! | `item` | the file and item loops, the keyword → item dispatch, packages, imports, DPI, generate |
//! | `module` | module/interface/program headers, ports, modports, clocking blocks |
//! | `decl` | data types, declarators, parameters, `typedef`/`enum`/`struct` |
@@ -59,6 +60,7 @@ mod keyword_stmt;
mod module;
mod primary;
mod recover;
mod recover_list;
mod split;
mod stmt;
mod sva;
+52 -23
View File
@@ -9,7 +9,7 @@ use super::*;
#[derive(Default)]
pub(super) struct ParamPortList {
/// `None` when no `#( ... )` was written at all.
pub(super) ports: Option<Vec<ParamPort>>,
pub(super) ports: Option<Vec<ListElem<ParamPort>>>,
pub(super) directives: Vec<ListDirective>,
pub(super) dangling: Vec<Comment>,
/// Comments written between the `#` and the `(`.
@@ -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,7 +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(";");
self.expect_sym(";")?;
// 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()?);
@@ -321,16 +325,19 @@ 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 {
list.push(self.parse_param_port()?);
if let Some(last) = list.last_mut() {
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, ",");
}
let comma = self.eat_sym(",");
if let Some(last) = list.last_mut() {
if let Some(ListElem::Ok(last)) = list.last_mut() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
@@ -341,13 +348,15 @@ impl<'a> Parser<'a> {
// With one, only the closing bracket says so: an `` `ifdef``
// arm may end without a comma and another arm may still follow
// (`` `else``), or the arm may have been the tail of the list.
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
// In tolerant mode the closing bracket decides on its own; see
// [`Parser::list_ends`].
if self.list_ends(at, comma, dirs.any, recovered) {
break;
}
}
}
out.dangling = self.take_dangling();
self.expect_sym(")")?;
self.close_list(mark)?;
out.ports = Some(list);
Ok(out)
}
@@ -434,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.
@@ -467,32 +477,34 @@ impl<'a> Parser<'a> {
if ansi {
let mut ports = Vec::new();
loop {
ports.push(self.parse_ansi_port()?);
if let Some(last) = ports.last_mut() {
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, ",");
}
let comma = self.eat_sym(",");
if let Some(last) = ports.last_mut() {
if let Some(ListElem::Ok(last)) = ports.last_mut() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
let dirs = self.take_list_directives(&mut directives, ports.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
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.expect_sym(")")?;
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
// in the *header's* gap, and printing it back inside the parens
// moves it across the `)`.
if !self.cur().is_sym(";") {
if let Some(last) = ports.last_mut() {
if let Some(ListElem::Ok(last)) = ports.last_mut() {
if last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
@@ -502,25 +514,42 @@ impl<'a> Parser<'a> {
} else {
let mut ports = Vec::new();
loop {
let start = self.here();
let mut meta = self.take_meta();
let name = self.expect_ident()?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let comma = self.eat_sym(",");
meta.trailing = self.take_trailing();
ports.push(NonAnsiPort { meta, name, comma, span });
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,
// 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 (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
if self.list_ends(at, comma, dirs.any, recovered) {
break;
}
}
let dangling = self.take_dangling();
self.expect_sym(")")?;
self.close_list(mark)?;
Ok((PortList::NonAnsi(ports), dangling, directives))
}
}
/// One name of a non-ANSI header's port list (`module m (a, b);`),
/// its separator included: the port *is* its name, so there is nothing
/// else to read and the `,` is what says whether another follows.
fn parse_non_ansi_port(&mut self) -> PResult<NonAnsiPort> {
let start = self.here();
let mut meta = self.take_meta();
let name = self.expect_ident()?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let comma = self.eat_sym(",");
meta.trailing = self.take_trailing();
Ok(NonAnsiPort { meta, name, comma, span })
}
fn parse_ansi_port(&mut self) -> PResult<AnsiPort> {
let start = self.here();
let mut meta = self.take_meta();
+1 -1
View File
@@ -114,7 +114,7 @@ impl<'a> Parser<'a> {
/// File `err` as a diagnostic. Called while the cursor still sits on the
/// token the error was raised at, which is where its span comes from.
fn push_diag(&mut self, err: ParseError) {
pub(super) fn push_diag(&mut self, err: ParseError) {
let span = self.cur().span;
self.diagnostics.push(ParseDiagnostic {
message: err.message,
@@ -0,0 +1,322 @@
//! Error recovery *inside* a header — its bracketed lists and the parentheses
//! of a statement header — reached only in tolerant mode.
//!
//! `recover.rs` recovers in item and statement **lists**, which means a typo
//! anywhere inside a header escapes to the nearest enclosing one and takes the
//! whole module, function or statement with it. This file is the second, much
//! smaller answer: a list element that does not parse becomes an
//! [`ListElem::Error`], a statement header's condition that does not parse
//! becomes an [`ExprKind::Error`], and the construct around it keeps its name,
//! the elements that were typed and its body.
//!
//! Two rules make the skipping predictable, and both are list-local:
//!
//! * the bracket counter is **seeded from the list's own open bracket** —
//! already consumed by the caller — so the `;`s inside a `for (…; …; …)`
//! header are invisible and no skip can run past the bracket that closes
//! the list it is in;
//! * a **line change** stops a skip. It is the one line-based rule in the
//! parser, and it is what makes `module m (input logic a, inp⏎ output b);`
//! cost one port instead of the rest of the list.
//!
//! See `docs/features/header-recovery/README.md`.
use super::directive::{closes_conditional, continues_conditional, opens_conditional};
use super::*;
impl<'a> Parser<'a> {
/// True where a bracketed header list may end: on its own closing
/// bracket, on a `;` (the header was abandoned), at end of file, or on a
/// keyword an enclosing construct owns.
///
/// Read only in tolerant mode, and only with the list's brackets balanced,
/// so a `)` here is the list's own.
pub(super) fn at_list_end(&self) -> bool {
let t = self.cur();
self.at_eof() || t.is_sym(")") || t.is_sym(";") || self.at_sync_stop()
}
/// 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,
/// 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(")"));
}
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
/// failure into an error element holding the text skipped to the next
/// element boundary. Strict mode propagates the error unchanged.
pub(super) fn element_or_recover<T>(
&mut self,
parse: impl FnOnce(&mut Self) -> PResult<T>,
) -> PResult<ListElem<T>> {
let start_pos = self.pos;
let start = self.here();
match parse(self) {
Ok(value) => Ok(ListElem::Ok(value)),
Err(e) if self.tolerant && !self.at_conditional_directive() => {
Ok(ListElem::Error(self.recover_element(start_pos, start, e)))
}
Err(e) => Err(e),
}
}
/// True on a `` `ifdef `` / `` `ifndef `` / `` `else `` / `` `elsif `` /
/// `` `endif ``: a directive that opens, continues or closes a
/// conditional-compilation region.
///
/// 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 !self.recovered_since(mark) {
self.record("expected `)`");
}
return Ok(());
}
self.error("expected `)`")
}
/// Consume `sym` after a header that already recovered from an error: its
/// diagnostic is the one about this header, so a `;` or bracket missing
/// behind it is taken silently rather than reported twice or — worse —
/// failing the whole header and losing the body.
///
/// Without a recovery, and in strict mode, this *is*
/// [`Parser::expect_sym`].
pub(super) fn expect_after_recovery(&mut self, sym: &str, recovered: bool) -> PResult<()> {
if recovered && self.tolerant {
let _ = self.eat_sym(sym);
return Ok(());
}
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.
///
/// In tolerant mode a failure — or a condition the `)` does not follow —
/// becomes one [`ExprKind::Error`] covering the text skipped up to the
/// header's own `)`, so the statement keeps its body and the file keeps
/// one diagnostic. In strict mode this is [`Parser::parse_expr`], and the
/// caller's `expect_sym(")")` reports the missing bracket as before.
pub(super) fn cond_or_recover(&mut self) -> PResult<Expr> {
if !self.tolerant {
return self.parse_expr();
}
let start_pos = self.pos;
let start = self.here();
match self.parse_expr() {
Ok(e) if self.cur().is_sym(")") => Ok(e),
Ok(_) => {
let err = self.make_error("expected `)`");
Ok(self.error_expr(start_pos, start, err))
}
Err(e) => Ok(self.error_expr(start_pos, start, e)),
}
}
/// Record `err` and skip the rest of a statement header's brackets,
/// handing back the skipped source as one [`ExprKind::Error`] node.
///
/// Called by [`Parser::cond_or_recover`] and by the `for` header, which
/// recovers as a whole: its three sections are one bracket, so the error
/// node stands where its condition would.
pub(super) fn error_expr(&mut self, start_pos: usize, start: u32, err: ParseError) -> Expr {
self.push_diag(err);
if self.pos == start_pos && !self.cur().is_sym(")") {
// The header consumed nothing and the skip below may not either;
// take one token so the statement cannot be re-read forever.
self.bump();
}
self.skip_inside_brackets(true);
// As in `recover`: comments inside the skipped range are bytes of the
// raw text now, and the trivia copies would otherwise reattach
// themselves to whatever node comes next.
let _ = self.take_dangling();
let span = self.recovered_span(start_pos, start);
let col = self.tokens.get(start_pos).map(|t| t.col).unwrap_or(1);
Expr { kind: ExprKind::Error(RawText { text: self.slice(span), col, span }), span }
}
/// Record `err` and skip the remains of a broken list element, handing
/// back the skipped source as a verbatim leaf spanning from `start`.
fn recover_element(&mut self, start_pos: usize, start: u32, err: ParseError) -> RawText {
self.push_diag(err);
if self.pos == start_pos && !self.at_list_end() && !self.cur().is_sym(",") {
// Nothing was consumed and nothing below will be: the list loop
// neither ends here nor eats a separator, so take one token to
// guarantee it advances.
self.bump();
}
self.skip_inside_brackets(false);
let _ = self.take_dangling();
let span = self.recovered_span(start_pos, start);
let col = self.tokens.get(start_pos).map(|t| t.col).unwrap_or(1);
RawText { text: self.slice(span), col, span }
}
/// The extent a recovery covers: from `start` through the last token it
/// took, or the empty range at `start` when it took none (the sync point
/// was already under the cursor).
fn recovered_span(&self, start_pos: usize, start: u32) -> TextRange {
if self.pos == start_pos {
TextRange::empty(start)
} else {
self.span_from(start)
}
}
/// Skip forward inside a bracket the caller already consumed, stopping
/// *before* the token that ends the skip.
///
/// The counter starts at one — the list's own open bracket — so a closing
/// bracket at that level is the list's own and ends the skip, and nothing
/// nested inside can be mistaken for it. At that level the skip also stops
/// at a `,` (the next element's separator), at a keyword an enclosing
/// construct owns, and at the first token of a new line. A `;` ends it too
/// unless `through_semis` is set, which is what lets a `for` header — the
/// one bracket with `;`s of its own inside it — recover as a whole.
fn skip_inside_brackets(&mut self, through_semis: bool) {
let mut open = 1u32;
let mut line = self.prev_line();
while !self.at_eof() {
if open == 1 && self.at_element_sync(line, through_semis) {
return;
}
let t = self.cur();
let opens = t.is_sym("(") || t.is_sym("[") || t.is_sym("{");
let closes = t.is_sym(")") || t.is_sym("]") || t.is_sym("}");
line = t.line;
if opens {
open += 1;
} else if closes {
open -= 1;
}
self.bump();
}
}
/// True on a token that ends a skip at the list's own bracket level:
/// `line` is the line the last token belonging to the broken element was
/// written on, so a token on any other line starts something new.
fn at_element_sync(&self, line: u32, through_semis: bool) -> bool {
let t = self.cur();
if t.is_sym(";") {
return !through_semis;
}
t.line != line
|| t.is_sym(",")
|| t.is_sym(")")
|| t.is_sym("]")
|| t.is_sym("}")
|| self.at_sync_stop()
}
/// The line the last consumed token was written on — the line a skip
/// measures "a new line" against. At the very first token there is none,
/// so the cursor's own line stands in.
fn prev_line(&self) -> u32 {
match self.pos.checked_sub(1) {
Some(i) => self.tokens[i].line,
None => self.cur().line,
}
}
}
+6 -5
View File
@@ -161,9 +161,10 @@ impl<'a> Parser<'a> {
self.expect_kw("if")?;
let after_kw = self.take_before_open("(");
self.expect_sym("(")?;
let cond = self.parse_expr()?;
self.expect_sym(")")?;
let then = Box::new(self.parse_stmt()?);
let cond = self.cond_or_recover()?;
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
@@ -182,8 +183,8 @@ impl<'a> Parser<'a> {
let kw = self.bump().text;
let after_kw = self.take_before_open("(");
self.expect_sym("(")?;
let expr = self.parse_expr()?;
self.expect_sym(")")?;
let expr = self.cond_or_recover()?;
self.expect_after_recovery(")", expr.is_error())?;
// `case (x) inside` — the same statement with one extra token, whose
// labels may be `[lo:hi]` ranges (handled by `parse_expr_item`).
let inside = self.eat_kw("inside");
+1 -1
View File
@@ -14,7 +14,7 @@ fn class_header_parts_are_kept_apart() {
assert_eq!(c.param_ports.as_ref().expect("a parameter port list").len(), 1);
let ext = c.extends.as_ref().expect("an extends clause");
assert_eq!(ext.name, "pkg::base");
let params = ext.params.as_ref().expect("base parameter overrides");
let params = oks(ext.params.as_ref().expect("base parameter overrides"));
assert_eq!(params.len(), 2);
assert_eq!(params[0].name, "A");
// An ordered override has no name, only an expression.
@@ -45,6 +45,7 @@ fn a_comment_before_a_list_comma_lands_in_before_sep() {
let file = parse_ok("module m (input a /* pre */, /* post */ input b);\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let PortList::Ansi(ports) = &m.ports else { panic!("expected an ANSI port list") };
let ports = oks(ports);
assert_eq!(ports[0].meta.before_sep.len(), 1, "written before the comma");
assert_eq!(ports[0].meta.before_sep[0].text, "/* pre */");
let trailing = ports[0].meta.trailing.as_ref().expect("written after the comma");
@@ -59,6 +60,7 @@ fn a_comment_after_the_last_element_is_not_a_before_sep_comment() {
let file = parse_ok("module m (input a /* tail */);\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let PortList::Ansi(ports) = &m.ports else { panic!("expected an ANSI port list") };
let ports = oks(ports);
assert!(ports[0].meta.before_sep.is_empty(), "nothing separates it from the `)`");
assert_eq!(ports[0].meta.trailing.as_ref().expect("a trailing comment").text, "/* tail */");
}
@@ -99,7 +101,7 @@ fn comments_before_a_headers_brackets_land_on_the_module() {
assert_eq!(m.param_comments[0].text, "// params");
assert_eq!(m.port_comments.len(), 1);
assert_eq!(m.port_comments[0].text, "// ports");
let params = m.param_ports.as_ref().expect("a parameter port list");
let params = oks(m.param_ports.as_ref().expect("a parameter port list"));
assert!(params[0].meta.leading.is_empty(), "not the first parameter's leading comment");
}
@@ -71,7 +71,7 @@ fn a_covergroup_header_keeps_its_name_its_args_and_its_end_label() {
let g = covergroup_of(&f);
assert_eq!(g.name.text, "g");
assert_eq!(&f.span.as_range().start, &0);
let args = g.args.as_ref().expect("the formal list was parsed");
let args = oks(g.args.as_ref().expect("the formal list was parsed"));
assert_eq!(args.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["a", "n"]);
assert_eq!(g.end_label.as_ref().expect("the label was kept").text, "g");
assert!(!g.end_semi);
@@ -98,7 +98,7 @@ fn a_sample_function_header_keeps_the_word_and_its_arguments() {
};
assert_eq!(s.name.text, "sample");
assert!(s.has_parens);
assert_eq!(s.args.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["addr", "rw"]);
assert_eq!(oks(&s.args).iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["addr", "rw"]);
}
#[test]
+5 -5
View File
@@ -131,8 +131,8 @@ fn a_virtual_interface_type_stands_in_every_type_position() {
assert_eq!(ty.virt, Some(VirtualKw::Bare));
assert_eq!(ty.name, "push_pull_if");
let ItemKind::Function(fun) = &items[1].kind else { panic!("expected a function") };
assert_eq!(fun.args[0].ty.virt, Some(VirtualKw::Interface));
assert_eq!(fun.args[0].ty.name, "bus_if");
assert_eq!(oks(&fun.args)[0].ty.virt, Some(VirtualKw::Interface));
assert_eq!(oks(&fun.args)[0].ty.name, "bus_if");
}
#[test]
@@ -229,7 +229,7 @@ fn a_let_declaration_keeps_its_ports_and_its_value() {
assert_eq!(l.name, "max");
assert!(l.has_parens);
assert_eq!(l.ports.len(), 2);
assert_eq!(l.ports[1].name, "b");
assert_eq!(oks(&l.ports)[1].name, "b");
assert!(matches!(l.value.kind, ExprKind::Ternary { .. }));
}
@@ -266,8 +266,8 @@ fn a_virtual_interface_type_may_name_a_modport() {
let f = parse_ok("module m;\n task t(virtual spi_if.tb sif);\n endtask\nendmodule\n");
let m = module_of(&f);
let ItemKind::Task(t) = &m.items[0].kind else { panic!("expected a task") };
assert_eq!(t.args[0].ty.name, "spi_if.tb");
assert!(t.args[0].ty.virt.is_some(), "still a virtual interface type");
assert_eq!(oks(&t.args)[0].ty.name, "spi_if.tb");
assert!(oks(&t.args)[0].ty.virt.is_some(), "still a virtual interface type");
}
#[test]
@@ -183,6 +183,7 @@ fn a_directive_between_ports_records_its_place_and_the_commas_around_it() {
let file = parse_ok(src);
let m = module_of(&file);
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
let ports = oks(ports);
assert_eq!(ports.len(), 3);
assert_eq!(
ports.iter().map(|p| p.comma).collect::<Vec<_>>(),
@@ -206,7 +207,7 @@ fn a_comma_written_after_a_directive_belongs_to_the_directive() {
let src = "module m #(\n parameter int A = 1\n`ifdef S\n ,\n parameter int B = 2\n`endif\n) ();\nendmodule\n";
let file = parse_ok(src);
let m = module_of(&file);
let params = m.param_ports.as_ref().expect("a parameter port list");
let params = oks(m.param_ports.as_ref().expect("a parameter port list"));
assert_eq!(params.len(), 2);
assert!(!params[0].comma, "the first parameter wrote no comma of its own");
assert!(!params[1].comma);
@@ -225,6 +226,7 @@ fn a_list_with_no_directive_keeps_an_empty_directive_vector() {
assert!(m.param_directives.is_empty());
assert!(m.port_directives.is_empty());
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
let ports = oks(ports);
assert_eq!(ports.iter().map(|p| p.comma).collect::<Vec<_>>(), vec![true, false]);
}
@@ -236,6 +238,7 @@ fn both_arms_of_an_else_are_ordinary_elements_of_one_list() {
let file = parse_ok(src);
let m = module_of(&file);
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
let ports = oks(ports);
assert_eq!(ports.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), vec!["a", "b"]);
assert!(ports.iter().all(|p| !p.comma), "neither arm's port wrote a comma");
assert_eq!(m.port_directives.len(), 3);
@@ -288,6 +291,7 @@ fn a_directive_between_connections_records_its_place_and_the_commas() {
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
let conns = oks(conns);
assert_eq!(conns.len(), 3);
assert_eq!(
conns.iter().map(|c| c.comma).collect::<Vec<_>>(),
@@ -311,7 +315,7 @@ fn a_directive_between_parameter_overrides_lands_on_the_instantiation() {
let src = "module m;\n sub #(\n`ifndef S\n`ifdef T\n .P(0),\n`endif\n .Q(1)\n`endif\n ) u (.a(x));\nendmodule\n";
let file = parse_ok(src);
let inst = instantiation_of(&file);
let params = inst.params.as_ref().expect("an override list");
let params = oks(inst.params.as_ref().expect("an override list"));
assert_eq!(params.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), vec!["P", "Q"]);
assert_eq!(params.iter().map(|c| c.comma).collect::<Vec<_>>(), vec![true, false]);
let d = &inst.param_directives;
@@ -355,6 +359,7 @@ fn a_directive_before_the_first_connection_does_not_hide_the_dot() {
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
let conns = oks(conns);
assert_eq!(conns.len(), 2);
assert_eq!(inst.instances[0].conn_directives[0].before, 0);
}
@@ -367,6 +372,7 @@ fn a_directive_between_positional_connections_is_harvested_too() {
let Connections::Ordered(conns) = &inst.instances[0].conns else {
panic!("expected ordered connections")
};
let conns = oks(conns);
assert_eq!(conns.iter().map(|c| c.comma).collect::<Vec<_>>(), vec![true, true, false]);
assert_eq!(inst.instances[0].conn_directives.len(), 2);
}
@@ -383,6 +389,7 @@ fn an_instantiation_with_no_directive_keeps_empty_directive_vectors() {
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
let conns = oks(conns);
assert_eq!(conns.iter().map(|c| c.comma).collect::<Vec<_>>(), vec![true, false]);
}
@@ -405,6 +412,7 @@ fn a_directive_inside_a_connection_is_captured_or_refused_by_kind() {
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
let conns = oks(conns);
assert_eq!(conns[0].name, "a");
let Some(Expr { kind: ExprKind::Verbatim(raw), .. }) = &conns[0].expr else {
panic!("expected a verbatim value")
@@ -163,6 +163,7 @@ fn an_attribute_may_precede_a_named_port_connection() {
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
let conns = oks(conns);
assert_eq!(conns[0].meta.attrs.len(), 1);
assert_eq!(conns[0].meta.attrs[0].text, "(* async *)");
assert_eq!(conns[0].name, "a");
+6 -5
View File
@@ -73,7 +73,7 @@ fn a_dpi_import_is_a_function_prototype_with_a_linkage_prefix() {
assert_eq!(b.dpi.as_ref().and_then(|d| d.property.clone()), Some("context".to_string()));
assert_eq!(b.ret.as_ref().map(|t| t.name.clone()), Some("chandle".to_string()));
assert_eq!(b.args.len(), 1);
assert!(b.args[0].dir.is_none());
assert!(oks(&b.args)[0].dir.is_none());
let ItemKind::Task(c) = &items[2].kind else { panic!("expected a task") };
let dpi = c.dpi.as_ref().expect("DPI prefix");
@@ -101,11 +101,12 @@ fn a_dpi_import_formal_may_be_written_without_a_name() {
let f = parse_ok(src);
let ItemKind::Package { items, .. } = &f.items[0].kind else { panic!("expected package") };
let ItemKind::Function(g) = &items[0].kind else { panic!("expected a function") };
let names: Vec<&str> = g.args.iter().map(|a| a.name.as_str()).collect();
let args = oks(&g.args);
let names: Vec<&str> = args.iter().map(|a| a.name.as_str()).collect();
assert_eq!(names, ["", "", "named"]);
assert_eq!(g.args[1].dir.as_deref(), Some("input"));
assert_eq!(g.args[1].ty.name, "logic");
for a in &g.args[..2] {
assert_eq!(args[1].dir.as_deref(), Some("input"));
assert_eq!(args[1].ty.name, "logic");
for a in &args[..2] {
assert!(a.name_span.is_empty(), "an absent name spans nothing");
assert!(a.span.start <= a.name_span.start && a.name_span.end <= a.span.end);
}
@@ -28,6 +28,13 @@ fn parse_ok(src: &str) -> SourceFile {
}
}
/// The well-formed elements of a header list. Every source here is parsed by
/// the **strict** parser, which never builds a [`ListElem::Error`], so this is
/// the whole list — it is the shape, not the content, that the wrapper costs.
fn oks<T>(list: &[ListElem<T>]) -> Vec<&T> {
list.iter().filter_map(ListElem::ok).collect()
}
/// The keywords of a qualifier run, without the comments each one carries.
fn words(run: &[Qualifier]) -> Vec<&str> {
run.iter().map(|q| q.text.as_str()).collect()
@@ -57,7 +57,7 @@ fn ansi_ports(src: &str) -> Vec<(String, String, String)> {
let file = parse_ok(src);
let m = module_of(&file);
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports in {src:?}") };
ports
oks(ports)
.iter()
.map(|p| (p.dir.clone().unwrap_or_default(), p.ty.name.clone(), p.name.clone()))
.collect()
@@ -147,6 +147,7 @@ fn a_name_only_port_list_is_still_non_ansi() {
let file = parse_ok("module m (a, b, c);\ninput a;\ninput b;\noutput c;\nendmodule\n");
let m = module_of(&file);
let PortList::NonAnsi(ports) = &m.ports else { panic!("expected a non-ANSI port list") };
let ports = oks(ports);
assert_eq!(ports.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), vec!["a", "b", "c"]);
assert_eq!(ports.iter().map(|p| p.comma).collect::<Vec<_>>(), vec![true, true, false]);
@@ -283,9 +284,10 @@ fn a_modport_may_import_a_method_prototype() {
assert_eq!(drive.kind, TfKind::Task);
assert_eq!(drive.name, "drive");
assert!(drive.ret.is_none(), "a task has no return type");
assert_eq!(drive.args.len(), 1);
assert_eq!(drive.args[0].name, "x");
assert_eq!(drive.args[0].dir.as_deref(), Some("input"));
let drive_args = oks(&drive.args);
assert_eq!(drive_args.len(), 1);
assert_eq!(drive_args[0].name, "x");
assert_eq!(drive_args[0].dir.as_deref(), Some("input"));
assert!(ports[1].names.is_empty(), "a prototype group names nothing else");
let peek = ports[2].prototype.as_ref().expect("an exported prototype");
assert_eq!(ports[2].kw, "export");
@@ -320,7 +322,7 @@ fn every_gap_of_a_modport_prototype_has_an_owner() {
let p = port.prototype.as_ref().expect("a prototype");
assert_eq!(p.after_kw.len(), 1, "between `task` and the name");
assert_eq!(p.before_args.len(), 1, "between the name and the `(`");
assert_eq!(p.args[0].meta.leading.len(), 1, "inside the `(`");
assert_eq!(oks(&p.args)[0].meta.leading.len(), 1, "inside the `(`");
}
#[test]
+2 -2
View File
@@ -382,7 +382,7 @@ fn an_ifdef_inside_an_instantiations_parameter_value_captures_only_that_value()
};
assert_eq!(inst.module, "padring");
assert_eq!(inst.instances[0].name, "u_padring");
let params = inst.params.as_ref().expect("a parameter override list");
let params = oks(inst.params.as_ref().expect("a parameter override list"));
let Some(Expr { kind: ExprKind::Verbatim(raw), .. }) = &params[0].expr else {
panic!("expected a verbatim override value")
};
@@ -392,7 +392,7 @@ fn an_ifdef_inside_an_instantiations_parameter_value_captures_only_that_value()
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
assert_eq!(conns[0].name, "clk");
assert_eq!(oks(conns)[0].name, "clk");
assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived");
}
+1 -1
View File
@@ -285,7 +285,7 @@ fn property_and_sequence_declarations_are_real_nodes() {
let items = &module_of(&f).items;
let ItemKind::PropSeqDecl(p) = &items[0].kind else { panic!("expected a property") };
assert_eq!(p.name.text, "p");
assert_eq!(p.args.as_ref().expect("the formal list").args[0].name, "w");
assert_eq!(oks(&p.args.as_ref().expect("the formal list").args)[0].name, "w");
assert_eq!(p.locals.len(), 1, "the `realtime t;` local variable");
assert!(p.spec_semi, "the spec's own `;`");
assert_eq!(
+76 -66
View File
@@ -221,82 +221,92 @@ impl<'a> Parser<'a> {
self.bump();
return Ok(TfPorts { args, dangling });
}
let mark = self.diags_mark();
loop {
let start = self.here();
let mut meta = self.take_meta();
let mut after_const = Vec::new();
let dir = {
let t = self.cur();
if t.is_kw("const") && self.nth(1).is_kw("ref") {
// `const ref` (IEEE 1800 §13.5.2), corpus
// `ibex/vendor/lowrisc_ip/dv/sv/dv_utils/dv_utils_pkg.sv:104`.
// Two keywords, so the gap between them is a slot of its
// own — no other direction has an inside.
self.bump();
after_const = self.take_gap();
self.bump();
Some("const ref".to_string())
} else if t.is_kw("input")
|| t.is_kw("output")
|| t.is_kw("inout")
|| t.is_kw("ref")
{
Some(self.bump().text)
} else {
None
}
};
let after_dir = if dir.is_some() { self.take_gap() } else { Vec::new() };
let ty = self.parse_opt_data_type()?;
let before_name = self.take_gap();
// A DPI import's formal may name its type and stop (§35.5.5);
// every other formal must be named. The empty name is the crate's
// convention for "written without one" — see [`TfArg::name`].
let unnamed = allow_unnamed && (self.cur().is_sym(",") || self.cur().is_sym(")"));
let Name { text: name, span: name_span } = if unnamed {
Name { text: String::new(), span: TextRange::empty(self.span_from(start).end) }
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, ",");
more = self.eat_sym(",");
last.meta.trailing = self.take_trailing();
} else {
self.expect_name()?
};
let unpacked = self.parse_dims()?;
let mut eq_comments = BinaryComments::default();
let default = if self.cur().is_sym("=") {
eq_comments.before = self.take_gap();
self.bump();
eq_comments.after = self.take_gap();
Some(self.parse_expr()?)
} else {
None
};
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
meta.trailing = self.take_trailing();
args.push(TfArg {
meta,
dir,
after_const,
after_dir,
ty,
before_name,
name,
name_span,
unpacked,
eq_comments: Box::new(eq_comments),
default,
span,
});
if !more {
more = self.eat_sym(",");
}
if self.list_ends(at, more, false, recovered) {
break;
}
}
if let Some(last) = args.last_mut() {
if let Some(ListElem::Ok(last)) = args.last_mut() {
self.take_before_sep(&mut last.meta, ")");
}
self.expect_sym(")")?;
self.close_list(mark)?;
Ok(TfPorts { args, dangling: Vec::new() })
}
/// One formal of a subroutine's port list: everything up to the `,` or
/// `)` that follows it, which the list itself reads.
fn parse_tf_arg(&mut self, allow_unnamed: bool) -> PResult<TfArg> {
let start = self.here();
let meta = self.take_meta();
let mut after_const = Vec::new();
let dir = {
let t = self.cur();
if t.is_kw("const") && self.nth(1).is_kw("ref") {
// `const ref` (IEEE 1800 §13.5.2), corpus
// `ibex/vendor/lowrisc_ip/dv/sv/dv_utils/dv_utils_pkg.sv:104`.
// Two keywords, so the gap between them is a slot of its own —
// no other direction has an inside.
self.bump();
after_const = self.take_gap();
self.bump();
Some("const ref".to_string())
} else if t.is_kw("input") || t.is_kw("output") || t.is_kw("inout") || t.is_kw("ref") {
Some(self.bump().text)
} else {
None
}
};
let after_dir = if dir.is_some() { self.take_gap() } else { Vec::new() };
let ty = self.parse_opt_data_type()?;
let before_name = self.take_gap();
// A DPI import's formal may name its type and stop (§35.5.5); every
// other formal must be named. The empty name is the crate's convention
// for "written without one" — see [`TfArg::name`].
let unnamed = allow_unnamed && (self.cur().is_sym(",") || self.cur().is_sym(")"));
let Name { text: name, span: name_span } = if unnamed {
Name { text: String::new(), span: TextRange::empty(self.span_from(start).end) }
} else {
self.expect_name()?
};
let unpacked = self.parse_dims()?;
let mut eq_comments = BinaryComments::default();
let default = if self.cur().is_sym("=") {
eq_comments.before = self.take_gap();
self.bump();
eq_comments.after = self.take_gap();
Some(self.parse_expr()?)
} else {
None
};
let span = self.span_from(start);
Ok(TfArg {
meta,
dir,
after_const,
after_dir,
ty,
before_name,
name,
name_span,
unpacked,
eq_comments: Box::new(eq_comments),
default,
span,
})
}
fn parse_tf_body(&mut self, end_kw: &str) -> PResult<TfBody> {
let mut stmts = Vec::new();
while !self.at_body_end(end_kw) {
+259 -16
View File
@@ -139,10 +139,54 @@ fn error_nodes(file: &SourceFile) -> Vec<(vlog_parser::TextRange, String)> {
out
}
/// The error elements of one header list, as the same (span, text) pairs an
/// error item or statement contributes: an element a tolerant parse could not
/// read is an error node like any other, and every count in this file is of
/// *all* of them.
fn walk_list<T>(list: &[ListElem<T>], out: &mut Vec<(vlog_parser::TextRange, String)>) {
for raw in list.iter().filter_map(ListElem::error) {
out.push((raw.span, raw.text.clone()));
}
}
fn walk_ports(ports: &PortList, out: &mut Vec<(vlog_parser::TextRange, String)>) {
match ports {
PortList::Ansi(ports) => walk_list(ports, out),
PortList::NonAnsi(ports) => walk_list(ports, out),
PortList::None | PortList::Empty => {}
}
}
fn walk_conns(conns: &Connections, out: &mut Vec<(vlog_parser::TextRange, String)>) {
match conns {
Connections::Named(conns) => walk_list(conns, out),
Connections::Ordered(conns) => walk_list(conns, out),
}
}
/// The leaf a recovered statement header leaves where its condition was.
fn walk_expr(expr: &Expr, out: &mut Vec<(vlog_parser::TextRange, String)>) {
if let ExprKind::Error(r) = &expr.kind {
out.push((r.span, r.text.clone()));
}
}
fn walk_item(item: &Item, out: &mut Vec<(vlog_parser::TextRange, String)>) {
match &item.kind {
ItemKind::Error(r) => out.push((r.span, r.text.clone())),
ItemKind::Module(m) => m.items.iter().for_each(|i| walk_item(i, out)),
ItemKind::Module(m) => {
walk_list(m.param_ports.as_deref().unwrap_or(&[]), out);
walk_ports(&m.ports, out);
m.items.iter().for_each(|i| walk_item(i, out));
}
ItemKind::Instantiation(i) => {
walk_list(i.params.as_deref().unwrap_or(&[]), out);
i.instances.iter().for_each(|inst| walk_conns(&inst.conns, out));
}
ItemKind::Class(c) => {
walk_list(c.param_ports.as_deref().unwrap_or(&[]), out);
c.items.iter().for_each(|i| walk_item(i, out));
}
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
items.iter().for_each(|i| walk_item(i, out))
}
@@ -154,8 +198,14 @@ fn walk_item(item: &Item, out: &mut Vec<(vlog_parser::TextRange, String)>) {
ItemKind::Initial(s) | ItemKind::Final(s) | ItemKind::Always { stmt: s, .. } => {
walk_stmt(s, out)
}
ItemKind::Function(f) => f.stmts.iter().for_each(|s| walk_stmt(s, out)),
ItemKind::Task(t) => t.stmts.iter().for_each(|s| walk_stmt(s, out)),
ItemKind::Function(f) => {
walk_list(&f.args, out);
f.stmts.iter().for_each(|s| walk_stmt(s, out));
}
ItemKind::Task(t) => {
walk_list(&t.args, out);
t.stmts.iter().for_each(|s| walk_stmt(s, out));
}
_ => {}
}
}
@@ -175,17 +225,28 @@ fn walk_stmt(stmt: &Stmt, out: &mut Vec<(vlog_parser::TextRange, String)>) {
StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => {
stmts.iter().for_each(|s| walk_stmt(s, out))
}
StmtKind::If { then, els, .. } => {
StmtKind::If { cond, then, els, .. } => {
walk_expr(cond, out);
walk_stmt(then, out);
els.iter().for_each(|s| walk_stmt(s, out));
}
StmtKind::Case { items, .. } => items.iter().for_each(|i| walk_stmt(&i.stmt, out)),
StmtKind::For { body, .. }
| StmtKind::While { body, .. }
| StmtKind::DoWhile { body, .. }
| StmtKind::Repeat { body, .. }
| StmtKind::Forever { body }
| StmtKind::Foreach { body, .. } => walk_stmt(body, out),
StmtKind::Case { expr, items, .. } => {
walk_expr(expr, out);
items.iter().for_each(|i| walk_stmt(&i.stmt, out));
}
StmtKind::For { cond, body, .. } => {
cond.iter().for_each(|c| walk_expr(c, out));
walk_stmt(body, out);
}
StmtKind::While { cond, body } | StmtKind::DoWhile { cond, body, .. } => {
walk_expr(cond, out);
walk_stmt(body, out);
}
StmtKind::Repeat { count, body } => {
walk_expr(count, out);
walk_stmt(body, out);
}
StmtKind::Forever { body } | StmtKind::Foreach { body, .. } => walk_stmt(body, out),
StmtKind::Timing { stmt, .. } | StmtKind::Wait { stmt, .. } => {
stmt.iter().for_each(|s| walk_stmt(s, out))
}
@@ -429,18 +490,200 @@ 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", "* ) ]"] {
+96 -42
View File
@@ -468,6 +468,37 @@ fn check_import_paths(src: &str, paths: &[ImportPath], parent: TextRange) {
}
}
/// The well-formed elements of a header list, for the pins that read one by
/// index. Their sources all parse, and the strict parser never builds a
/// [`ListElem::Error`], so this is the whole list.
fn oks<T>(list: &[ListElem<T>]) -> Vec<&T> {
list.iter().filter_map(ListElem::ok).collect()
}
/// Walk a header list, checking the error elements a tolerant parse may have
/// left — they nest inside the header and slice back to their own text, like
/// every other raw leaf — and handing the well-formed ones to `check`.
///
/// Every list this runs over goes through here, so a new header list cannot
/// quietly skip the invariant for its error elements.
fn check_list<T>(
src: &str,
what: &str,
list: &[ListElem<T>],
parent: TextRange,
mut check: impl FnMut(&T),
) {
for elem in list {
match elem {
ListElem::Ok(v) => check(v),
ListElem::Error(raw) => {
assert_inside(src, what, raw.span, parent);
assert_eq!(slice(src, raw.span), raw.text, "{what} does not slice back");
}
}
}
}
fn assert_inside(src: &str, what: &str, inner: TextRange, outer: TextRange) {
assert!(
outer.start <= inner.start && inner.end <= outer.end,
@@ -496,25 +527,25 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
assert_inside(src, "list directive", d.raw.span, here);
}
if let Some(params) = &m.param_ports {
for p in params {
check_list(src, "parameter port", params, here, |p| {
assert_inside(src, "parameter port", p.span, here);
check_name(src, "parameter port name", &p.name, p.name_span, p.span);
check_opt_expr(src, p.default.as_ref(), p.span);
}
});
}
match &m.ports {
PortList::Ansi(ports) => {
for p in ports {
check_list(src, "port", ports, here, |p| {
assert_inside(src, "port", p.span, here);
check_name(src, "port name", &p.name, p.name_span, p.span);
}
});
}
PortList::NonAnsi(ports) => {
for p in ports {
check_list(src, "port", ports, here, |p| {
assert_inside(src, "port", p.span, here);
// A non-ANSI port *is* its name, so `span` is the range.
check_name(src, "port name", &p.name, p.span, here);
}
});
}
PortList::None | PortList::Empty => {}
}
@@ -612,10 +643,12 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
for d in &c.param_directives {
assert_inside(src, "list directive", d.raw.span, here);
}
for p in c.param_ports.iter().flatten() {
assert_inside(src, "class parameter port", p.span, here);
check_name(src, "class parameter port name", &p.name, p.name_span, p.span);
check_opt_expr(src, p.default.as_ref(), p.span);
if let Some(params) = &c.param_ports {
check_list(src, "class parameter port", params, here, |p| {
assert_inside(src, "class parameter port", p.span, here);
check_name(src, "class parameter port name", &p.name, p.name_span, p.span);
check_opt_expr(src, p.default.as_ref(), p.span);
});
}
if let Some(ext) = &c.extends {
assert_inside(src, "extends clause", ext.span, here);
@@ -630,10 +663,18 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
for d in &ext.param_directives {
assert_inside(src, "list directive", d.raw.span, ext.span);
}
for c in ext.params.iter().flatten() {
assert_inside(src, "base parameter override", c.span, ext.span);
check_name(src, "base parameter override name", &c.name, c.name_span, c.span);
check_opt_expr(src, c.expr.as_ref(), c.span);
if let Some(params) = &ext.params {
check_list(src, "base parameter override", params, ext.span, |c| {
assert_inside(src, "base parameter override", c.span, ext.span);
check_name(
src,
"base parameter override name",
&c.name,
c.name_span,
c.span,
);
check_opt_expr(src, c.expr.as_ref(), c.span);
});
}
}
for item in &c.items {
@@ -655,7 +696,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
proto.name_span,
p.span,
);
for a in &proto.args {
check_list(src, "modport prototype formal", &proto.args, p.span, |a| {
assert_inside(src, "modport prototype formal", a.span, p.span);
check_name(
src,
@@ -664,7 +705,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
a.name_span,
a.span,
);
}
});
}
}
}
@@ -693,9 +734,9 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
ItemKind::PropSeqDecl(d) => {
check_name(src, "property name", &d.name.text, d.name.span, here);
if let Some(args) = &d.args {
for a in &args.args {
check_list(src, "formal", &args.args, here, |a| {
check_name(src, "formal name", &a.name, a.name_span, here);
}
});
}
for local in &d.locals {
check_item(src, local, here);
@@ -721,10 +762,10 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
check_name(src, "function name", &f.name, f.name_span, here);
check_dpi_import(src, f.dpi.as_ref(), here);
check_opt_name(src, "endfunction label", f.end_label.as_ref(), f.end_label_span, here);
for a in &f.args {
check_list(src, "argument", &f.args, here, |a| {
assert_inside(src, "argument", a.span, here);
check_name(src, "argument name", &a.name, a.name_span, a.span);
}
});
for s in &f.stmts {
check_stmt(src, s, here);
}
@@ -733,20 +774,20 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
check_name(src, "task name", &t.name, t.name_span, here);
check_dpi_import(src, t.dpi.as_ref(), here);
check_opt_name(src, "endtask label", t.end_label.as_ref(), t.end_label_span, here);
for a in &t.args {
check_list(src, "argument", &t.args, here, |a| {
assert_inside(src, "argument", a.span, here);
check_name(src, "argument name", &a.name, a.name_span, a.span);
}
});
for s in &t.stmts {
check_stmt(src, s, here);
}
}
ItemKind::Let(l) => {
check_name(src, "let name", &l.name, l.name_span, here);
for a in &l.ports {
check_list(src, "let port", &l.ports, here, |a| {
assert_inside(src, "let port", a.span, here);
check_name(src, "let port name", &a.name, a.name_span, a.span);
}
});
check_expr(src, &l.value, here);
}
ItemKind::Defparam(pairs) => {
@@ -783,10 +824,12 @@ fn check_instantiation(src: &str, inst: &Instantiation, here: TextRange) {
for d in &inst.param_directives {
assert_inside(src, "list directive", d.raw.span, here);
}
for c in inst.params.iter().flatten() {
assert_inside(src, "parameter override", c.span, here);
check_name(src, "parameter override name", &c.name, c.name_span, c.span);
check_opt_expr(src, c.expr.as_ref(), c.span);
if let Some(params) = &inst.params {
check_list(src, "parameter override", params, here, |c| {
assert_inside(src, "parameter override", c.span, here);
check_name(src, "parameter override name", &c.name, c.name_span, c.span);
check_opt_expr(src, c.expr.as_ref(), c.span);
});
}
for i in &inst.instances {
assert_inside(src, "instance", i.span, here);
@@ -796,17 +839,17 @@ fn check_instantiation(src: &str, inst: &Instantiation, here: TextRange) {
}
match &i.conns {
Connections::Named(cs) => {
for c in cs {
check_list(src, "connection", cs, i.span, |c| {
assert_inside(src, "connection", c.span, i.span);
check_name(src, "connection name", &c.name, c.name_span, c.span);
check_opt_expr(src, c.expr.as_ref(), c.span);
}
});
}
Connections::Ordered(cs) => {
for c in cs {
check_list(src, "connection", cs, i.span, |c| {
assert_inside(src, "connection", c.span, i.span);
check_opt_expr(src, c.expr.as_ref(), c.span);
}
});
}
}
}
@@ -1200,6 +1243,12 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) {
assert_inside(src, "verbatim expression", raw.span, here);
assert_eq!(slice(src, raw.span), raw.text, "a verbatim expression does not slice back");
}
// The leaf a recovered statement header leaves behind, under the same
// rule: its own bytes, nesting where it was written.
ExprKind::Error(raw) => {
assert_inside(src, "error expression", raw.span, here);
assert_eq!(slice(src, raw.span), raw.text, "an error expression does not slice back");
}
}
}
@@ -1288,13 +1337,14 @@ fn every_name_span_slices_back_to_its_name() {
assert_eq!(slice(src, paths[1].pkg.span), "pkg_a");
assert_eq!(slice(src, paths[1].item.span), "color_e");
let params = m.param_ports.as_ref().expect("a parameter port list");
let params = oks(m.param_ports.as_ref().expect("a parameter port list"));
assert_eq!(slice(src, params[0].name_span), "W");
// The `parameter type T` arm is a separate construction site.
assert!(params[1].is_type);
assert_eq!(slice(src, params[1].name_span), "T");
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
let ports = oks(ports);
assert_eq!(slice(src, ports[0].name_span), "clk_i");
assert_eq!(slice(src, ports[1].name_span), "data_o");
@@ -1309,9 +1359,11 @@ fn every_name_span_slices_back_to_its_name() {
let ItemKind::Instantiation(inst) = &m.items[2].kind else { panic!("expected an instance") };
assert_eq!(slice(src, inst.module_span), "sub");
assert_eq!(slice(src, inst.params.as_ref().expect("a parameter override")[0].name_span), "PW");
let overrides = oks(inst.params.as_ref().expect("a parameter override"));
assert_eq!(slice(src, overrides[0].name_span), "PW");
assert_eq!(slice(src, inst.instances[0].name_span), "u_sub");
let Connections::Named(conns) = &inst.instances[0].conns else { panic!("named connections") };
let conns = oks(conns);
assert_eq!(slice(src, conns[0].name_span), "clk");
// `.*` has no name of its own; its span is the wildcard token.
assert_eq!(slice(src, conns[1].name_span), "*");
@@ -1344,13 +1396,13 @@ fn every_name_span_slices_back_to_its_name() {
let ItemKind::Function(f) = &m.items[6].kind else { panic!("expected a function") };
assert_eq!(slice(src, f.name_span), "fn_add");
assert_eq!(slice(src, f.end_label_span.expect("an endfunction label")), "fn_add");
assert_eq!(slice(src, f.args[0].name_span), "a_i");
assert_eq!(slice(src, f.args[1].name_span), "b_i");
assert_eq!(slice(src, oks(&f.args)[0].name_span), "a_i");
assert_eq!(slice(src, oks(&f.args)[1].name_span), "b_i");
let ItemKind::Task(t) = &m.items[7].kind else { panic!("expected a task") };
assert_eq!(slice(src, t.name_span), "tsk_go");
assert_eq!(slice(src, t.end_label_span.expect("an endtask label")), "tsk_go");
assert_eq!(slice(src, t.args[0].name_span), "r_o");
assert_eq!(slice(src, oks(&t.args)[0].name_span), "r_o");
}
#[test]
@@ -1432,17 +1484,19 @@ fn a_label_and_its_end_label_get_separate_spans() {
/// every expression inside the item, and every `foreach` loop variable.
fn check_covergroup(src: &str, c: &CovergroupDecl, here: TextRange) {
check_name(src, "covergroup name", &c.name.text, c.name.span, here);
for a in c.args.iter().flatten() {
assert_inside(src, "covergroup argument", a.span, here);
check_name(src, "covergroup argument name", &a.name, a.name_span, a.span);
if let Some(args) = &c.args {
check_list(src, "covergroup argument", args, here, |a| {
assert_inside(src, "covergroup argument", a.span, here);
check_name(src, "covergroup argument name", &a.name, a.name_span, a.span);
});
}
match &c.event {
Some(CoverageEvent::Sample(s)) => {
check_name(src, "sample method name", &s.name.text, s.name.span, here);
for a in &s.args {
check_list(src, "sample argument", &s.args, here, |a| {
assert_inside(src, "sample argument", a.span, here);
check_name(src, "sample argument name", &a.name, a.name_span, a.span);
}
});
}
// A clocking event's own spans are the statement `always @(...)`
// machinery's, checked where that is.
+7 -4
View File
@@ -19,7 +19,7 @@
use std::path::Path;
use vlog_parser::ast::{AnsiPort, ItemKind, Module, ParamPort, PortList};
use vlog_parser::ast::{AnsiPort, ItemKind, ListElem, Module, ParamPort, PortList};
use vlog_parser::parse_source_tolerant;
use vlog_parser::span::TextRange;
use vlog_semantic::{Semantics, WorkspaceIndex};
@@ -338,7 +338,8 @@ fn params(module: &Module, text: &str) -> Vec<PlanParam> {
let Some(declared) = &module.param_ports else { return Vec::new() };
let mut out = Vec::new();
let mut kw = String::new();
for param in declared {
// A parameter a tolerant parse could not read has no name to override.
for param in declared.iter().filter_map(ListElem::ok) {
if let Some(written) = &param.kw {
kw = written.clone();
}
@@ -388,6 +389,7 @@ fn ports(module: &Module, text: &str) -> Vec<PlanPort> {
PortList::Ansi(declared) => ansi_ports(declared, text),
PortList::NonAnsi(declared) => declared
.iter()
.filter_map(ListElem::ok)
.map(|port| {
let (dir, ty) = non_ansi_type(module, text, &port.name);
PlanPort { name: port.name.clone(), dir, ty, auto_connect: false }
@@ -404,10 +406,11 @@ fn ports(module: &Module, text: &str) -> Vec<PlanPort> {
/// expects to see spelled out. An element that writes *something* is reported
/// exactly as written, however partial: guessing what a bare `output q`
/// defaults to is the language's business, not a hint's.
fn ansi_ports(declared: &[AnsiPort], text: &str) -> Vec<PlanPort> {
fn ansi_ports(declared: &[ListElem<AnsiPort>], text: &str) -> Vec<PlanPort> {
let mut out: Vec<PlanPort> = Vec::new();
let (mut dir, mut ty) = (String::new(), String::new());
for port in declared {
// A port a tolerant parse could not read has no name to connect.
for port in declared.iter().filter_map(ListElem::ok) {
if port.name.is_empty() {
continue;
}
+12 -11
View File
@@ -5,7 +5,7 @@
use std::path::Path;
use vlog_parser::ast::{Connections, Instance, ItemKind, Module, PortList};
use vlog_parser::ast::{Connections, Instance, ItemKind, ListElem, Module, PortList};
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::{parse_source_tolerant, tokenize, LineIndex};
@@ -17,7 +17,7 @@ use super::find::{
collect_instantiations, declared_ports, find_module, name_visible, DeclaredPort, ModuleSite,
};
use super::list::{
after_same_line_comments, append_to_list, conn_list_open, header_semicolon, insert,
after_same_line_comments, append_to_list, conn_list_open, elem_spans, header_semicolon, insert,
line_indent, port_list_open,
};
use super::{shape, Plan};
@@ -65,7 +65,8 @@ pub(super) fn parse_port_decl(decl: &str) -> Result<NewPort, String> {
return Err(refusal);
}
let PortList::Ansi(ports) = &module.ports else { return Err(refusal) };
let [port] = ports.as_slice() else { return Err(refusal) };
// The probe parsed without a diagnostic, so its one element is a port.
let [ListElem::Ok(port)] = ports.as_slice() else { return Err(refusal) };
if port.comma {
return Err(refusal);
}
@@ -401,18 +402,18 @@ fn instantiation_edits(
for instantiation in instantiations.iter().filter(|i| i.module == site.name) {
for instance in &instantiation.instances {
match &instance.conns {
Connections::Named(conns) if conns.iter().any(|c| c.name == "*") => {
Connections::Named(conns)
if conns.iter().filter_map(ListElem::ok).any(|c| c.name == "*") =>
{
wildcards.push(instance)
}
Connections::Named(conns) => {
if conns.iter().any(|c| c.name == port.name) {
if conns.iter().filter_map(ListElem::ok).any(|c| c.name == port.name) {
continue;
}
named.push((
instance,
conns.iter().map(|c| c.span).collect(),
conn_list_open(text, instance, conns.first().map(|c| c.span)),
));
let spans = elem_spans(conns, |c| c.span);
let first = spans.first().copied();
named.push((instance, spans, conn_list_open(text, instance, first)));
}
// An empty list connects nothing, so a new port changes
// nothing there: it stays unconnected either way.
@@ -435,7 +436,7 @@ fn instantiation_edits(
site.name
));
}
ordered.push((instance, conns.iter().map(|c| c.span).collect()));
ordered.push((instance, elem_spans(conns, |c| c.span)));
}
}
}
+5 -1
View File
@@ -8,7 +8,7 @@
use std::path::Path;
use vlog_parser::ast::{
GenBlock, GenElse, Instantiation, Item, ItemKind, Module, PortList, SourceFile,
GenBlock, GenElse, Instantiation, Item, ItemKind, ListElem, Module, PortList, SourceFile,
};
use vlog_parser::parse_source_tolerant;
use vlog_parser::span::TextRange;
@@ -123,13 +123,17 @@ pub(super) struct DeclaredPort {
}
pub(super) fn declared_ports(module: &Module) -> Vec<DeclaredPort> {
// A port a tolerant parse could not read declares no name, so it is not a
// port anything can be propagated to or renamed.
match &module.ports {
PortList::Ansi(ports) => ports
.iter()
.filter_map(ListElem::ok)
.map(|port| DeclaredPort { name: port.name.clone(), span: port.span })
.collect(),
PortList::NonAnsi(ports) => ports
.iter()
.filter_map(ListElem::ok)
.map(|port| DeclaredPort { name: port.name.clone(), span: port.span })
.collect(),
PortList::Empty | PortList::None => Vec::new(),
+18 -1
View File
@@ -4,7 +4,7 @@
//! list past its `#(...)`, a header's `;`, an instance's connection list.
//! Text-level, and shared by all three planners.
use vlog_parser::ast::Instance;
use vlog_parser::ast::{Instance, ListElem};
use vlog_parser::span::TextRange;
use vlog_parser::token::{Token, TokenKind};
@@ -269,6 +269,23 @@ fn skip_group(tokens: &[Token], open: usize) -> Option<usize> {
None
}
/// The code extents of a header list's elements, in source order.
///
/// An error element — text a tolerant parse could not read — takes the space
/// it was written in like any other element, so its own span stands in: these
/// spans say where the list's text *is*, not what it means.
pub(super) fn elem_spans<T>(
list: &[ListElem<T>],
span_of: impl Fn(&T) -> TextRange,
) -> Vec<TextRange> {
list.iter()
.map(|e| match e {
ListElem::Ok(v) => span_of(v),
ListElem::Error(raw) => raw.span,
})
.collect()
}
/// The `(` opening an instance's connection list.
pub(super) fn conn_list_open(
text: &str,
+7 -1
View File
@@ -342,7 +342,13 @@ fn shape(text: &str, module: &str) -> Shape {
}
for instance in &instantiation.instances {
let names = match &instance.conns {
Connections::Named(conns) => conns.iter().map(|c| c.name.clone()).collect(),
// An error element keeps its place in the fingerprint — it is
// an element of the list — but it names nothing, exactly as a
// positional connection names nothing.
Connections::Named(conns) => conns
.iter()
.map(|c| c.ok().map(|c| c.name.clone()).unwrap_or_default())
.collect(),
Connections::Ordered(conns) => conns.iter().map(|_| String::new()).collect(),
};
out.instances.push((instance.name.clone(), names));
+8 -6
View File
@@ -5,7 +5,7 @@
use std::path::Path;
use vlog_parser::ast::{Connections, Instance, Instantiation};
use vlog_parser::ast::{Connections, Instance, Instantiation, ListElem};
use vlog_parser::span::TextRange;
use vlog_parser::{parse_source_tolerant, LineIndex};
@@ -16,7 +16,7 @@ use super::find::{
collect_instantiations, declared_ports, find_module, locate_module, name_visible, not_in_scope,
ModuleSite,
};
use super::list::{append_to_list, conn_list_open};
use super::list::{append_to_list, conn_list_open, elem_spans};
use super::{shape, ModuleRef, Plan};
pub(super) fn plan_propagate(
@@ -64,7 +64,8 @@ pub(super) fn plan_propagate(
}
Connections::Named(conns) => conns,
};
if conns.iter().any(|c| c.name == "*") {
// An error element names no port: it neither connects one nor blocks one.
if conns.iter().filter_map(ListElem::ok).any(|c| c.name == "*") {
return Err(format!(
"`{}` connects with `.*`, which already binds every same-named port.",
instance.name
@@ -80,7 +81,7 @@ pub(super) fn plan_propagate(
let missing: Vec<String> = declared
.iter()
.map(|p| p.name.clone())
.filter(|name| conns.iter().all(|c| &c.name != name))
.filter(|name| conns.iter().filter_map(ListElem::ok).all(|c| &c.name != name))
.collect();
if missing.is_empty() {
return Err(format!(
@@ -89,7 +90,7 @@ pub(super) fn plan_propagate(
));
}
let spans: Vec<TextRange> = conns.iter().map(|c| c.span).collect();
let spans: Vec<TextRange> = elem_spans(conns, |c| c.span);
let Some(open) = conn_list_open(text, instance, spans.first().copied()) else {
return Err(missing_parens(&instance.name, file));
};
@@ -101,7 +102,8 @@ pub(super) fn plan_propagate(
let mut edits = Vec::new();
let mut spans = spans;
let mut todo: Vec<String> = Vec::new();
let mut connected: Vec<String> = conns.iter().map(|c| c.name.clone()).collect();
let mut connected: Vec<String> =
conns.iter().filter_map(ListElem::ok).map(|c| c.name.clone()).collect();
for name in &missing {
let expr = if name_visible(scope, i, at, name) {
name.clone()
+12 -6
View File
@@ -5,7 +5,7 @@
use std::path::Path;
use vlog_parser::ast::{Connections, ItemKind, Module, PortList};
use vlog_parser::ast::{Connections, ItemKind, ListElem, Module, PortList};
use vlog_parser::span::TextRange;
use vlog_parser::{parse_source_tolerant, LineIndex};
use vlog_semantic::SymbolKind;
@@ -18,7 +18,7 @@ use super::find::{
collect_instantiations, declared_ports, find_module, locate_module, module_at, not_in_scope,
ModuleSite,
};
use super::list::{remove_element, whole_line};
use super::list::{elem_spans, remove_element, whole_line};
use super::{shape, ModuleRef, Plan};
/// The module and port name a removal request points at. The cursor may sit on
@@ -270,7 +270,9 @@ fn disconnection_edits(
// `.*` binds the port implicitly, so there is nothing to
// delete — and the signal it was binding may now have no
// reader at all, which is worth saying.
if conns.iter().any(|c| c.name == "*") && conns.iter().all(|c| c.name != port) {
// An error element names no port either way.
let named = || conns.iter().filter_map(ListElem::ok);
if named().any(|c| c.name == "*") && named().all(|c| c.name != port) {
warnings.push(format!(
"`{}` at {}:{} connects with `.*`, so nothing was removed there; the signal it bound `{port}` to may now be unused.",
instance.name,
@@ -279,11 +281,15 @@ fn disconnection_edits(
));
continue;
}
let Some(index) = conns.iter().position(|c| c.name == port) else { continue };
let Some(index) =
conns.iter().position(|c| c.ok().is_some_and(|c| c.name == port))
else {
continue;
};
// The connected expression goes with the connection. A
// plain `.p(p)` loses nothing; anything else is said out
// loud, because it is the user's code being deleted.
if let Some(expr) = conns.get(index) {
if let Some(expr) = conns.get(index).and_then(ListElem::ok) {
let written = text.get(expr.span.as_range()).unwrap_or("");
let trivial = written == format!(".{port}({port})")
|| written == format!(".{port}()")
@@ -296,7 +302,7 @@ fn disconnection_edits(
));
}
}
let spans: Vec<TextRange> = conns.iter().map(|c| c.span).collect();
let spans: Vec<TextRange> = elem_spans(conns, |c| c.span);
sites += 1;
edits.append(&mut remove_element(text, &spans, index)?);
}
+2 -2
View File
@@ -36,7 +36,7 @@ impl<'a> Binder<'a> {
// class's own parameters (`extends base #(.W(W))`), so it binds
// in the class scope.
let base = last_segment(&ext.name);
for conn in ext.params.iter().flatten() {
for conn in ext.params.iter().flatten().filter_map(ListElem::ok) {
if conn.name != "*" {
self.use_name(
inner,
@@ -330,7 +330,7 @@ impl<'a> Binder<'a> {
kind: SymbolKind,
scope_kind: ScopeKind,
ret: Option<&DataType>,
args: &'a [TfArg],
args: &'a [ListElem<TfArg>],
stmts: &'a [Stmt],
) {
let home = self.out_of_body_home(path, name_span, span, decl_scope);
+10 -3
View File
@@ -24,11 +24,16 @@ impl<'a> Binder<'a> {
/// what an instantiation may override — the two now agree because they
/// read the same field the same way, where before this one read nothing
/// and called everything a `Param`.
///
/// An error element — a parameter a tolerant parse could not read — is
/// skipped, the way `bind/item.rs` skips an [`ItemKind::Error`]: it
/// declares nothing, so there is nothing to bind.
pub(super) fn bind_param_ports(
&mut self,
ports: impl Iterator<Item = &'a ParamPort>,
ports: impl Iterator<Item = &'a ListElem<ParamPort>>,
scope: ScopeId,
) {
let ports = ports.filter_map(ListElem::ok);
let mut kw = String::new();
for p in ports {
if let Some(written) = &p.kw {
@@ -42,8 +47,10 @@ impl<'a> Binder<'a> {
}
}
pub(super) fn bind_tf_args(&mut self, args: &'a [TfArg], scope: ScopeId) {
for a in args {
/// A subroutine's formals. An error element declares nothing, exactly as
/// in [`Binder::bind_param_ports`].
pub(super) fn bind_tf_args(&mut self, args: &'a [ListElem<TfArg>], scope: ScopeId) {
for a in args.iter().filter_map(ListElem::ok) {
self.bind_data_type(&a.ty, TextRange::new(a.span.start, a.name_span.start), scope);
let ty = a.unpacked.is_empty().then_some(&a.ty);
self.declare_typed(scope, &a.name, SymbolKind::TfArg, a.name_span, a.span, ty);
+9 -3
View File
@@ -35,9 +35,15 @@ impl<'a> Binder<'a> {
match &e.kind {
ExprKind::Ident(name) => self.use_name(scope, name, e.span, Target::Lexical),
// `Verbatim` is a region whose value depends on a `` `ifdef ``
// this crate never evaluates: opaque bytes record nothing.
ExprKind::Number(_) | ExprKind::Str(_) | ExprKind::Empty(_) | ExprKind::Verbatim(_) => {
}
// this crate never evaluates: opaque bytes record nothing. Nor
// does `Error`, the text a tolerant parse could not read as a
// statement header's condition — the same call `bind/item.rs`
// makes for an `ItemKind::Error`.
ExprKind::Number(_)
| ExprKind::Str(_)
| ExprKind::Empty(_)
| ExprKind::Verbatim(_)
| ExprKind::Error(_) => {}
ExprKind::Unary { expr, .. } | ExprKind::Postfix { expr, .. } => {
self.bind_expr(expr, scope)
}
+24 -26
View File
@@ -205,8 +205,10 @@ impl<'a> Binder<'a> {
}
self.bind_param_ports(m.param_ports.iter().flatten(), inner);
match &m.ports {
// An error element — a port a tolerant parse could not read —
// declares nothing, exactly as an `ItemKind::Error` does.
PortList::Ansi(ports) => {
for p in ports {
for p in ports.iter().filter_map(ListElem::ok) {
self.bind_data_type(
&p.ty,
TextRange::new(p.span.start, p.name_span.start),
@@ -225,7 +227,7 @@ impl<'a> Binder<'a> {
}
}
PortList::NonAnsi(ports) => {
for p in ports {
for p in ports.iter().filter_map(ListElem::ok) {
self.declare(inner, &p.name, SymbolKind::Port, p.span, p.span);
}
}
@@ -262,7 +264,7 @@ impl<'a> Binder<'a> {
// so it is taken only when it slices back to the stored name.
let ns = self.exact_or_empty(i.module_span, &i.module);
self.use_name(scope, &i.module, ns, Target::Module);
for c in i.params.iter().flatten() {
for c in i.params.iter().flatten().filter_map(ListElem::ok) {
self.bind_connection(c, &i.module, scope);
}
for inst in &i.instances {
@@ -284,18 +286,7 @@ impl<'a> Binder<'a> {
self.symbols[id.0 as usize].type_name = Some(i.module.clone());
}
self.bind_dims(&inst.dims, scope);
match &inst.conns {
Connections::Named(conns) => {
for c in conns {
self.bind_connection(c, &i.module, scope);
}
}
Connections::Ordered(conns) => {
for c in conns {
self.bind_opt_expr(c.expr.as_ref(), scope);
}
}
}
self.bind_connections(&inst.conns, &i.module, scope);
}
}
@@ -333,24 +324,31 @@ impl<'a> Binder<'a> {
let ns = self.exact_or_empty(i.module_span, &i.module);
self.use_name(scope, &i.module, ns, Target::Module);
let previous = std::mem::replace(&mut self.bind_target, head.map(|h| h.name.clone()));
for c in i.params.iter().flatten() {
for c in i.params.iter().flatten().filter_map(ListElem::ok) {
self.bind_connection(c, &i.module, scope);
}
for inst in &i.instances {
match &inst.conns {
Connections::Named(conns) => {
for c in conns {
self.bind_connection(c, &i.module, scope);
}
self.bind_connections(&inst.conns, &i.module, scope);
}
self.bind_target = previous;
}
/// One instance's connection list, named or positional. An error element
/// — a connection a tolerant parse could not read — names nothing and
/// values nothing, so it binds nothing.
fn bind_connections(&mut self, conns: &Connections, module: &str, scope: ScopeId) {
match conns {
Connections::Named(conns) => {
for c in conns.iter().filter_map(ListElem::ok) {
self.bind_connection(c, module, scope);
}
Connections::Ordered(conns) => {
for c in conns {
self.bind_opt_expr(c.expr.as_ref(), scope);
}
}
Connections::Ordered(conns) => {
for c in conns.iter().filter_map(ListElem::ok) {
self.bind_opt_expr(c.expr.as_ref(), scope);
}
}
}
self.bind_target = previous;
}
fn bind_connection(&mut self, c: &Connection, module: &str, scope: ScopeId) {
+6 -4
View File
@@ -61,7 +61,7 @@ request.
| M7 | Semantic lints (`unused-signal`, `undriven-net`, `multiply-driven`) ship **off by default**. | linter-core / semantic-lints READMEs; blocked on topo §2.9-6 (workspace-wide "does any file mention this name"). | These are the lints RTL engineers want most; the index now has reference postings and `files_spelling`, so §2.9-6 is closer than when filed. |
| M8 | ~~Lint rules do not descend into verbatim regions~~ — **closed at 0.33.0 for what parses**, by construction: the rules read the reference table, and a structured assertion contributes ordinary references to it. A `signals.rs` `opaque_span` remains only for a region that fell back. | assertions / clocking-wave / sva-bodies READMEs. | Same root as C1; resolved with it. |
| ~~M9~~ | ~~Statement-level format fences (inside `always`, case items, port lists) and fences inside class bodies (topo §2.9-3).~~ — **closed at 0.34.0+ by TODO §31.** Class bodies and every statement *list* (`begin`…`end`, `fork`…`join*`, function/task bodies, `initial`/`always`/`final` bodies, a `case` item's block body, a statement fragment) are fenceable scopes; `--lines` still loses to a fence. Two of the three named places stay out, with reasons: port/parameter lists and `case` **label** lists print mid-line inside a `Group`, where `Doc::Verbatim` (column-0, break-forcing) cannot stand — that wants a new printer primitive, not a scan arm. Measured on OpenTitan, which has 9 fenced files: four now keep their fenced bytes, including a 110-line class-body region. | statement-fences README; format-fences / classes / shared-fence-filter READMEs amended. | Users protect hand-aligned tables inside procedural blocks; DV users protect them in classes. |
| M10 | Error recovery does not reach headers and lists (port lists, parameter lists, for-headers) — a half-typed port list yields a garbage tree. | error-recovery README (QA-confirmed). | Editing experience: diagnostics cascade while typing a header. |
| ~~M10~~ | ~~Error recovery does not reach headers and lists (port lists, parameter lists, for-headers) — a half-typed port list yields a garbage tree.~~ — **closed by TODO §32.** A list element that does not parse is now a `ListElem::Error` element of its own list and a statement header's broken condition an `ExprKind::Error`, so the module, function or instantiation keeps its name, the elements that were typed and its body: the QA shape that cost 3 items and 2 diagnostics costs 1 and 1, and the `wire w;` under a half-typed `sub u (.a(` is a sibling item again. Measured over the corpus truncated at each file's midpoint: **622 → 555 error nodes** (−11 %), while diagnostics rise 1 702 → 1 826 because the constructs that now survive report their own missing closers (`expected \`endmodule\`` +91) instead of vanishing into one node. | header-recovery README; error-recovery README amended. | Editing experience: diagnostics no longer cascade while typing a header, and the outline keeps the module. |
| M11 | Anonymous aggregate members (`enum {A,B} x;`) not symbols (topo §2.9-13); cast type `state_t'(0)` records no reference. | overlay-promotion README; probe: enum *typedef'd* members do work. | Partial: named enums navigate, anonymous ones do not. |
| M12 | No `lint` key in `lucisv.toml` (topo §2.9-4); no `--rules-doc`. | four READMEs. | Config surface, not language — but it gates per-project rule selection. |
| ~~M13~~ | ~~Modport method prototypes (`import task drive(int x);`), `const` task/function arguments, unnamed DPI formals.~~ — **closed at 0.33.0 by TODO §30.** Modport method prototypes parse, format, bind and span; unnamed DPI formals parse behind the DPI flag only (§35.5.5), print as their type alone and declare nothing. The `const` half was **misfiled**: `const ref` (§13.5.2's only `const` argument form) has parsed and formatted since the corpus shape landed — the probe found only one real gap, a comment written *between* `const` and `ref`, now its own slot. | interface-dpi-arms README; interfaces / dpi-export READMEs. | Real interface-class idioms; each was a small grammar arm. |
@@ -149,9 +149,11 @@ signal named only inside a property edits it, references list it, and the
"at least identifier occurrences" fallback the C1 row asked for was
overtaken rather than built (what the grammar cannot read still rewinds to
the byte-exact capture, and rename *names* those regions instead of going
quiet). What the tables above still leave open, by weight: M10 error recovery
inside headers and lists; the second half of
M12 (`--rules-doc`, §2.9-5); L3, L6, L9 and L10. M13's small
quiet). What the tables above still leave open, by weight: the second half of
M12 (`--rules-doc`, §2.9-5); L3, L6, L9 and L10. M10's error recovery inside
headers and lists is closed (TODO §32), with the narrowing recorded in its
row: a truncated file reports *more* diagnostics than before, because the
constructs that now survive say what closer they are missing. M13's small
interface/DPI grammar arms are closed (TODO §30) — with one narrowing
recorded there: a single `import` may carry one prototype, not a
comma-separated list of them. M9's format fences are closed too (TODO §31,
+30 -9
View File
@@ -129,7 +129,19 @@ structure at all.
`for (i = 0; i < ; i = i + 1)` fails inside the header, resyncs at the `;`
*inside* the header, and reports again on the remains. Every extra
diagnostic is at a real position and the file still parses to the end; no
attempt is made to suppress cascades.
attempt is made to suppress cascades. *(Amended 2026-09-03: that `for` is
now one diagnostic — its `;`s are inside the header's own brackets and the
seeded counter makes them invisible. See `docs/features/header-recovery/
README.md`; cascades in general are still not suppressed.)*
- **A broken *header* distorts the tree around it, not just the header.**
This is the shape a consumer had to expect before header recovery landed:
an error anywhere inside a port list, parameter list, formal list or
connection list escapes to the nearest enclosing *item or statement list*,
so the whole `Module`/`FunctionDecl`/`Instantiation` becomes one error node,
its body re-parses at the enclosing scope, and its `endmodule` is orphaned
into a second error item — 2 diagnostics and a misleading tree for one typo.
*(Amended 2026-09-03: `docs/features/header-recovery/README.md` closes this;
the sentence stays because the Review below refers to it.)*
- **Comments attached to a construct that failed to parse are dropped from the
tolerant tree.** They were harvested into the failed node's `Meta` before
the error, and comments *inside* the skipped range survive only as bytes of
@@ -246,6 +258,14 @@ signatures.
`module`, `wire [7:`, `sub u0 (.a(`, garbage between two modules (six
kinds), error inside a generate block, error inside a function body,
all-garbage file, stray `endmodule`, lex error, empty file.
*(Amended 2026-09-03: two of these changed outcome when header recovery
landed, and their pins were rewritten to match. `sub u0 (.a(` no longer
costs the item — the instantiation keeps its name and its typed
connection, the half-typed one is an error **element**, and the `wire w;`
under it is a sibling item again; `for (i = 0; i < ; i = i + 1)` costs
one diagnostic instead of two. Every other shape here is unchanged, byte
for byte. The full before/after table is in
`docs/features/header-recovery/README.md`.)*
- [x] `cargo test --workspace` green, `cargo clippy -p vlog_parser
--all-targets` silent, `cargo fmt --check` clean.
- [x] TODO.md §6 error-tolerant checkbox.
@@ -253,14 +273,15 @@ signatures.
- [ ] **Not done:** cascade suppression (a "don't report twice within N
tokens" rule). Wait for the LSP to show whether the cascades are
actually noisy in practice.
- [ ] **Not done:** recovery inside headers and lists (port lists, parameter
lists, for-headers). Those need per-construct resync points, and the
first consumer should say whether the coarse-grained answer is enough.
Note (QA finding, lead-confirmed): today a broken *header* doesn't just
go unrecovered — it distorts the surrounding tree (the module body
re-parses as file-scope items and the orphaned `endmodule` becomes a
second error item, 2 diagnostics for one typo). The LSP consumer
should expect that shape until header recovery lands.
- [x] **Done, 2026-09-03, by a feature of its own:** recovery inside headers
and lists (port lists, parameter lists, formal lists, connection lists,
for-headers). The per-construct resync points this asked for are the
list-local, bracket-seeded sync set in `parser/recover_list.rs`, and the
QA finding above is closed: the module keeps its name, its typed
elements and its body, and the shape that cost 3 items and 2 diagnostics
costs 1 and 1. `docs/features/header-recovery/README.md` is the feature;
the mechanism in *this* README — item and statement lists — is
unchanged and still handles everything outside a header.
## Work log
+663
View File
@@ -0,0 +1,663 @@
# 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; needs
re-applying at merge — this branch predates 0.36.0's linter):** 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`).
- [x] 32.6 the completion pin: `a_broken_header_still_completes_from_the_
modules_scope` — with a half-typed parameter above the cursor, the
module still has a scope and `visible_symbols` still answers from it.
- [x] 32.6 the three validity probes (`inline.rs`, `templates.rs`,
`completion/tiers.rs`) keep their verdicts, and each now has a pin for
the other direction: broken text still reports, so the probe is still
discriminating.
- [x] 32.7 measurements: `parse_tolerant` timing before/after on the largest
corpus file, and the truncated-at-midpoint corpus census. Numbers in the
work log.
- [x] 32.7 docs: the error-recovery README's Assumptions sentence, its
inverted "Not done" line and its mid-edit-shapes note;
`docs/coverage_gaps.md` M10 closed; TODO §32 ticked.
- [x] Gates: `cargo fmt -p` per crate, `cargo clippy --all-targets
--workspace` (0 warnings), `cargo test --workspace` (3 259 / 0 / 42),
corpus 814/820 with `--stdout` byte-identical to the 0.36.0 baseline
over all 820 files, and the read-only opentitan sweep unchanged.
## 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`.
### 2026-09-04 — dev agent (finished: 32.6, 32.7, docs, gates)
**32.6, completed.** `completion/tiers.rs` gained
`a_broken_header_still_completes_from_the_modules_scope`: with
`#(parameter W = , parameter DEPTH = 4)` above the cursor and the cursor inside
the port list, `DEPTH` is still offered at `TIER_SCOPE` — the module has a
scope again, so the scope chain covering that offset is the module's. The three
validity probes keep their verdicts (they assert an *empty* diagnostic list for
generated text, and that text still parses); each file also gained a pin for
the direction that actually matters after this round — recovery widened what a
tolerant parse reads, so a probe is only worth asking while broken text still
reports. `the_insertion_probe_…`, `the_expansion_probe_…` and
`the_accepted_text_probe_still_reports_text_that_does_not_parse` are those.
**32.7, measurement 1 — `parse_tolerant` cost on the largest corpus file.**
Measured properly rather than across binaries built on different days: the
parser crate was extracted at both revisions into a throwaway harness
(scratchpad only, nothing in the repo) that times `parse` and `parse_tolerant`
over the same tokens, so the *strict* path — which this round provably does not
touch — is the control.
| `corpus/picorv32/picorv32.v` (94 657 B, 16 559 tokens) | `parse` | `parse_tolerant` |
|---|---|---|
| before (§32 absent) | 2.455 / 2.175 / 2.161 ms | 2.302 / 2.101 / 2.141 ms |
| after (this branch) | 2.214 / 2.190 / 2.170 ms | 2.172 / 2.167 / 2.166 ms |
Three runs each, mean of 40 parses per run, clone included. Run-to-run spread
is ~2 % **on the untouched strict path too**, and the tolerant/strict ratio is
≤ 1 on both builds — so the new bookkeeping (`let at = self.pos`, a diagnostic
mark per header, one extra branch per element) is below the noise floor. The
same holds on `ibex_core.sv` (1.298 → 1.216 ms tolerant, with strict moving
1.473 → 1.233 ms between the two builds, which is the point). The in-repo
`perf.rs` harness, run read-only, prints `parse_tolerant` 1.34 ms at 1 k lines
and 15.5 ms at 10 k against `docs/perf/README.md`'s 1.16 / 14.3 ms — but
`tokenize` (untouched) reads 1.39 ms against a recorded 1.14 ms in the same
run, so that table was taken on a faster day and is not a before/after.
**32.7, measurement 2 — the truncated-corpus census.** Every corpus file cut at
its midpoint (char-boundary), parsed tolerantly, by both revisions of the
parser:
| | error nodes | diagnostics |
|---|---|---|
| before | 622 | 1 702 |
| after | **555** (−11 %) | **1 826** (+7 %) |
Error nodes fell, as predicted. **Diagnostics rose, which the plan did not
predict**, and the breakdown says why: `expected \`endmodule\`` goes 333 → 424
(+91) and `expected \`)\`` 118 → 147 (+29), while `expected identifier` falls
77 → 63. A module whose header is cut in half now *survives* and reaches its
body loop, where a truncated file has no `endmodule` — so it says so. Before,
that module was swallowed into one error node and said nothing about its
closer. The rise is 91 modules-worth of "you have not closed this yet", not new
noise: the new `expected \`,\`` message does not even reach the top eight. An
LSP shows the same count of *squiggles per real problem*, on constructs that
now exist in the tree.
**Gates, all through `tools/guard.sh`.**
- `cargo fmt -p` for each of the six touched crates — clean (it reflowed three
lines of mine).
- `cargo clippy --all-targets --workspace` — **0 warnings**.
- `cargo test --workspace` — **3 259 passed, 0 failed, 42 ignored**. That is
0.35.0's 3 244 plus exactly the 15 pins this round adds (9 in
`error_recovery.rs`, 6 in the server). The branch is based on 6a15594, so it
does *not* carry 0.36.0's §33 linter tests; the 3 393 / 48 the lead quoted is
master's number, and the comparison to make at merge is 3 393 + 15.
- `cargo build --release -p lucisv` + `scripts/corpus_gate.sh corpus` —
**814/820 (99.3 %)**, the same six failures by category
(`invalid-or-fragment` 2, `directive-split` 1, `macro-items` 1,
`not-verilog` 1, `other` 1).
- `--stdout` over all **820** corpus files against
`~/.cache/lucisv-baselines/lucisv-0.36.0`: **0 differing**. The strict path is
untouched, byte for byte.
- OpenTitan, read-only (`--check` only): identical to the baseline binary's
sweep — **3 896 would reformat, 72 unchanged, 11 failed**, and the failure
*set* and would-reformat *set* diff empty against the baseline, which is
byte-level evidence over 3 979 files. `git -C …/opentitan status --porcelain`
before and after shows the same three files
(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`,
`hw/top_earlgrey/ip/ast/rtl/ast.sv`) and nothing else.
**For the merge.** This branch is based on 6a15594, before 0.36.0. The three
`vlog_linter` arms named in Handshakes (`visit.rs::walk_param_ports`, the two
connection loops in `signals.rs`) are carried here against the *pre*-§33
linter; master's linter has since grown 36 rules, `Severity` on `Rule` and new
files, so those three arms need re-applying to master's versions of the two
files at merge. Nothing else in this branch touches `crates/vlog_linter`.
## QA log
### 2026-09-04 — QA agent
Read CLAUDE.md, TODO §32, this README, `docs/features/error-recovery/README.md`,
and the code in `crates/vlog_parser/src/parser/{recover.rs, recover_list.rs,
module.rs, tf.rs, instance.rs, stmt.rs, keyword_stmt.rs}`,
`crates/vlog_parser/tests/error_recovery.rs`,
`crates/lucisv_server/src/{diagnostics.rs, symbols.rs, completion/tiers.rs}`
before testing. All commands ran through `tools/guard.sh` per CLAUDE.md.
Scratch work in `/private/tmp/.../scratchpad/qa-32/`, including two throwaway
worktrees (`before_4d70de1` at the pre-§32 commit, `throwaway` at f1d44a2 with
the dev's uncommitted diff applied) — neither touched by any tracked-file
edit; both removed after use. Never touched `git checkout/stash/reset/clean`
in the dev worktree; the only edit here is this entry.
**1. Gates — all reproduced exactly, independently.**
- `cargo fmt --all -- --check`: clean.
- `cargo clippy --all-targets --workspace`: 0 warnings. `git diff 4d70de1 --
-- '*.rs'` has zero added `#[allow(` lines.
- `tools/guard.sh -m 8 -t 1800 -- cargo test --workspace --no-fail-fast`:
summed every `test result:` line myself (not trusting the dev's tally) —
**3 259 passed, 0 failed, 42 ignored.** Matches exactly.
- `git diff --stat f1d44a2 -- crates/vlog_formatter/src/verify.rs`: empty.
- Changed-file set: `git diff --stat 4d70de1 -- .` (58 files) is the four
list-type crates + the two disclosed `vlog_linter` arms (`visit.rs`,
`signals.rs`) named in Handshakes, **plus `crates/vlog_refactor/src/{
instantiate.rs, ports/*.rs}` (7 files)**, which is *also* disclosed in
Handshakes ("`vlog_refactor` ... both had to decide") but was not named in
TODO §32's original "Files:" list written 2026-09-02 (written before the
dev found refactor's exhaustive matches also needed arms). Not a violation
— it's transparently documented — but flagging so the lead's merge review
knows the file-ownership list undersold the true footprint. LOW.
- `cargo build --release -p lucisv` + `--stdout` over all **820** corpus
files (`~/.cache/lucisv-corpus`) against `~/.cache/lucisv-baselines/
lucisv-0.36.0`: **0 differing.** `tools/corpus_check.sh`: **814/820
(99.3 %)**, same six failure categories as claimed.
- Opentitan, read-only, sampled: `--check` exit codes over the 118 `.sv`/`.v`
files under `hw/ip/aes` — dev binary vs the 0.36.0 baseline binary — **0
differing.** `git -C .../opentitan status --porcelain` before and after:
unchanged (the same three pre-existing modified files).
**2. The advance guarantee, adversarially, then fuzzed.**
Read `list_ends`/`element_or_recover`/`skip_inside_brackets` end to end. The
guarantee is structural, not argued: every one of the five list loops (ANSI
ports, non-ANSI ports, param ports, tf-args, connections) calls
`list_ends(start, ...)` at the top of its check, and `list_ends`'s *first*
condition in tolerant mode is `self.pos == start` — an iteration that made no
progress ends the list unconditionally, before any of the comma/bracket/
directive logic runs. This holds regardless of what `element_or_recover`,
`recover_element` or `skip_inside_brackets` do internally, including the edge
case where `recover_element`'s own forced-bump is skipped (already at a sync
stop) — the outer check still catches it. I could not construct a case where
this loop iterates without the cursor moving. Confirmed sound.
Fuzzed 30 corpus files of deliberately varied shape (ANSI/non-ANSI ports,
param lists, instantiations, functions, `for`/`if`, macros, `` `ifdef ``
splits, classes, covergroups, header files) under `tools/guard.sh -m 4 -t
900`, running (a) truncate-at-every-byte, (b) delete-every-character, (c)
delete-every-token, (d) insert a stray `,`/`)`/`;`/`(` at every token
boundary, via a standalone harness linked directly against `vlog_parser`
(faster and more precise than shelling out to the CLI per mutation; built in
`scratchpad/qa-32/fuzzharness`, never inside the dev worktree). List of files
and the harness source are in the scratchpad.
**First run hit the guard, and it was my own harness's bug, not the
parser's.** Computing `format!("{tree:?}")` on every one of ~94 658
mutations of `picorv32.v` (94 657 B) to count error nodes, plus (worse)
eagerly collecting the delete-char/insert-stray categories into one
`Vec<String>` of near-full-length variants *before* iterating (up to ~132 000
strings × ~95 KB each for insert-stray alone), pushed the harness itself past
4 GB and `tools/guard.sh` correctly killed it. I isolated the cause with a
second, minimal harness (`leancheck`) that parses every truncation of
`picorv32.v` with no debug-formatting at all: **94 658 parses, 283.6 s total,
max single parse 115.02 ms, RSS flat at ~20 MB** — proving the parser itself
was never the problem. Fixed the harness (lazy iterators throughout instead of eager `Vec<String>`
collection; error-node counting sampled every 20th variant) and reran under
the same `-m 4 -t 900` guard: RSS stayed flat at 20–32 MB through the first
~4.5 minutes (truncate + well into delete-char/delete-token), a small
fraction of the 4 GB cap, with no growth trend — conclusively confirming the
fix. The other 29 files completed cleanly (0 panics) well before that, with
a max single-parse time of **95.73 ms**. Diagnostics and error-node counts
scale with how broken each mutation is (up to ~195 diagnostics on the most
heavily-mutated UVM sequence file) but never explode disproportionately to
input size. No finding against the feature here — the guard kill was mine to
fix, and I did; the corrected full run on all four categories of
`picorv32.v` was still finishing (large file, ~250k total mutations across
the four categories) as this report was written, with memory behavior
already dispositive.
**3. Strict-mode parity, extended to the full corpus.** Wrote a second
standalone harness (`scratchpad/qa-32/fuzzharness/src/bin/parity.rs`) that
walks every `.v`/`.sv` file under `~/.cache/lucisv-corpus`, keeps the ones
`parse_source` accepts, and asserts `Debug` equality against
`parse_source_tolerant` plus an empty diagnostic list. Result: **814
strict-parseable files, 0 mismatches, 0 diagnostics-on-strict-ok.** 814 is
exactly `tools/corpus_check.sh`'s "parsed & formattable" count, which is the
right cross-check. PASS — extends the 550-fixture guarantee to the full
corpus with zero exceptions.
**4. Shapes (a)–(g) and three of my own.** Built a small `shapes` probe
(prints diagnostics + a summary of the tree) against the dev worktree's
`vlog_parser`, in the throwaway harness — equivalent to, and more precise
than, `lucisv --check` for this purpose.
- QA source `module m #(parameter W = , parameter X = 4) (input a); wire
ok; endmodule` → **1 diagnostic**, one `Module m`, `param_ports` = [error,
ok `X`], one ansi port `a`, one body item (the `wire ok;`). Exactly as
pinned.
- (b) `module m (input logic a, inp⏎ output b);` → **1 diagnostic**
(`expected \`,\``), ports `a`, `inp`, `b`, no error element. Exactly as
claimed.
- (e) `sub u (.a(x), .b(⏎ wire w;` → **1 diagnostic**, module body has 2
items (the instantiation with one error connection element, and `wire w;`
as a sibling item). Exactly as claimed.
- (c), (d), (f), (g) I did not re-probe by hand — they are asserted exactly
by the dev's own pins in `tests/error_recovery.rs`, which passed under my
own from-scratch `cargo test --workspace` run (item 1), so I trust them at
the same level as every other passing test in that suite.
**My three added shapes:**
- **A mid-typed interface port list**
(`module m (bus_if.mp bus, input logic clk, input logic\nendmodule\n`):
**1 diagnostic** (`expected identifier`), 3 ansi ports — `bus`, `clk`, and
one error element for the truncated last port. Recovers cleanly; matches
the feature's promise.
- **A broken `case (` header**
(`case (a ==\n endcase\n`, inside a module/initial/begin): **1
diagnostic** (`unexpected keyword \`endcase\` in expression`), the `case`
statement survives with an `Error` condition and correctly consumes
`endcase`. Recovers cleanly.
- **A half-typed `#(` override in an instantiation** — **MEDIUM finding**,
see below.
**MEDIUM: a half-typed parameter override whose broken value can be extended
into a call swallows the whole instantiation, not just the element.**
Source:
```
module m;
sub #(.WIDTH(8), .DEPTH(
u0 (.a(x), .b(y));
endmodule
```
Result: **2 diagnostics**, and the module's one body item is an **item-level
`Error` node covering the entire instantiation** — `.WIDTH(8)`, which parsed
fine, is lost along with everything else. This is the *pre-§32* failure mode
("garbage tree... whole construct destroyed"), not the improved one, despite
this being exactly the shape §32.5 asks to be tested (a half-typed `#(`
override in an instantiation).
Root cause, traced through `recover_element`/`skip_inside_brackets`: `.DEPTH(`
opens a paren the user never closes. `parse_expr_or_type` on the value is
*greedy* and this grammar supports named-argument call syntax
(`f(.a(1), .b(2))`, IEEE 1800 §13.5.3) — so when the very next real construct
happens to look exactly like `identifier(...)` (which an instance name plus
its own connection list always does), the value expression successfully
parses `u0(.a(x), .b(y))` as a **call expression**, consuming the real next
instance's name and connections *before* any error is ever raised. The
`expect_sym(")")` for `.DEPTH(`'s own closing paren then fails on the real
`;` — a clean, single failure — and `element_or_recover` correctly turns
*that* into one list element error. But the instance name it needed
(`u0`) is already gone: `parse_instantiation`'s `instances` loop (which has
no `element_or_recover` of its own — it isn't one of the five covered list
types) calls `expect_name()` on the `;` and fails, and *that* Err has no
recovery closer than the outer item-level `item_or_recover`, which swallows
the whole instantiation, discarding the good `.WIDTH(8)` progress along with
it.
Control test confirming the mechanism (not the bug): the same shape with a
value that *cannot* extend into a call —
`.DEPTH(4\n u0 (.a(x), .b(y));` (a bare number instead of an identifier) —
recovers correctly: **1 diagnostic**, `.DEPTH(` becomes an error element, the
instantiation survives with 1 item. The difference is entirely that `u0(...)`
is syntactically valid as a *continuation* of the broken expression, so the
failure never reaches the list boundary where `element_or_recover` could
catch it before the damage is done.
This is a real, if narrow, gap in the "headers keep their node" promise: it
is not covered by any of the 9 parser pins, and the error-recovery README's
existing "greedy expression" Assumption describes a much milder consequence
(a for-loop's *next statement* is lost, but the loop survives) — here the
*entire enclosing construct* is lost, which is the outcome §32 exists to
prevent. Recommend: either note it explicitly as a known limitation in
Assumptions (the parenthetical, named-argument-call ambiguity is subtle
enough to be worth writing down), or — better — extend the "declines on a
line change" style protection so a connection/param value's own greedy call
parse can also be interrupted by a sync-stop condition, though that is a
larger design question for the dev, not something I should redesign in QA.
File/line: `crates/vlog_parser/src/parser/instance.rs` (`parse_connection`,
`parse_instantiation`'s `instances` loop), `parser/recover_list.rs`
(`element_or_recover`, `skip_inside_brackets`). Reproduction is the source
block above.
**5. Server behavior, over the wire.** Built `cargo build -p lucisv_server`
(already built by item 1's workspace test run) and drove the real
`lucisv-server` binary with hand-rolled LSP framing (same technique as
`tests/e2e.rs`), from a standalone probe binary
(`scratchpad/qa-32/fuzzharness/src/bin/e2e_probe.rs`).
- **Probe A** (the dev's own `diagnostics.rs` pin source, byte for byte:
`module m (input a, , input b);\n wire ok;\nendmodule\n`): documentSymbol
lists module `m` with children port `a`, port `b`, net `ok`. Exactly **1**
`publishDiagnostics` push, **1** diagnostic in it. Matches the unit-test pin
exactly, now confirmed over the real wire protocol too.
- **Probe A2** (the completion-scope pin source, `top #(parameter W = ,
parameter DEPTH = 4) (...)`): completion at the cursor after `output logic
DE` offers `DEPTH` first — `TIER_SCOPE`, as pinned. 1 push, 2 diagnostics
(the 1 parse diagnostic + 1 pre-existing, unrelated lint finding —
`explicit-parameter-storage-type` on the untyped `DEPTH` parameter, which
predates §32 and is not part of the header-recovery diagnostic count; the
dev's own unit test isolates parse-only diagnostics via `diagnostics(doc)`,
which is why it says "1" — the wire-level push legitimately aggregates
parse + lint). Not a discrepancy, just worth stating precisely.
- **Probe B** (real `opentitan/hw/ip/aes/rtl/aes_core.sv`, ~600 lines, one
port line half-deleted **in the buffer sent over `didOpen` only** —
`input logic rst_shadowed_ni,` truncated to
`input logic rst_sh`, no trailing comma):
documentSymbol still lists the whole module — every parameter, `clk_i`,
`rst_ni` *before* the truncation, the truncated port itself (read as a
legitimately-shaped, if oddly-named, ANSI port — no error element needed,
because syntactically `input logic rst_sh` is complete), and every port
*after* it (`entropy_clearing_req_o`, `entropy_clearing_ack_i`, …) through
to the end of the 600+ line body. **Exactly 1** `publishDiagnostics` push
with **1** diagnostic (`expected \`,\`` on the following port line).
Completion at the truncation cursor offers the real identifier
(`rst_shadowed_ni`) alongside the partial token. `git -C
/Users/guoliangchen/repo/opentitan status --porcelain`: unchanged (still
only `hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`,
`hw/top_earlgrey/ip/ast/rtl/ast.sv` — the file itself was never written).
- The three validity probes: confirmed present and asserting the claimed
direction — `templates.rs::the_expansion_probe_still_reports_text_that_
does_not_parse`, `inline.rs::the_accepted_text_probe_still_reports_text_
that_does_not_parse`, `completion/tiers.rs::the_insertion_probe_still_
reports_text_that_does_not_parse` all assert `!parse_source_tolerant(probe)
.1.is_empty()` on genuinely-broken generated text. All green under item 1's
test run.
PASS on the whole item — the user-visible contract holds, including on a
real 600-line file from the wild, not just a hand-crafted fixture.
**6. The census, re-derived independently.** Built two more standalone
harnesses linking `vlog_parser` at two revisions: `before_4d70de1` (the
commit immediately before any §32 work) and the dev worktree as-is. Both cut
every corpus file at its own midpoint (char-boundary-safe) and parse
tolerantly. My numbers, from scratch, matching the dev's exactly:
| | error nodes | diagnostics |
|---|---|---|
| before | 622 | 1 702 |
| after | 555 | 1 826 |
Top-message deltas also match exactly: `expected \`endmodule\`` 333 → 424
(**+91**), `expected \`)\`` 118 → 147 (**+29**), `expected identifier` 77 →
63. Read all 10 files where the diagnostic count rose the most
(`prim_diff_to_alert.sv`, `push_pull_driver_lib.sv`, `synth_gates.v`,
`synth_area_top.v` ×2, `axicheck2.v`, `uart_bind.sv`, `uart_nf_if.sv`,
`prim_flop_en.sv`, `prim_flop.sv`) with both binaries side by side. Every
single one holds the dev's explanation without exception: before, the
header failure swallowed the whole construct into one error node that said
nothing past its own header (1–2 diagnostics, no closer message, because the
body-parsing loop was never reached); after, the same construct survives its
header and reaches the body loop, which then hits EOF without its
`endmodule`/`endclass`/`endinterface`/`)` and reports exactly that. The
"rise is 91 modules-worth of you-have-not-closed-this-yet, not new noise"
claim holds — confirmed, not just plausible.
**7. Docs.** `docs/features/header-recovery/README.md`: all seven sections
present and current. `docs/features/error-recovery/README.md`: the header
sentence is in Assumptions, the "Not done" line is inverted into a "Done,
2026-09-03" entry with the mechanism named, the "known shapes" amendment note
is present. `docs/coverage_gaps.md`: M10 struck through and closed with the
measured numbers. The §33-linter handshake (three arms to re-apply on
master's files at merge) is named precisely (`visit.rs::walk_param_ports`,
two loops in `signals.rs`). The (undisclosed-in-the-original-plan but
disclosed-in-Handshakes) `vlog_refactor` footprint is noted above under
Gates.
**LOW: `TODO.md` §32's "Gates" checkbox is unticked** despite the Gates line
in this very README's Status/TODO being `[x]` and every gate genuinely
passing (independently re-verified in item 1). `TODO.md:3474-3476`. Easy fix
at merge — tick it; the "QA" line below it is correctly left unticked since
QA (this pass) is what resolves it.
**CLAUDE.md compliance:** no `unwrap()`/`expect()`/`panic!` introduced outside
`#[cfg(test)]` (spot-checked the diff's non-test hunks). No `unsafe`. File
sizes: `recover_list.rs` at 322 production lines, comfortably under 600;
nothing in the diff pushes a file over threshold. Runaway guard: every
`cargo test`, fuzz sweep, corpus/opentitan sweep and server run in this QA
pass went through `tools/guard.sh` — including, notably, the one that caught
my own harness's memory bug (item 2), which is exactly what the guard is
for.
**Verdict: PASS.**
No CRITICAL (opentitan confirmed untouched, twice — the aes-subtree sweep and
the e2e probe). No HIGH (no guard kill, panic or slow parse attributable to
the feature itself — the one guard kill in this pass was my own harness,
isolated and fixed; strict-mode parity holds over the full corpus, not just
the 550 fixtures; every pinned shape's exact counts reproduce). One MEDIUM
(item 4: a half-typed `#(...)` override whose value can extend into a call
swallows the whole instantiation rather than just the element — real, not
forcing, worth a follow-up pin) and two LOW (the `vlog_refactor` footprint
undersold in TODO §32's original file list, though disclosed in Handshakes;
the unticked `TODO.md` Gates checkbox). Recommend the lead tick the Gates
checkbox at merge and decide whether the MEDIUM finding gets a follow-up pin
now or is filed for later — it does not block this round, since it is no
worse than pre-§32 behavior on that specific shape, just not yet improved by
it.
## Review
**2026-09-04 — lead.** Accepted. This round earned its structural rule
the hard way: the first cut's list loop could iterate without consuming
a token, and under the delete-any-character fuzzer it allocated
diagnostics until the machine died. The fix — `list_ends` ends a list
whose iteration left the cursor where it started — is a guarantee a
reader can check in one line, QA read it adversarially and then fuzzed
four mutation classes over thirty files without a stall, and the guard
that now wraps every suite exists because of this lane. The second
finding, strict parity broken by recovery swallowing the failure that
`split.rs` needs to see, is fixed at the one place the two mechanisms
meet. The census is reported honestly: fewer error nodes, more
diagnostics, because a module whose header was cut now survives to
report its missing `endmodule` — the right trade. QA's MEDIUM (a
half-typed `#(` override whose value reads as a call swallows the next
instance's name, so that instantiation still collapses to an item-level
error) is filed as `docs/topo.md` §2.9-24, not a rework: the shape is
outside the plan's list and the fix is a lookahead in the override
grammar, its own small item. TODO's Gates line ticked at review; the
`vlog_refactor` touch (two exhaustive-match arms) accepted. The three
`vlog_linter` arms are re-applied at merge against §33's files. Ships
in 0.37.0.