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:
1 parent
d071957393
commit
c2ea1656e1
10 files changed
+1039
-30
No files matched your search
@@ -387,10 +387,17 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
|
||||
- Named function/task call arguments (`csr_wr(.ptr(p), .value(v))`,
|
||||
`.flag()`), `case (expr) inside` with `[lo:hi]` range labels, and bare
|
||||
event controls (`@ev;`, `@hier.name;`)
|
||||
- Expressions: the full operator precedence table, ternaries,
|
||||
concatenation/replication, slices (`+:`/`-:`), casts (`int'(x)`),
|
||||
assignment patterns (`'{...}`), `inside`, hierarchical and package-scoped
|
||||
names
|
||||
- Expressions: the full operator precedence table including the implication
|
||||
operators `->`/`<->`, ternaries, concatenation/replication, slices
|
||||
(`+:`/`-:`), streaming concatenations (`{<<8{v}}`, `{>>{a, b}}`, also as an
|
||||
assignment target), casts over any constant primary (`int'(x)`,
|
||||
`(NumLevels)'(x)`, `pkg::Width'(x)`), assignment patterns (`'{...}`,
|
||||
including the replication form `'{N{0}}`), `inside` (with a `{...}` set or
|
||||
a macro standing in for one), hierarchical and package-scoped names. See
|
||||
`docs/features/expressions-2/README.md`
|
||||
- Drive strengths on a continuous assignment
|
||||
(`assign (weak0, pull1) x = y;`), `const ref` task/function arguments, and
|
||||
`(* attribute *)` instances in front of a named port connection
|
||||
- Macro invocations (`` `NAME ``, `` `NAME(args) ``, with or without a
|
||||
trailing `;`) in expression position **and** wherever a module item or a
|
||||
statement can appear — module and package bodies, generate regions and
|
||||
@@ -490,8 +497,15 @@ corpus baseline this ordering comes from:
|
||||
`virtual` interface types in every type position unblocked 28 corpus files
|
||||
and moved the parse rate from 86.8% to 90.2%; the other 3 advanced to
|
||||
blockers in the `expressions` and `other` buckets. Still open in this item:
|
||||
streaming operators, specify blocks, `let`/`checker`, `program` and
|
||||
`interface class` — all rare in the corpus RTL
|
||||
specify blocks, `let`/`checker`, `program` and `interface class` — all rare
|
||||
in the corpus RTL
|
||||
9. ~~Expressions: casts with a non-simple base, streaming concatenations,
|
||||
`->`/`<->` implication, drive strengths, attributes on port connections,
|
||||
the `'{N{0}}` assignment-pattern replication, `inside` a macro, and
|
||||
`const ref` arguments~~ — **done**; see
|
||||
`docs/features/expressions-2/README.md`. Emptied the `expressions` bucket
|
||||
(21 files) plus one `other` file and moved the parse rate from 91.6% to
|
||||
94.1%
|
||||
|
||||
Like ruff, `vfmt` refuses to output anything for a file it cannot fully
|
||||
parse, so it can never corrupt code.
|
||||
|
||||
@@ -344,6 +344,17 @@ Adapt each:
|
||||
every type position are done; the 3 files left advanced to blockers in
|
||||
the `expressions` and `other` buckets. `dv-statements` (26 files) is
|
||||
now the top blocker.
|
||||
→ expressions-2 (`docs/features/expressions-2/README.md`) then took it
|
||||
from 751/820 (91.6%, the baseline after round 21) to **772/820
|
||||
(94.1%)** — 20 of the 21 `expressions` files plus the `dv_utils_pkg.sv`
|
||||
`other` file gained, 0 lost, passing set verified as a strict superset.
|
||||
Casts over any constant primary, streaming concatenations, `->`/`<->`
|
||||
implication, drive strengths on continuous assigns, attributes on named
|
||||
port connections, the `'{N{0}}` pattern replication, `inside` a macro
|
||||
and `const ref` arguments are done; the one file left
|
||||
(`compare_helper.sv`) advanced to a macro-items blocker
|
||||
(`` `MACRO expr`` in expression position). `dv-statements` (26 files)
|
||||
is still the top blocker.
|
||||
- [ ] **[R] Fuzzing.** ruff fuzzes its parser. `cargo-fuzz` targets:
|
||||
(a) parser must never panic on arbitrary bytes, (b) for inputs that
|
||||
parse, format must satisfy equivalence + convergence.
|
||||
|
||||
@@ -1571,6 +1571,9 @@ impl<'a> Fmt<'a> {
|
||||
|
||||
fn cont_assign(&self, a: &ContAssign) -> Doc {
|
||||
let mut docs = vec![text("assign ")];
|
||||
if let Some(s) = &a.strength {
|
||||
docs.push(text(format!("({}, {}) ", s.first, s.second)));
|
||||
}
|
||||
if let Some(delay) = &a.delay {
|
||||
docs.push(text("#"));
|
||||
docs.push(self.expr(delay));
|
||||
@@ -1751,7 +1754,11 @@ impl<'a> Fmt<'a> {
|
||||
/// parens — is one cell and never joins a group.
|
||||
fn connection_cells(&self, c: &Connection) -> Vec<Doc> {
|
||||
let plain = || vec![self.connection_plain(c)];
|
||||
if c.name.is_empty() || c.name == "*" {
|
||||
// An attributed connection is one cell: the attribute widens the row
|
||||
// by an amount no other row shares, so it never joins a group —
|
||||
// `list_breaks` already ends the group at it, as it does at a
|
||||
// compiler directive.
|
||||
if c.name.is_empty() || c.name == "*" || !c.meta.attrs.is_empty() {
|
||||
return plain();
|
||||
}
|
||||
let Some(e) = &c.expr else { return plain() };
|
||||
@@ -1768,6 +1775,24 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
|
||||
fn connection_plain(&self, c: &Connection) -> Doc {
|
||||
// `(* async *) .async_data_o (x)`: the attributes stay in front of
|
||||
// the connection, on its line (corpus
|
||||
// `common_cells/src/cdc_fifo_gray.sv:140`).
|
||||
if !c.meta.attrs.is_empty() {
|
||||
let mut docs = Vec::new();
|
||||
for attr in &c.meta.attrs {
|
||||
docs.push(self.raw_inline(attr));
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.connection_bare(c));
|
||||
return concat(docs);
|
||||
}
|
||||
self.connection_bare(c)
|
||||
}
|
||||
|
||||
/// A connection without its attributes: `.name(expr)`, `.name()`,
|
||||
/// `.name`, `.*`, or a positional value.
|
||||
fn connection_bare(&self, c: &Connection) -> Doc {
|
||||
if c.name == "*" {
|
||||
return text(".*");
|
||||
}
|
||||
@@ -2664,6 +2689,11 @@ impl<'a> Fmt<'a> {
|
||||
"+" | "-" => 9,
|
||||
"*" | "/" | "%" => 10,
|
||||
"**" => 11,
|
||||
// `->` and `<->` are the lowest-precedence binary operators
|
||||
// (IEEE 1800 §11.3.2). This table is only ever compared for
|
||||
// equality — it decides which neighbours flatten into one
|
||||
// chain — and no other operator reaches the fallback.
|
||||
"->" | "<->" => 0,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
@@ -2724,6 +2754,16 @@ impl<'a> Fmt<'a> {
|
||||
self.expr_list("{", inner, "}"),
|
||||
text("}"),
|
||||
]),
|
||||
// `{<<8{v}}` — written tight, like a replication.
|
||||
ExprKind::Stream { dir, slice, inner } => {
|
||||
let mut docs = vec![text("{"), text(dir.clone())];
|
||||
if let Some(s) = slice {
|
||||
docs.push(self.expr(s));
|
||||
}
|
||||
docs.push(self.expr_list("{", inner, "}"));
|
||||
docs.push(text("}"));
|
||||
concat(docs)
|
||||
}
|
||||
ExprKind::Paren { inner, before, after } => {
|
||||
if before.is_empty() && after.is_empty() {
|
||||
return self.parens(inner);
|
||||
@@ -2747,7 +2787,7 @@ impl<'a> Fmt<'a> {
|
||||
group(outer)
|
||||
}
|
||||
ExprKind::Cast { ty, expr } => {
|
||||
concat(vec![text(format!("{ty}'(")), self.expr(expr), text(")")])
|
||||
concat(vec![self.expr(ty), text("'("), self.expr(expr), text(")")])
|
||||
}
|
||||
ExprKind::AssignPattern(items) => {
|
||||
let items: Vec<ListItem> = items
|
||||
@@ -2764,10 +2804,20 @@ impl<'a> Fmt<'a> {
|
||||
.collect();
|
||||
self.delimited("'{", items, "}", false)
|
||||
}
|
||||
// `'{N{0}}` — written tight, like the `{N{0}}` it replicates.
|
||||
ExprKind::AssignPatternRepl { count, inner } => concat(vec![
|
||||
text("'{"),
|
||||
self.expr(count),
|
||||
self.expr_list("{", inner, "}"),
|
||||
text("}"),
|
||||
]),
|
||||
ExprKind::Postfix { expr, op } => concat(vec![self.expr(expr), text(op.clone())]),
|
||||
ExprKind::Inside { lhs, ranges } => {
|
||||
concat(vec![self.expr(lhs), text(" inside "), self.expr_list("{", ranges, "}")])
|
||||
}
|
||||
ExprKind::InsideMacro { lhs, set } => {
|
||||
concat(vec![self.expr(lhs), text(" inside "), text(set.clone())])
|
||||
}
|
||||
// A named call argument, printed the way a named connection is:
|
||||
// `.name(value)`, tight, with a break opportunity inside.
|
||||
ExprKind::NamedArg { name, value, close_comments, .. } => match &value.kind {
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
# casts with a parenthesized base
|
||||
module m;
|
||||
assign a = (NumLevels)'(unsigned'(j));
|
||||
assign b = (DepthW+3)'(1'b1);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign a = (NumLevels)'(unsigned'(j));
|
||||
assign b = (DepthW + 3)'(1'b1);
|
||||
endmodule
|
||||
====
|
||||
# casts with a package-scoped base
|
||||
module m;
|
||||
assign c = lc_ctrl_pkg::TxWidth'(lc_en_i);
|
||||
assign d = prim_mubi_pkg::mubi4_t'(de ? d : q);
|
||||
assign e = cfg.width'(x);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign c = lc_ctrl_pkg::TxWidth'(lc_en_i);
|
||||
assign d = prim_mubi_pkg::mubi4_t'(de ? d : q);
|
||||
assign e = cfg.width'(x);
|
||||
endmodule
|
||||
====
|
||||
# the simple cast bases still print tight
|
||||
module m;
|
||||
assign e = 4'(x);
|
||||
assign f = W'(x);
|
||||
assign g = signed'(x) + int'(y) + string'(z);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign e = 4'(x);
|
||||
assign f = W'(x);
|
||||
assign g = signed'(x) + int'(y) + string'(z);
|
||||
endmodule
|
||||
====
|
||||
# streaming concatenations
|
||||
module m;
|
||||
function automatic int f(input logic v);
|
||||
logic [31:0] a, b, x;
|
||||
a = {<<8{v}};
|
||||
b = { << LfsrIdxDw { col } };
|
||||
x = {>>{a, b}};
|
||||
x = {<<{x}};
|
||||
x = {<< byte {x}};
|
||||
endfunction
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
function automatic int f(input logic v);
|
||||
logic [31:0] a, b, x;
|
||||
a = {<<8{v}};
|
||||
b = {<<LfsrIdxDw{col}};
|
||||
x = {>>{a, b}};
|
||||
x = {<<{x}};
|
||||
x = {<<byte{x}};
|
||||
endfunction
|
||||
endmodule
|
||||
====
|
||||
# a streaming concatenation as an assignment target
|
||||
module m;
|
||||
initial begin
|
||||
{>>{a, b}} = x;
|
||||
{ << 8 { c } } <= y;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
{>>{a, b}} = x;
|
||||
{<<8{c}} <= y;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# the implication operators
|
||||
module m;
|
||||
assign y = (a -> b);
|
||||
assign z = a->b->c;
|
||||
assign w = a <-> b;
|
||||
assign v = a ? b : c -> d;
|
||||
assign u = p || q -> r && s;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign y = (a -> b);
|
||||
assign z = a -> b -> c;
|
||||
assign w = a <-> b;
|
||||
assign v = a ? b : c -> d;
|
||||
assign u = p || q -> r && s;
|
||||
endmodule
|
||||
====
|
||||
# `-> ev;` at statement position is still an event trigger
|
||||
module m;
|
||||
event ev;
|
||||
initial begin
|
||||
-> ev;
|
||||
x = `IS_CSR -> ex_is_checkable_csr;
|
||||
-> done;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
event ev;
|
||||
initial begin
|
||||
-> ev;
|
||||
x = `IS_CSR -> ex_is_checkable_csr;
|
||||
-> done;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a comment on an implication keeps the side it was written on
|
||||
module m;
|
||||
assign e = f -> // why
|
||||
g;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign e = f -> // why
|
||||
g;
|
||||
endmodule
|
||||
====
|
||||
# drive strengths on a continuous assignment
|
||||
module m;
|
||||
assign (weak0, pull1) a = b;
|
||||
assign (pull1,weak0) c = d;
|
||||
assign (supply0,supply1) e = f;
|
||||
assign (highz0, strong1) g = h;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign (weak0, pull1) a = b;
|
||||
assign (pull1, weak0) c = d;
|
||||
assign (supply0, supply1) e = f;
|
||||
assign (highz0, strong1) g = h;
|
||||
endmodule
|
||||
====
|
||||
# a drive strength may be followed by a delay, and neither is required
|
||||
module m;
|
||||
assign (weak0, weak1) #2 i = j;
|
||||
assign #1 k = l;
|
||||
assign {a, b} = c;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign (weak0, weak1) #2 i = j;
|
||||
assign #1 k = l;
|
||||
assign {a, b} = c;
|
||||
endmodule
|
||||
====
|
||||
# an attribute in front of a named port connection
|
||||
module m;
|
||||
sub u (
|
||||
.aaa ( x ),
|
||||
.b ( y ),
|
||||
(* async *) .c ( z )
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub u (
|
||||
.aaa (x),
|
||||
.b (y),
|
||||
(* async *) .c(z)
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# an attributed connection may come first, and ends the alignment group
|
||||
module m;
|
||||
sub u (
|
||||
(* async *) .a ( x ),
|
||||
.bbbbbb ( y ),
|
||||
.c ( z )
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub u (
|
||||
(* async *) .a(x),
|
||||
.bbbbbb (y),
|
||||
.c (z)
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# the replication form of an assignment pattern
|
||||
module m #(
|
||||
parameter sel_t V [NumRegs] = '{NumRegs{0}},
|
||||
parameter sel_t W [N] = '{uart_reg_pkg::NumRegs{0}},
|
||||
parameter sel_t R = '{(N+1){2}}
|
||||
) ();
|
||||
endmodule
|
||||
----
|
||||
module m #(
|
||||
parameter sel_t V [NumRegs] = '{NumRegs{0}},
|
||||
parameter sel_t W [N] = '{uart_reg_pkg::NumRegs{0}},
|
||||
parameter sel_t R = '{(N + 1){2}}
|
||||
) ();
|
||||
endmodule
|
||||
====
|
||||
# the keyed and positional pattern forms are unchanged
|
||||
module m #(
|
||||
parameter sel_t X = '{a: 0, b: 1},
|
||||
parameter sel_t Y = '{x, y},
|
||||
parameter sel_t Z = '{{a, b}},
|
||||
parameter sel_t Q = '{default: 0}
|
||||
) ();
|
||||
endmodule
|
||||
----
|
||||
module m #(
|
||||
parameter sel_t X = '{a: 0, b: 1},
|
||||
parameter sel_t Y = '{x, y},
|
||||
parameter sel_t Z = '{{a, b}},
|
||||
parameter sel_t Q = '{default: 0}
|
||||
) ();
|
||||
endmodule
|
||||
====
|
||||
# `inside` with a macro standing in for the set
|
||||
package p;
|
||||
function bit g(int x);
|
||||
return x inside `TX_IGNORED_PERIOD;
|
||||
endfunction
|
||||
function bit h(int x);
|
||||
return x inside `RANGE(1, 2);
|
||||
endfunction
|
||||
function bit i(int x);
|
||||
return x inside {[0:3], 7};
|
||||
endfunction
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
function bit g(int x);
|
||||
return x inside `TX_IGNORED_PERIOD;
|
||||
endfunction
|
||||
function bit h(int x);
|
||||
return x inside `RANGE(1, 2);
|
||||
endfunction
|
||||
function bit i(int x);
|
||||
return x inside {[0:3], 7};
|
||||
endfunction
|
||||
endpackage
|
||||
====
|
||||
# a `const ref` task/function argument
|
||||
package p;
|
||||
function automatic int max(const ref int int_q[$]);
|
||||
max = int_q[0];
|
||||
endfunction
|
||||
function automatic void f(ref int a, const ref int b, input int c);
|
||||
endfunction
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
function automatic int max(const ref int int_q [$]);
|
||||
max = int_q[0];
|
||||
endfunction
|
||||
function automatic void f(ref int a, const ref int b, input int c);
|
||||
endfunction
|
||||
endpackage
|
||||
====
|
||||
# every new shape is left alone inside a format fence
|
||||
module m;
|
||||
// verilog_format: off
|
||||
assign (weak0,pull1) a = {<<8{v}} ;
|
||||
assign b = '{N{0}} ;
|
||||
assign c = d ->e;
|
||||
// verilog_format: on
|
||||
assign e = f;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// verilog_format: off
|
||||
assign (weak0,pull1) a = {<<8{v}} ;
|
||||
assign b = '{N{0}} ;
|
||||
assign c = d ->e;
|
||||
// verilog_format: on
|
||||
assign e = f;
|
||||
endmodule
|
||||
====
|
||||
# comments written inside the new constructs stay inside them
|
||||
module m;
|
||||
assign h = {<<8{ /* c */ v}};
|
||||
assign i = /* pre */ (W)'(x);
|
||||
sub u (
|
||||
// leading
|
||||
(* async *) .a ( x )
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign h = {<<8{
|
||||
/* c */
|
||||
v
|
||||
}};
|
||||
assign i = /* pre */ (W)'(x);
|
||||
sub u (
|
||||
// leading
|
||||
(* async *) .a(x)
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# a cast and a stream at the line-length boundary
|
||||
module m;
|
||||
assign long_target_signal_name = (SomeWidthParam)'(some_function_call(aaa, bbb));
|
||||
assign other_target_name_here = {<<8{some_quite_long_source_signal_name_x}};
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign long_target_signal_name = (SomeWidthParam)'(some_function_call(aaa, bbb));
|
||||
assign other_target_name_here = {<<8{some_quite_long_source_signal_name_x}};
|
||||
endmodule
|
||||
====
|
||||
@@ -607,11 +607,23 @@ pub struct Declarator {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ContAssign {
|
||||
/// Drive strength: the `(weak0, pull1)` in
|
||||
/// `assign (weak0, pull1) x = y;` (IEEE 1800 §10.3.1), in source order.
|
||||
pub strength: Option<DriveStrength>,
|
||||
/// Delay expression: the `5` in `assign #5 x = y;`
|
||||
pub delay: Option<Expr>,
|
||||
pub assigns: Vec<AssignPair>,
|
||||
}
|
||||
|
||||
/// The `( strength0 , strength1 )` pair of a continuous assignment. The two
|
||||
/// strengths are stored in the order the source wrote them — the language
|
||||
/// allows either order and vfmt is not a legality checker.
|
||||
#[derive(Debug)]
|
||||
pub struct DriveStrength {
|
||||
pub first: String,
|
||||
pub second: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AssignPair {
|
||||
pub meta: Meta,
|
||||
@@ -1302,6 +1314,18 @@ pub enum ExprKind {
|
||||
/// comment inside a replication stays inside it.
|
||||
inner: Vec<ExprItem>,
|
||||
},
|
||||
/// A streaming concatenation, IEEE 1800 §11.4.14:
|
||||
/// `{<<8{v}}`, `{>>{a, b}}`, `{<< byte {x}}`. Legal as an lvalue too,
|
||||
/// which is why it is an ordinary primary expression.
|
||||
Stream {
|
||||
/// `<<` or `>>`.
|
||||
dir: String,
|
||||
/// The optional slice size: a constant expression or a type.
|
||||
slice: Option<Box<Expr>>,
|
||||
/// The stream expressions, carrying their comments the way a
|
||||
/// concatenation's elements do.
|
||||
inner: Vec<ExprItem>,
|
||||
},
|
||||
Paren {
|
||||
inner: Box<Expr>,
|
||||
/// Comments written just inside the `(`.
|
||||
@@ -1309,13 +1333,23 @@ pub enum ExprKind {
|
||||
/// Comments left over just before the `)`.
|
||||
after: Vec<Comment>,
|
||||
},
|
||||
/// `ty'(expr)` cast; `ty` kept as raw text.
|
||||
/// `ty'(expr)` cast. The casting type is an expression because it may be
|
||||
/// a name (`int`, `my_t`), a package-scoped name
|
||||
/// (`lc_ctrl_pkg::TxWidth'(x)`), a size (`4'(x)`) or a parenthesized
|
||||
/// constant expression (`(DepthW + 3)'(1'b1)`) — IEEE 1800 §6.24.1.
|
||||
Cast {
|
||||
ty: String,
|
||||
ty: Box<Expr>,
|
||||
expr: Box<Expr>,
|
||||
},
|
||||
/// `'{...}` assignment pattern.
|
||||
AssignPattern(Vec<PatternItem>),
|
||||
/// The replication form of an assignment pattern, IEEE 1800 §10.9.1:
|
||||
/// `'{NumRegs{0}}`. Distinct from [`ExprKind::Repl`], which is the
|
||||
/// concatenation form `{N{x}}`.
|
||||
AssignPatternRepl {
|
||||
count: Box<Expr>,
|
||||
inner: Vec<ExprItem>,
|
||||
},
|
||||
Postfix {
|
||||
expr: Box<Expr>,
|
||||
op: String,
|
||||
@@ -1324,6 +1358,14 @@ pub enum ExprKind {
|
||||
lhs: Box<Expr>,
|
||||
ranges: Vec<ExprItem>,
|
||||
},
|
||||
/// `x inside `MACRO` — the set is a macro invocation that expands to a
|
||||
/// `{...}` set, so it is kept verbatim (corpus
|
||||
/// `opentitan/hw/ip/uart/dv/env/uart_scoreboard.sv:155`).
|
||||
InsideMacro {
|
||||
lhs: Box<Expr>,
|
||||
/// The macro invocation token, exactly as written.
|
||||
set: String,
|
||||
},
|
||||
/// A named call argument: the `.ptr(ral.ovrd)` of
|
||||
/// `csr_wr(.ptr(ral.ovrd), .value(x))`. `value` is [`ExprKind::Empty`]
|
||||
/// for `.name()`, exactly as an empty connection is.
|
||||
|
||||
@@ -52,9 +52,9 @@ struct RawLexer<'a> {
|
||||
|
||||
/// Multi-character operators, longest first so greedy matching works.
|
||||
const OPERATORS: &[&str] = &[
|
||||
"<<<=", ">>>=", "===", "!==", "==?", "!=?", "<<<", ">>>", "<<=", ">>=", "**", "==", "!=", "<=",
|
||||
">=", "&&", "||", "<<", ">>", "->", "=>", "::", "+:", "-:", "+=", "-=", "*=", "/=", "%=", "&=",
|
||||
"|=", "^=", "++", "--", "~&", "~|", "~^", "^~", "##", "'{",
|
||||
"<<<=", ">>>=", "===", "!==", "==?", "!=?", "<<<", ">>>", "<<=", ">>=", "<->", "**", "==",
|
||||
"!=", "<=", ">=", "&&", "||", "<<", ">>", "->", "=>", "::", "+:", "-:", "+=", "-=", "*=", "/=",
|
||||
"%=", "&=", "|=", "^=", "++", "--", "~&", "~|", "~^", "^~", "##", "'{",
|
||||
];
|
||||
|
||||
const SINGLE_OPS: &[u8] = b"+-*/%&|^~!<>=?:;,.#@()[]{}'$";
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -813,8 +813,12 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) {
|
||||
match &e.kind {
|
||||
ExprKind::Unary { expr, .. }
|
||||
| ExprKind::Postfix { expr, .. }
|
||||
| ExprKind::Cast { expr, .. }
|
||||
| ExprKind::Paren { inner: expr, .. } => check_expr(src, expr, here),
|
||||
ExprKind::Cast { ty, expr } => {
|
||||
check_expr(src, ty, here);
|
||||
check_expr(src, expr, here);
|
||||
}
|
||||
ExprKind::InsideMacro { lhs, .. } => check_expr(src, lhs, here),
|
||||
ExprKind::NamedArg { name, name_span, value, .. } => {
|
||||
check_name(src, "named argument", name, *name_span, here);
|
||||
check_expr(src, value, here);
|
||||
@@ -853,13 +857,20 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) {
|
||||
check_expr(src, &i.expr, here);
|
||||
}
|
||||
}
|
||||
ExprKind::Repl { count, inner } => {
|
||||
ExprKind::Repl { count, inner } | ExprKind::AssignPatternRepl { count, inner } => {
|
||||
check_expr(src, count, here);
|
||||
for i in inner {
|
||||
assert_inside(src, "element", i.span, here);
|
||||
check_expr(src, &i.expr, here);
|
||||
}
|
||||
}
|
||||
ExprKind::Stream { slice, inner, .. } => {
|
||||
check_opt_expr(src, slice.as_deref(), here);
|
||||
for i in inner {
|
||||
assert_inside(src, "element", i.span, here);
|
||||
check_expr(src, &i.expr, here);
|
||||
}
|
||||
}
|
||||
ExprKind::AssignPattern(items) => {
|
||||
for i in items {
|
||||
assert_inside(src, "element", i.span, here);
|
||||
|
||||
@@ -1061,14 +1061,29 @@ impl<'a> Binder<'a> {
|
||||
self.bind_expr(&i.expr, scope);
|
||||
}
|
||||
}
|
||||
ExprKind::Repl { count, inner } => {
|
||||
ExprKind::Repl { count, inner } | ExprKind::AssignPatternRepl { count, inner } => {
|
||||
self.bind_expr(count, scope);
|
||||
for i in inner {
|
||||
self.bind_expr(&i.expr, scope);
|
||||
}
|
||||
}
|
||||
// The slice size of a streaming concatenation is a constant
|
||||
// expression or a type; both are ordinary uses.
|
||||
ExprKind::Stream { slice, inner, .. } => {
|
||||
if let Some(s) = slice {
|
||||
self.bind_expr(s, scope);
|
||||
}
|
||||
for i in inner {
|
||||
self.bind_expr(&i.expr, scope);
|
||||
}
|
||||
}
|
||||
// The set is a macro invocation this crate makes no claims about.
|
||||
ExprKind::InsideMacro { lhs, .. } => self.bind_expr(lhs, scope),
|
||||
ExprKind::Paren { inner, .. } => self.bind_expr(inner, scope),
|
||||
// The cast type is raw text with no span of its own.
|
||||
// Only the cast's operand is bound. The casting type names a
|
||||
// type — a keyword (`int'(x)`), a typedef or a parameter — and
|
||||
// resolving those is the type-name work this crate does not do
|
||||
// anywhere else either.
|
||||
ExprKind::Cast { expr, .. } => self.bind_expr(expr, scope),
|
||||
ExprKind::AssignPattern(items) => {
|
||||
for i in items {
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
# expressions-2
|
||||
|
||||
## Goal
|
||||
|
||||
Empty the corpus's `expressions` bucket — 21 files, every one of them blocked
|
||||
on a piece of expression grammar vfmt did not have — plus the one `other` file
|
||||
blocked on a `const ref` argument. Eight independent shapes, each taken from a
|
||||
real corpus file and cited below. All eight are **structural**: real AST nodes
|
||||
with a canonical layout, no new verbatim pass-through and no new normalization,
|
||||
so `verify.rs` is untouched.
|
||||
|
||||
| # | shape | corpus evidence |
|
||||
|---|---|---|
|
||||
| 1 | cast over a non-simple base: `(NumLevels)'(unsigned'(j))`, `(DepthW + 3)'(1'b1)`, `lc_ctrl_pkg::TxWidth'(x)`, `prim_mubi_pkg::mubi4_t'(de ? d : q)` | `common_cells/src/lzc.sv:67`, `.../prim_fifo_sync_assert_fpv.sv:33`, `.../prim_fifo_async.sv:230`, `.../prim_fifo_async_sram_adapter.sv:346`, `.../prim_lc_sender.sv:32`, `.../prim_lc_sync.sv:42`, `.../prim_subreg_arb.sv:63` |
|
||||
| 2 | streaming concatenation `{<<8{v}}`, `{<<LfsrIdxDw{col}}` | `.../prim_sha2_pkg.sv:123`, `.../prim_lfsr.sv:402` |
|
||||
| 3 | `->` / `<->` implication as a binary operator | `ibex/dv/formal/check/peek/compare_helper.sv:42`, `.../follower.sv:168`, `ibex/dv/formal/check/top.sv:432` |
|
||||
| 4 | drive strength on a continuous assign: `assign (weak0, pull1) x = ...;` | `.../prim_usb_diff_rx.sv:39`, `.../prim_pad_wrapper.sv:71`, `.../common_ifs/pins_if.sv:97` |
|
||||
| 5 | `(* attribute *)` in front of a named port connection | `common_cells/src/cdc_fifo_gray.sv:140`, `.../cdc_fifo_gray_clearable.sv:182`, `.../cdc_reset_ctrlr.sv:158` |
|
||||
| 6 | assignment-pattern replication `'{NumRegs{0}}`, `'{uart_reg_pkg::NumRegs{0}}` | `opentitan/hw/ip/uart/rtl/uart.sv:17`, `.../uart_reg_top.sv:14` |
|
||||
| 7 | `x inside `MACRO` — the set is a macro invocation | `opentitan/hw/ip/uart/dv/env/uart_scoreboard.sv:155` |
|
||||
| 8 | `const ref` task/function argument | `ibex/vendor/lowrisc_ip/dv/sv/dv_utils/dv_utils_pkg.sv:104` |
|
||||
|
||||
Beyond the cited shapes, the same grammar rules were taken where they cost
|
||||
nothing: `{>>{a, b}}` and `{<<{x}}` (no slice size), `{<< byte {x}}` (a type
|
||||
slice size), a streaming concatenation as an assignment *target*, `<->`,
|
||||
`(highz0, strong1)` and the other strength keywords in either order, a strength
|
||||
followed by a delay, and a `.name` / `.*` connection carrying an attribute.
|
||||
|
||||
## Layout
|
||||
|
||||
Everything in this round is written tight, the way the constructs it extends
|
||||
already are:
|
||||
|
||||
```systemverilog
|
||||
assign a = (NumLevels)'(unsigned'(j)); // cast: no space anywhere
|
||||
assign b = {<<8{v}}; // stream: like a replication
|
||||
assign c = a -> b; // implication: like any binary op
|
||||
assign (weak0, pull1) d = e; // strength: one space after `)`
|
||||
parameter sel_t V [N] = '{NumRegs{0}}; // pattern replication
|
||||
return x inside `TX_IGNORED_PERIOD; // macro set, verbatim
|
||||
function automatic int max(const ref int q [$]);
|
||||
sub u (
|
||||
(* async *) .a(x), // attribute, then the connection
|
||||
.bbbbbb (y),
|
||||
.c (z)
|
||||
);
|
||||
```
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **`->` after an operand is always the implication operator.** The event
|
||||
trigger `-> ev;` is taken by `parse_stmt_kind` before any expression is
|
||||
parsed, so the two never compete. The non-blocking trigger `->>` still lexes
|
||||
as `->` `>` and is still unsupported, exactly as before.
|
||||
- **`->`/`<->` bind looser than `? :` and associate right** (IEEE 1800
|
||||
§11.3.2), which is why they sit in their own `parse_implication` layer above
|
||||
`parse_ternary` rather than in the precedence-climbing table — everything in
|
||||
that table binds tighter than `? :`.
|
||||
- **A `(` right after `assign` opens a drive strength only when a strength
|
||||
keyword follows it.** Any other `(` is left to the left-hand side, so no
|
||||
existing assignment changes meaning.
|
||||
- **The casting type is a `constant_primary`** (IEEE 1800 §6.24.1). Accepted
|
||||
bases: a name, a `pkg::name` or `a.b` name, a number, and a parenthesized
|
||||
expression. Anything else (`f(1)'(x)`, `a[0]'(x)`) still gets the old
|
||||
`unsupported cast base expression` error — no corpus file needs it and
|
||||
guessing is how a formatter starts inventing grammar.
|
||||
- **`'{` opens the replication form when the first delimiter reached at
|
||||
bracket depth zero is a `{` that is not the very first token.** `'{a: 0}`
|
||||
(keyed), `'{x, y}` (positional), `'{default: 0}` and `'{{a, b}}` (one
|
||||
element, a concatenation) are all still the ordinary pattern. The decision is
|
||||
a token lookahead rather than a parse-then-look, because parsing the first
|
||||
element harvests its leading comments and there is nowhere to put them back.
|
||||
- **The `with [range]` form of a stream expression is not supported.** No
|
||||
corpus file writes it; a file that does keeps its old
|
||||
`expected expression` error rather than getting a half-modelled node.
|
||||
- **A `` `MACRO`` on the right of `inside` is passed through verbatim.** vfmt
|
||||
does not expand macros, so it cannot know the set the macro produces; the
|
||||
invocation is one token and is printed back as that token.
|
||||
- **A comment written immediately before a replication count is not kept.**
|
||||
`'{ /* c */ N{0}}` (and, unchanged from before this round,
|
||||
`{ /* c */ N{0}}`) makes the safety net reject the output and vfmt reports a
|
||||
clean error — never a dropped comment in a written file. The count has no
|
||||
comment slot in either AST node; adding one is the same fix for both and is
|
||||
left for whoever needs it.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed**
|
||||
|
||||
- `vlog_parser::lexer` — `TokenKind::Attribute` for `(* ... *)`, and
|
||||
`Token::is_macro()` for the `` `MACRO`` on the right of `inside`.
|
||||
- `Meta::attrs`, which already existed for items and statements, is what a
|
||||
connection's attributes are stored in; `Fmt::list_breaks` already treats a
|
||||
non-empty `attrs` as an alignment-group boundary, so no alignment code
|
||||
needed changing.
|
||||
|
||||
**Promised / changed**
|
||||
|
||||
- `ast::ExprKind::Cast::ty` changed from `String` to `Box<Expr>`. Consumers
|
||||
updated: `vlog_formatter::format` (prints the base as an expression),
|
||||
`vlog_semantic::bind` (unchanged behaviour — the casting type names a type
|
||||
and is still not bound), `vlog_parser/tests/spans.rs` (walks it).
|
||||
- Three new `ExprKind` variants: `Stream`, `AssignPatternRepl`, `InsideMacro`.
|
||||
Minimal arms added in `vlog_semantic/src/bind.rs` and
|
||||
`vlog_parser/tests/spans.rs`. `vlog_linter` matches no `ExprKind` and needed
|
||||
nothing.
|
||||
- New `ast::DriveStrength` and `ContAssign::strength`.
|
||||
- `lexer.rs`: `<->` added to `OPERATORS`. It is strictly widening — `<->` was
|
||||
previously two tokens that no rule accepted — and `a<-b` / `a<--b` still lex
|
||||
as `<` `-` / `<` `--`.
|
||||
- `verify.rs`: **untouched.**
|
||||
|
||||
**Requests to other features**
|
||||
|
||||
- `corpus/ibex/dv/formal/check/peek/compare_helper.sv` advanced past its
|
||||
`->` blocker and now fails at line 69, `assign csrs_match = `X_EACH_CSR 1;`
|
||||
— a macro invocation followed by an operand in expression position. The
|
||||
score script now classifies it as **macro-items**, not `expressions`. Left
|
||||
for that feature: reading `` `MACRO expr`` as anything other than two
|
||||
adjacent primaries needs the macro's definition, which vfmt does not have.
|
||||
- `corpus/picorv32/scripts/smtbmc/mulcmp.v` (`other`) is a trailing comma in
|
||||
a connection list — invalid Verilog. Left alone, as briefed.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Baseline score saved and diffed against the final run (no file that
|
||||
passed before fails now).
|
||||
- [x] 1. Casts with a parenthesized / scoped / member base.
|
||||
- [x] 2. Streaming concatenations, including as an assignment target and with
|
||||
a type slice size.
|
||||
- [x] 3. `->` / `<->` implication, with the event trigger kept intact.
|
||||
- [x] 4. Drive strengths on continuous assignments.
|
||||
- [x] 5. `(* attribute *)` before a named port connection, alignment groups
|
||||
broken at it.
|
||||
- [x] 6. `'{N{0}}` assignment-pattern replication.
|
||||
- [x] 7. `inside` a macro invocation.
|
||||
- [x] 8. `const ref` task/function arguments.
|
||||
- [x] Cases in `crates/vlog_formatter/tests/cases/expressions_2.cases`: one
|
||||
per corpus shape, plus the fenced, commented and line-length-boundary
|
||||
edges and the negative forms of every ambiguity.
|
||||
- [x] Parser unit tests for the ambiguities: `-> ev;` stays a trigger,
|
||||
`'{a: 0}` stays a keyed pattern, an unsupported cast base still errors,
|
||||
a `(` after `assign` is only a strength when a strength keyword follows.
|
||||
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test` clean.
|
||||
- [x] README "Supported syntax" and roadmap item 9 updated; TODO.md item
|
||||
checked.
|
||||
- [ ] Not taken: `wire (pull1, weak0) w = 1;` — a drive strength on a *net
|
||||
declaration*. Same grammar, different item; no corpus file needs it, so
|
||||
it is left rather than written on spec.
|
||||
- [ ] Not taken: `{<<{a with [1:2]}}`. See Assumptions.
|
||||
- [ ] Not taken: a comment slot for a replication count. See Assumptions.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-21 — dev**
|
||||
|
||||
Baseline, before any change:
|
||||
|
||||
```
|
||||
{"passing":751,"total":820,"pct":91.6,"failures_by_category":{"dv-statements":26,"expressions":21,"directive-split":14,"invalid-or-fragment":3,"lex-macro-number":2,"other":2,"not-verilog":1}}
|
||||
```
|
||||
|
||||
After:
|
||||
|
||||
```
|
||||
{"passing":772,"total":820,"pct":94.1,"failures_by_category":{"dv-statements":26,"directive-split":14,"invalid-or-fragment":3,"lex-macro-number":2,"macro-items":1,"not-verilog":1,"other":1}}
|
||||
```
|
||||
|
||||
+21 files, and the pass set is a strict superset of the baseline's (checked
|
||||
with `comm` over both TSVs — zero regressions). All 20 remaining
|
||||
`expressions` files and the `dv_utils_pkg.sv` `other` file pass; the 21st
|
||||
`expressions` file, `compare_helper.sv`, advanced to a macro-items blocker and
|
||||
is now classified there (see Handshakes).
|
||||
|
||||
Decisions worth recording:
|
||||
|
||||
- **`Cast::ty` became an expression.** The alternative was to keep it a
|
||||
`String` and slice the source for the base, but then `(DepthW+3)'(1)` would
|
||||
print its base unformatted while everything around it was normalized. As an
|
||||
expression the base goes through `Fmt::expr` like any other, and
|
||||
`(DepthW+3)'(1'b1)` comes out `(DepthW + 3)'(1'b1)`.
|
||||
- **`parse_implication` gates only its recursion, not its entry.** The first
|
||||
cut wrapped the whole function in `enter()`/`leave()`, which put one nesting
|
||||
level on *every* expression in the language and halved the depth limit — the
|
||||
`deep_nesting` tests caught it immediately. Now only the right-associative
|
||||
`a -> b -> c` chain costs budget, which is the only part that recurses.
|
||||
- **The `'{N{...}}` decision is a lookahead, not a parse-and-look.** Parsing
|
||||
the first element first would have been shorter, but `parse_expr_item`
|
||||
harvests the element's leading comments into a `Meta` that the replication
|
||||
branch has nowhere to store — dropping them breaks a hard invariant, so the
|
||||
branch is chosen before any token is consumed.
|
||||
- **An attributed connection never joins an alignment group.**
|
||||
`Fmt::list_breaks` already ends a group at an element with attributes, and
|
||||
`connection_cells` now returns a single cell for one, so it cannot be
|
||||
measured into a neighbour's column either. The result is stable across
|
||||
passes, which the idempotency check in the case suite pins.
|
||||
- **The cast base is still not name-bound** in `vlog_semantic`. It now *has* a
|
||||
span, so binding it would have been one line, but `int'(x)` would then look
|
||||
up `int` as a lexical name and the linter would start reporting it. Type-name
|
||||
resolution is not something that crate does anywhere else; left alone
|
||||
deliberately, with the reason in the code comment.
|
||||
|
||||
Files changed:
|
||||
|
||||
- `crates/vlog_parser/src/ast.rs` — `Cast::ty` retyped; `Stream`,
|
||||
`AssignPatternRepl`, `InsideMacro` variants; `DriveStrength` and
|
||||
`ContAssign::strength`.
|
||||
- `crates/vlog_parser/src/lexer.rs` — `<->` in `OPERATORS`.
|
||||
- `crates/vlog_parser/src/parser.rs` — widened cast bases;
|
||||
`parse_stream_concat`; `parse_implication`; `parse_opt_drive_strength` and
|
||||
`is_drive_strength`/`DRIVE_STRENGTHS`; `at_assign_pattern_repl` /
|
||||
`parse_assign_pattern_repl`; the `` `MACRO`` arm of `inside`; `const ref` in
|
||||
`parse_tf_ports`; attributes in `parse_connection` and the
|
||||
`at_named_connection` peek; eight new unit tests.
|
||||
- `crates/vlog_formatter/src/format.rs` — printers for the four new/changed
|
||||
expression kinds, the drive strength, and a connection's attributes;
|
||||
`binary_prec` entry for `->`/`<->`; `connection_plain` split into itself and
|
||||
`connection_bare`.
|
||||
- `crates/vlog_semantic/src/bind.rs` — arms for the new variants.
|
||||
- `crates/vlog_parser/tests/spans.rs` — arms for the new variants.
|
||||
- `crates/vlog_formatter/tests/cases/expressions_2.cases` — new, 19 cases.
|
||||
- `README.md`, `TODO.md`.
|
||||
|
||||
## QA log
|
||||
|
||||
## Review
|
||||
Reference in new issue
Block a user