Add expressions-2: casts, streaming, ->, drive strengths, pattern replication

Casts with parenthesized/keyword/scoped bases, streaming operators, -> and <-> implication, assign (weak0, pull1) drive strengths, (* attr *) on named connections, '{N{x}} replication in assignment patterns, x inside `MACRO, const ref tf arguments.

Coverage loop round 1, cluster 7: 751 -> 772 / 820 (91.6% -> 94.1%).
Feature README: docs/features/expressions-2/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-21 00:46:39 -07:00
1 parent d071957393
commit c2ea1656e1
10 files changed
+1039 -30

No files matched your search

+343 -13
View File
@@ -141,6 +141,12 @@ const MEMBER_QUALIFIERS: &[&str] = &[
const ASSIGN_OPS: &[&str] =
&["=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "<<<=", ">>>="];
/// The strength keywords a drive strength is written from (IEEE 1800 §28.11).
const DRIVE_STRENGTHS: &[&str] = &[
"supply0", "supply1", "strong0", "strong1", "pull0", "pull1", "weak0", "weak1", "highz0",
"highz1",
];
/// How deeply constructs may nest before the parser gives up.
///
/// Chosen from measured stack use, not from taste: nested statements are the
@@ -252,6 +258,11 @@ pub(crate) fn error_file(source: &str) -> SourceFile {
SourceFile { items: vec![item], dangling: Vec::new(), span }
}
/// True when `t` is one of the strength keywords a drive strength names.
fn is_drive_strength(t: &Token) -> bool {
t.kind == TokenKind::Keyword && DRIVE_STRENGTHS.contains(&t.text.as_str())
}
/// Split an optional [`Name`] into the `(text, span)` pair the nodes that keep
/// a name in a `String` field store it as.
fn split_label(name: Option<Name>) -> (Option<String>, Option<TextRange>) {
@@ -2464,6 +2475,7 @@ impl<'a> Parser<'a> {
fn parse_cont_assign(&mut self) -> PResult<ContAssign> {
self.expect_kw("assign")?;
let strength = self.parse_opt_drive_strength()?;
let delay = if self.cur().is_sym("#") {
self.bump();
Some(self.parse_delay_value()?)
@@ -2495,7 +2507,29 @@ impl<'a> Parser<'a> {
}
}
self.expect_sym(";")?;
Ok(ContAssign { delay, assigns })
Ok(ContAssign { strength, delay, assigns })
}
/// The optional `( strength0 , strength1 )` of a continuous assignment
/// (IEEE 1800 §10.3.1), e.g. `assign (weak0, pull1) x = y;` (corpus
/// `ibex/vendor/lowrisc_ip/ip/prim_generic/rtl/prim_usb_diff_rx.sv:39`).
///
/// Both orders are accepted, as the grammar allows; the `(` only opens a
/// strength when a strength keyword follows it, so a parenthesized
/// left-hand side is untouched.
fn parse_opt_drive_strength(&mut self) -> PResult<Option<DriveStrength>> {
if !self.cur().is_sym("(") || !is_drive_strength(self.nth(1)) {
return Ok(None);
}
self.bump(); // (
let first = self.bump().text;
self.expect_sym(",")?;
if !is_drive_strength(self.cur()) {
return self.error("expected a drive strength");
}
let second = self.bump().text;
self.expect_sym(")")?;
Ok(Some(DriveStrength { first, second }))
}
fn parse_delay_value(&mut self) -> PResult<Expr> {
@@ -2703,7 +2737,7 @@ impl<'a> Parser<'a> {
if self.cur().is_sym(")") {
return Ok(Connections::Ordered(Vec::new()));
}
if self.cur().is_sym(".") {
if self.at_named_connection() {
let mut conns = Vec::new();
loop {
conns.push(self.parse_connection()?);
@@ -2758,11 +2792,31 @@ impl<'a> Parser<'a> {
}
}
/// 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.
fn at_named_connection(&self) -> bool {
let mut i = self.pos;
while i < self.tokens.len() && self.tokens[i].kind == TokenKind::Attribute {
i += 1;
}
self.tokens.get(i).is_some_and(|t| t.is_sym("."))
}
/// `.name(expr)`, `.name()`, `.name`, `.*`, or (for parameter lists and
/// ordered parameter overrides) a bare expression.
fn parse_connection(&mut self) -> PResult<Connection> {
let start = self.here();
let mut meta = self.take_meta();
// `(* async *) .async_data_o (x)` — an attribute instance may precede
// a port connection (IEEE 1800 §A.4.1.1), corpus
// `common_cells/src/cdc_fifo_gray.sv:140`. Harvested exactly the way
// an item's or a statement's attributes are.
while self.cur().kind == TokenKind::Attribute {
meta.attrs.push(self.take_raw_text());
let tok = &mut self.tokens[self.pos];
meta.leading.append(&mut tok.leading);
}
if self.eat_sym(".") {
let star = self.cur().span;
if self.eat_sym("*") {
@@ -3101,7 +3155,17 @@ impl<'a> Parser<'a> {
let mut meta = self.take_meta();
let dir = {
let t = self.cur();
if t.is_kw("input") || t.is_kw("output") || t.is_kw("inout") || t.is_kw("ref") {
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`.
self.bump();
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
@@ -3652,7 +3716,44 @@ impl<'a> Parser<'a> {
// ------------------------------------------------------------------
pub fn parse_expr(&mut self) -> PResult<Expr> {
self.parse_ternary()
self.parse_implication()
}
/// The implication operators `->` and `<->` (IEEE 1800 §11.3.2): the
/// lowest-precedence binary operators, below `? :`, right-associative.
///
/// They sit above [`Parser::parse_ternary`] rather than in the
/// precedence-climbing table because everything in that table binds
/// tighter than `? :`. A `->` is only read as an operator here, *after*
/// an operand — `-> ev;` at statement position is still an event trigger,
/// which `parse_stmt_kind` takes before any expression is parsed.
fn parse_implication(&mut self) -> PResult<Expr> {
let mark = self.pending_trailing.len();
let start = self.here();
let lhs = self.parse_ternary()?;
if !self.cur().is_sym("->") && !self.cur().is_sym("<->") {
return Ok(lhs);
}
let before = self.take_around(mark);
let op = self.bump().text;
let after = self.take_around(mark);
// Right-associative: `a -> b -> c` is `a -> (b -> c)`, so the chain
// recurses and is gated. Only the recursion is: an expression with no
// `->` in it must cost no nesting budget, or every other construct's
// depth limit would halve.
self.enter()?;
let rhs = self.parse_implication();
self.leave();
let rhs = rhs?;
Ok(self.expr_at(
start,
ExprKind::Binary {
lhs: Box::new(lhs),
op,
rhs: Box::new(rhs),
comments: Box::new(BinaryComments { before, after }),
},
))
}
/// The gate for the whole expression grammar: every expression recursion
@@ -3743,6 +3844,16 @@ impl<'a> Parser<'a> {
}
if self.cur().is_kw("inside") {
self.bump();
// `x inside `MACRO` — the macro expands to the `{...}` set,
// so it stands in for one (corpus
// `opentitan/hw/ip/uart/dv/env/uart_scoreboard.sv:155`).
if self.cur().is_macro() {
let set = self.bump().text;
self.link()?;
let start = lhs.span.start;
lhs = self.expr_at(start, ExprKind::InsideMacro { lhs: Box::new(lhs), set });
continue;
}
self.expect_sym("{")?;
let mut ranges: Vec<ExprItem> = Vec::new();
loop {
@@ -3926,17 +4037,27 @@ impl<'a> Parser<'a> {
self.expect_sym(")")?;
expr = self.expr_at(start, ExprKind::Call { callee: Box::new(expr), args });
} else if t.is_sym("'") && self.nth(1).is_sym("(") {
// Cast: `expr'(x)` where expr is a simple name or size.
let ty = match &expr.kind {
ExprKind::Ident(n) => n.clone(),
ExprKind::Number(n) => n.clone(),
_ => return self.error("unsupported cast base expression"),
};
// Cast: `expr'(x)`. The casting type is a `constant_primary`
// (IEEE 1800 §6.24.1): a name, a package-scoped or
// hierarchical name, a size, or a parenthesized constant
// expression — `(NumLevels)'(unsigned'(j))` (corpus
// `common_cells/src/lzc.sv:67`).
if !matches!(
expr.kind,
ExprKind::Ident(_)
| ExprKind::Number(_)
| ExprKind::Scope { .. }
| ExprKind::Member { .. }
| ExprKind::Paren { .. }
) {
return self.error("unsupported cast base expression");
}
self.bump(); // '
self.bump(); // (
let inner = self.parse_expr()?;
self.expect_sym(")")?;
expr = self.expr_at(start, ExprKind::Cast { ty, expr: Box::new(inner) });
expr = self
.expr_at(start, ExprKind::Cast { ty: Box::new(expr), expr: Box::new(inner) });
} else {
// `++` / `--`, the only remaining segment kind.
let op = self.bump().text;
@@ -3946,6 +4067,72 @@ impl<'a> Parser<'a> {
Ok(expr)
}
/// A streaming concatenation, the `{` already consumed and the cursor on
/// its `<<` or `>>`: IEEE 1800 §11.4.14
/// `{ (<<|>>) [slice_size] { stream_expression {, stream_expression} } }`.
///
/// The `with [range]` form of a stream expression is not supported; a
/// file using it keeps its old "expected expression" error.
fn parse_stream_concat(&mut self, start: u32) -> PResult<Expr> {
let dir = self.bump().text;
// The slice size is optional and is a constant expression or a type
// (`{<< byte {x}}`); a `{` here means it was omitted.
let slice =
if self.cur().is_sym("{") { None } else { Some(Box::new(self.parse_expr_or_type()?)) };
self.expect_sym("{")?;
let first = self.parse_expr_item()?;
let inner = self.parse_expr_list(first, "}")?;
self.expect_sym("}")?;
self.expect_sym("}")?;
Ok(self.expr_at(start, ExprKind::Stream { dir, slice, inner }))
}
/// True when the `'{` just consumed opens the replication form
/// `'{N{0}}` (IEEE 1800 §10.9.1) rather than a keyed or positional
/// pattern.
///
/// Decided by a lookahead rather than by parsing the first element,
/// because the element's leading comments are harvested by the parse and
/// there is nowhere to put them back. The first delimiter reached at
/// bracket depth zero says which form this is: `{` opens the replicated
/// list, `:` a keyed element, `,` or `}` a positional one. The `{` must
/// not be the very first token — `'{{a, b}}` is a pattern whose one
/// element is a concatenation.
fn at_assign_pattern_repl(&self) -> bool {
let mut depth = 0u32;
let mut i = self.pos;
while i < self.tokens.len() {
let t = &self.tokens[i];
if t.kind == TokenKind::Eof {
return false;
}
if t.kind == TokenKind::Symbol {
match t.text.as_str() {
"(" | "[" | "'{" => depth += 1,
")" | "]" => depth = depth.saturating_sub(1),
"{" if depth > 0 => depth += 1,
"{" => return i > self.pos,
"}" if depth > 0 => depth -= 1,
"}" | ":" | "," if depth == 0 => return false,
_ => {}
}
}
i += 1;
}
false
}
/// `'{N{a, b}}`, the `'{` already consumed.
fn parse_assign_pattern_repl(&mut self, start: u32) -> PResult<Expr> {
let count = self.parse_expr()?;
self.expect_sym("{")?;
let first = self.parse_expr_item()?;
let inner = self.parse_expr_list(first, "}")?;
self.expect_sym("}")?;
self.expect_sym("}")?;
Ok(self.expr_at(start, ExprKind::AssignPatternRepl { count: Box::new(count), inner }))
}
fn parse_primary(&mut self) -> PResult<Expr> {
let start = self.here();
let t = self.cur();
@@ -3972,12 +4159,17 @@ impl<'a> Parser<'a> {
&& self.nth(1).is_sym("'")
&& self.nth(2).is_sym("(")
{
let ty = self.bump().text;
let ty_start = self.here();
let ty_text = self.bump().text;
let ty = self.expr_at(ty_start, ExprKind::Ident(ty_text));
self.bump(); // '
self.bump(); // (
let inner = self.parse_expr()?;
self.expect_sym(")")?;
return Ok(self.expr_at(start, ExprKind::Cast { ty, expr: Box::new(inner) }));
return Ok(self.expr_at(
start,
ExprKind::Cast { ty: Box::new(ty), expr: Box::new(inner) },
));
}
// Type keyword used as an argument (e.g. `$bits(int)`).
if TYPE_KEYWORDS.contains(&kw.as_str()) {
@@ -4030,6 +4222,9 @@ impl<'a> Parser<'a> {
}
"{" => {
self.bump();
if self.cur().is_sym("<<") || self.cur().is_sym(">>") {
return self.parse_stream_concat(start);
}
if self.cur().is_sym("}") {
// `{}` — the empty queue/dynamic-array literal
// (`q = {};`). Illegal as a Verilog concatenation,
@@ -4056,6 +4251,9 @@ impl<'a> Parser<'a> {
}
"'{" => {
self.bump();
if self.at_assign_pattern_repl() {
return self.parse_assign_pattern_repl(start);
}
let mut items = Vec::new();
if !self.cur().is_sym("}") {
loop {
@@ -5817,4 +6015,136 @@ mod tests {
assert!(parse_err("module m;\n enum logic [1:0] {A, B state;\nendmodule\n")
.contains("expected"));
}
/// Run `check` on the right-hand side of `src`'s first continuous
/// assignment. A closure rather than a getter: the parsed file owns the
/// expression and must outlive the borrow.
fn with_assign_rhs(src: &str, check: impl FnOnce(&Expr)) {
let f = parse_ok(src);
let ItemKind::ContAssign(a) = &module_of(&f).items[0].kind else {
panic!("expected an assign")
};
check(&a.assigns[0].rhs);
}
#[test]
fn a_cast_base_may_be_parenthesized_or_scoped() {
// corpus/common_cells/src/lzc.sv:67 and
// corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_lc_sender.sv:32.
with_assign_rhs("module m;\n assign a = (NumLevels)'(unsigned'(j));\nendmodule\n", |e| {
let ExprKind::Cast { ty, .. } = &e.kind else { panic!("expected a cast") };
assert!(
matches!(ty.kind, ExprKind::Paren { .. }),
"base is the parenthesized expression"
);
});
with_assign_rhs("module m;\n assign a = lc_ctrl_pkg::TxWidth'(x);\nendmodule\n", |e| {
let ExprKind::Cast { ty, .. } = &e.kind else { panic!("expected a cast") };
assert!(matches!(ty.kind, ExprKind::Scope { .. }), "base is the scoped name");
});
}
#[test]
fn a_cast_base_that_is_not_a_constant_primary_is_still_rejected() {
let msg = parse_err("module m;\n assign a = f(1)'(x);\nendmodule\n");
assert!(msg.contains("unsupported cast base expression"), "unexpected: {msg}");
}
#[test]
fn an_arrow_at_statement_position_is_still_an_event_trigger() {
let f =
parse_ok("module m;\n initial begin\n -> ev;\n x = a -> b;\n end\nendmodule\n");
let ItemKind::Initial(stmt) = &module_of(&f).items[0].kind else {
panic!("expected an initial")
};
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
assert!(matches!(stmts[0].kind, StmtKind::EventTrigger(_)), "`-> ev;` is a trigger");
let StmtKind::Assign { rhs, .. } = &stmts[1].kind else { panic!("expected an assignment") };
assert!(matches!(rhs.kind, ExprKind::Binary { .. }), "`a -> b` is an implication");
}
#[test]
fn the_implication_operators_are_right_associative_and_bind_loosest() {
// `a ? b : c -> d` is `(a ? b : c) -> d`; `a -> b -> c` is
// `a -> (b -> c)` (IEEE 1800 §11.3.2).
with_assign_rhs("module m;\n assign y = a ? b : c -> d;\nendmodule\n", |e| {
let ExprKind::Binary { lhs, op, .. } = &e.kind else {
panic!("expected an implication")
};
assert_eq!(op, "->");
assert!(matches!(lhs.kind, ExprKind::Ternary { .. }), "the `? :` is the left operand");
});
with_assign_rhs("module m;\n assign y = a -> b -> c;\nendmodule\n", |e| {
let ExprKind::Binary { rhs, .. } = &e.kind else { panic!("expected an implication") };
assert!(matches!(rhs.kind, ExprKind::Binary { .. }), "the chain nests to the right");
});
}
#[test]
fn only_a_brace_after_the_first_element_makes_an_assignment_pattern_a_replication() {
// corpus/opentitan/hw/ip/uart/rtl/uart.sv:17.
with_assign_rhs("module m;\n assign y = '{NumRegs{0}};\nendmodule\n", |e| {
assert!(matches!(e.kind, ExprKind::AssignPatternRepl { .. }));
});
for src in [
"module m;\n assign y = '{a: 0, b: 1};\nendmodule\n",
"module m;\n assign y = '{x, y};\nendmodule\n",
"module m;\n assign y = '{{a, b}};\nendmodule\n",
"module m;\n assign y = '{default: 0};\nendmodule\n",
] {
with_assign_rhs(src, |e| {
assert!(matches!(e.kind, ExprKind::AssignPattern(_)), "not a replication: {src:?}");
});
}
}
#[test]
fn a_streaming_concatenation_keeps_its_direction_and_optional_slice_size() {
// corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_sha2_pkg.sv:123.
with_assign_rhs("module m;\n assign y = {<<8{v}};\nendmodule\n", |e| {
let ExprKind::Stream { dir, slice, inner } = &e.kind else {
panic!("expected a stream")
};
assert_eq!(dir, "<<");
assert!(matches!(slice.as_deref().map(|s| &s.kind), Some(ExprKind::Number(_))));
assert_eq!(inner.len(), 1);
});
with_assign_rhs("module m;\n assign y = {>>{a, b}};\nendmodule\n", |e| {
let ExprKind::Stream { dir, slice, inner } = &e.kind else {
panic!("expected a stream")
};
assert_eq!(dir, ">>");
assert!(slice.is_none(), "no slice size was written");
assert_eq!(inner.len(), 2);
});
}
#[test]
fn a_drive_strength_is_only_read_where_a_strength_keyword_follows_the_paren() {
// corpus/ibex/vendor/lowrisc_ip/ip/prim_generic/rtl/prim_usb_diff_rx.sv:39.
let f = parse_ok("module m;\n assign (weak0, pull1) a = b;\n assign c = d;\nendmodule\n");
let items = &module_of(&f).items;
let ItemKind::ContAssign(a) = &items[0].kind else { panic!("expected an assign") };
let s = a.strength.as_ref().expect("the strength was parsed");
assert_eq!((s.first.as_str(), s.second.as_str()), ("weak0", "pull1"));
let ItemKind::ContAssign(b) = &items[1].kind else { panic!("expected an assign") };
assert!(b.strength.is_none());
}
#[test]
fn an_attribute_may_precede_a_named_port_connection() {
// corpus/common_cells/src/cdc_fifo_gray.sv:140.
let f =
parse_ok("module m;\n sub u (\n (* async *) .a(x),\n .b(y)\n );\nendmodule\n");
let ItemKind::Instantiation(inst) = &module_of(&f).items[0].kind else {
panic!("expected an instantiation")
};
let Connections::Named(conns) = &inst.instances[0].conns else {
panic!("expected named connections")
};
assert_eq!(conns[0].meta.attrs.len(), 1);
assert_eq!(conns[0].meta.attrs[0].text, "(* async *)");
assert_eq!(conns[0].name, "a");
assert!(conns[1].meta.attrs.is_empty());
}
}