WIP §32 header recovery — DO NOT MERGE: half-finished; a fuzz test loops without advancing and exhausts memory (crashed the machine 2026-09-03)

Checkpoint of the interrupted dev work (rate limit) so master stays
clean. Known state: a_half_typed_instantiation_is_one_error_node
(expected to invert) and tolerant_parse_equals_strict_parse_on_valid_
sources FAIL; the error_recovery test binary exceeds 6 GB under
tools/guard.sh (a non-advancing recovery loop under the delete-any-
character / truncate fuzzers). Resume in a worktree of this branch,
under tools/guard.sh, fixing the advance guarantee first.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-09-03 17:48:28 -07:00
1 parent 4d70de1976
commit 6a15594ae8
50 files changed
+1135 -430

No files matched your search

+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
+19 -2
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
@@ -563,6 +579,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");
}
+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,
})
+42 -3
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,19 @@ 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();
let mut breaks: Vec<bool> = 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)
}
+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.
+4 -2
View File
@@ -5,7 +5,7 @@
//! text and no children, so they are visited and matched by nothing.
use vlog_parser::ast::{
Fragment, GenBlock, GenElse, Item, ItemKind, ParamPort, SourceFile, Stmt, StmtKind,
Fragment, GenBlock, GenElse, Item, ItemKind, ListElem, ParamPort, SourceFile, Stmt, StmtKind,
};
/// Calls `f` on every item in the file, nested items included.
@@ -150,7 +150,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``,
+29 -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,21 @@ 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>>),
}
impl PortList {
/// True when a tolerant parse recovered from an error inside this list.
/// Always false on a tree [`crate::parse`] built.
pub fn has_error(&self) -> bool {
match self {
PortList::None | PortList::Empty => false,
PortList::Ansi(ports) => ports.iter().any(ListElem::is_error),
PortList::NonAnsi(ports) => ports.iter().any(ListElem::is_error),
}
}
}
/// A name-only port in a non-ANSI header (`module m (a, b);`). It has no
@@ -208,7 +220,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 +252,19 @@ pub struct Instance {
#[derive(Debug)]
pub enum Connections {
Ordered(Vec<OrderedConn>),
Named(Vec<Connection>),
Ordered(Vec<ListElem<OrderedConn>>),
Named(Vec<ListElem<Connection>>),
}
impl Connections {
/// True when a tolerant parse recovered from an error inside this list.
/// Always false on a tree [`crate::parse`] built.
pub fn has_error(&self) -> bool {
match self {
Connections::Ordered(conns) => conns.iter().any(ListElem::is_error),
Connections::Named(conns) => conns.iter().any(ListElem::is_error),
}
}
}
#[derive(Debug)]
+6 -6
View File
@@ -101,30 +101,30 @@ 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() {
list.push(self.element_or_recover(|p| p.parse_connection())?);
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(comma, dirs.any) {
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(list.iter().any(ListElem::is_error))?;
params = Some(list);
}
Ok(ClassExtends {
+42 -30
View File
@@ -268,12 +268,12 @@ 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() {
list.push(self.element_or_recover(|p| p.parse_connection())?);
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 +285,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(comma, dirs.any) {
break;
}
}
@@ -293,11 +293,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(list.iter().any(ListElem::is_error))?;
params = Some(list);
}
let mut instances = Vec::new();
@@ -310,7 +310,7 @@ impl<'a> Parser<'a> {
self.expect_sym("(")?;
let mut conn_directives = Vec::new();
let conns = self.parse_connections(&mut conn_directives)?;
self.expect_sym(")")?;
self.close_list(conns.has_error())?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
@@ -377,58 +377,70 @@ 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() {
conns.push(self.element_or_recover(|p| p.parse_connection())?);
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(comma, dirs.any) {
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()?)
conns.push(self.element_or_recover(|p| p.parse_ordered_connection())?);
let comma = match conns.last() {
Some(ListElem::Ok(last)) => last.comma,
_ => 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(comma, dirs.any) {
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.
+101 -72
View File
@@ -86,77 +86,12 @@ 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(")")?;
let cond = self.cond_or_recover()?;
self.expect_after_recovery(")", cond.is_error())?;
Ok(StmtKind::While { cond, body: Box::new(self.parse_stmt()?) })
}
"do" => {
@@ -167,17 +102,17 @@ 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(")")?;
let count = self.cond_or_recover()?;
self.expect_after_recovery(")", count.is_error())?;
Ok(StmtKind::Repeat { count, body: Box::new(self.parse_stmt()?) })
}
"forever" => {
@@ -334,4 +269,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.parse_stmt()?);
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;
+41 -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 `(`.
@@ -41,7 +41,12 @@ 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 recovered keeps its `;` optional: the missing
// one is part of the typo already reported, and the body behind it is
// what the module is for.
let recovered =
param_ports.iter().flatten().any(|p| p.is_error()) || ports.has_error();
self.expect_after_recovery(";", recovered)?;
let mut items = Vec::new();
while !self.at_body_end(end_kw) {
items.push(self.item_or_recover()?);
@@ -325,12 +330,12 @@ impl<'a> Parser<'a> {
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() {
list.push(self.element_or_recover(|p| p.parse_param_port())?);
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 +346,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(comma, dirs.any) {
break;
}
}
}
out.dangling = self.take_dangling();
self.expect_sym(")")?;
self.close_list(list.iter().any(ListElem::is_error))?;
out.ports = Some(list);
Ok(out)
}
@@ -467,32 +474,32 @@ 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() {
ports.push(self.element_or_recover(|p| p.parse_ansi_port())?);
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(comma, dirs.any) {
break;
}
}
// Comments on their own lines before the `)` belong inside it.
let dangling = self.take_dangling();
self.expect_sym(")")?;
self.close_list(ports.iter().any(ListElem::is_error))?;
// 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 +509,36 @@ 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 });
ports.push(self.element_or_recover(|p| p.parse_non_ansi_port())?);
let comma = match ports.last() {
Some(ListElem::Ok(last)) => last.comma,
_ => false,
};
let dirs = self.take_list_directives(&mut directives, ports.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
if self.list_ends(comma, dirs.any) {
break;
}
}
let dangling = self.take_dangling();
self.expect_sym(")")?;
self.close_list(ports.iter().any(ListElem::is_error))?;
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,238 @@
//! 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::*;
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, having just read an element that
/// was (`comma`) or was not followed by a `,`, with `dirs_any` recording
/// whether a compiler directive was harvested after it.
///
/// Strict mode asks exactly what the loops asked before this file
/// existed. Tolerant mode asks the closing bracket instead of the comma: a
/// missing `,` in the middle of a port list would otherwise throw away
/// every port after it. On a list that parses the two agree — the loops
/// all end with the cursor on their `)` — which is what keeps a tolerant
/// parse of a good file identical to a strict one.
pub(super) fn list_ends(&self, comma: bool, dirs_any: bool) -> bool {
if self.tolerant {
return self.at_list_end();
}
(!comma && !dirs_any) || (dirs_any && self.cur().is_sym(")"))
}
/// 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 => {
Ok(ListElem::Error(self.recover_element(start_pos, start, e)))
}
Err(e) => Err(e),
}
}
/// Consume the `)` that closes a header list.
///
/// In tolerant mode a missing one is not a failure: with `recovered` set,
/// the element that failed has already said what is wrong and a second
/// message about the same typo would be noise; without it, the missing
/// bracket is itself the news and gets one diagnostic. Strict mode fails
/// with exactly the message [`Parser::expect_sym`] would have used.
pub(super) fn close_list(&mut self, recovered: bool) -> PResult<()> {
if self.eat_sym(")") {
return Ok(());
}
if self.tolerant {
if !recovered {
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 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,
}
}
}
+4 -4
View File
@@ -161,8 +161,8 @@ 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 cond = self.cond_or_recover()?;
self.expect_after_recovery(")", cond.is_error())?;
let then = Box::new(self.parse_stmt()?);
let mut else_comments = Vec::new();
let els = if self.cur().is_kw("else") {
@@ -182,8 +182,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!(
+73 -66
View File
@@ -222,81 +222,88 @@ impl<'a> Parser<'a> {
return Ok(TfPorts { args, dangling });
}
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) }
args.push(self.element_or_recover(|p| p.parse_tf_arg(allow_unnamed))?);
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(more, false) {
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(args.iter().any(ListElem::is_error))?;
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) {
+72 -11
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))
}
+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) {