Add types-decls: inline aggregates, typedef'd types with packed dims

Anonymous enum/struct/union declarations, struct packed as a parameter type default, user_t [N:0] x; at item and statement position, typedef enum with a typedef'd base, nested anonymous structs, localparam type as a body item, multi-declaration for-loop inits.

Coverage loop round 1, cluster 6: 740 -> 751 / 820 (90.2% -> 91.6%).
Feature README: docs/features/types-decls/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-21 00:24:04 -07:00
1 parent 2a63faf9a2
commit d071957393
7 files changed
+1001 -200

No files matched your search

+17 -3
View File
@@ -341,7 +341,15 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
- `generate` regions and module-level `if`/`for`/`case` - `generate` regions and module-level `if`/`for`/`case`
- Functions and tasks (ANSI and old-style port declarations) - Functions and tasks (ANSI and old-style port declarations)
- `typedef` (aliases, `enum`, packed `struct`/`union`, `typedef class` - `typedef` (aliases, `enum`, packed `struct`/`union`, `typedef class`
forward declarations) forward declarations), including an `enum` whose base type is a typedef'd
name and a struct member whose own type is an inline aggregate
- Anonymous `enum`/`struct`/`union` used as a type in place, wherever a type
stands: `enum logic [1:0] {IDLE, STOP} state, state_next;`, `struct packed
{ ... } s;`, and as the default of a `type` parameter. `parameter type` /
`localparam type` also stand as body items, not only in the `#( ... )`
list. A typedef'd type may carry packed dimensions before the declarator
(`payload_t [NumOut-1:0][NumInp-1:0] out_data;`). See
`docs/features/types-decls/README.md`
- Classes: `class`/`virtual class` … `endclass[: label]`, `#( ... )` class - Classes: `class`/`virtual class` … `endclass[: label]`, `#( ... )` class
parameters, `extends Base[#( ... )]`, `implements`, and class-scope members — parameters, `extends Base[#( ... )]`, `implements`, and class-scope members —
properties with `rand`/`randc`/`local`/`protected`/`static`/`const`, virtual properties with `rand`/`randc`/`local`/`protected`/`static`/`const`, virtual
@@ -439,8 +447,14 @@ corpus baseline this ordering comes from:
`inside`-blocked files format; 28 of the 41 `$`-blocked and 17 of the 21 `inside`-blocked files format; 28 of the 41 `$`-blocked and 17 of the 21
`.`-blocked do too, the rest advancing to named next blockers `.`-blocked do too, the rest advancing to named next blockers
(`interface` at 25 files is now the top one — item 8 below) (`interface` at 25 files is now the top one — item 8 below)
5. Declarations with identifier (typedef'd) types in some positions 5. ~~Declarations with identifier (typedef'd) types in some positions
(`my_t [N-1:0] x;`) (`my_t [N-1:0] x;`)~~ — **done**; see
`docs/features/types-decls/README.md`. With the rest of the `types-decls`
bucket (anonymous `enum`/`struct` as a type, `struct packed` as a
`parameter type` default, a typedef'd enum base type, nested anonymous
structs, `localparam type` as a body item, and a `for` init declaring
several variables) it unblocked all 11 files of the bucket and moved the
parse rate from 90.2% to 91.6%
5b. ~~Macro invocation with a space before its argument list 5b. ~~Macro invocation with a space before its argument list
(`` `uvm_field_int (a, b) ``), a bare macro item followed by a declaration (`` `uvm_field_int (a, b) ``), a bare macro item followed by a declaration
on the next line, `` `error``/`` `warning`` directives, and elaboration on the next line, `` `error``/`` `warning`` directives, and elaboration
+93 -59
View File
@@ -1215,7 +1215,7 @@ impl<'a> Fmt<'a> {
// `uvm_analysis_port #(bit [31:0]) port;` — spaced before the `#(`, // `uvm_analysis_port #(bit [31:0]) port;` — spaced before the `#(`,
// like an instantiation's overrides and unlike the tight `#(` of a // like an instantiation's overrides and unlike the tight `#(` of a
// parameterized name in expression position. // parameterized name in expression position.
if let Some(params) = &ty.params { if let Some(params) = ty.params() {
if need_space { if need_space {
docs.push(text(" ")); docs.push(text(" "));
} }
@@ -1236,6 +1236,25 @@ impl<'a> Fmt<'a> {
for d in &ty.packed { for d in &ty.packed {
docs.push(self.dim(d)); docs.push(self.dim(d));
} }
need_space = true;
}
// An anonymous aggregate is the type itself, so it never shares the
// line with a name — but it can follow a `virtual` prefix, and the
// `need_space` bookkeeping above is what puts the space in.
match ty.inline() {
Some(TypeExtra::Enum(e)) => {
if need_space {
docs.push(text(" "));
}
docs.push(self.enum_type(e));
}
Some(TypeExtra::Struct(s)) => {
if need_space {
docs.push(text(" "));
}
docs.push(self.struct_type(s));
}
_ => {}
} }
Some(concat(docs)) Some(concat(docs))
} }
@@ -1380,6 +1399,9 @@ impl<'a> Fmt<'a> {
} }
} }
let mut docs = vec![text(d.kw.clone()), text(" ")]; let mut docs = vec![text(d.kw.clone()), text(" ")];
if d.is_type {
docs.push(text("type "));
}
if let Some(t) = self.data_type(&d.ty) { if let Some(t) = self.data_type(&d.ty) {
docs.push(t); docs.push(t);
docs.push(text(" ")); docs.push(text(" "));
@@ -1392,6 +1414,9 @@ impl<'a> Fmt<'a> {
/// columns: the keyword and type, the name, and the `= value`. /// columns: the keyword and type, the name, and the `= value`.
fn param_decl_cells(&self, d: &ParamDecl, decl: &Declarator, init: &Expr) -> Vec<Doc> { fn param_decl_cells(&self, d: &ParamDecl, decl: &Declarator, init: &Expr) -> Vec<Doc> {
let mut prefix = vec![text(d.kw.clone())]; let mut prefix = vec![text(d.kw.clone())];
if d.is_type {
prefix.push(text(" type"));
}
if let Some(t) = self.data_type(&d.ty) { if let Some(t) = self.data_type(&d.ty) {
prefix.push(text(" ")); prefix.push(text(" "));
prefix.push(t); prefix.push(t);
@@ -1454,70 +1479,79 @@ impl<'a> Fmt<'a> {
concat(docs) concat(docs)
} }
TypedefKind::Enum(e) => { TypedefKind::Enum(e) => {
let mut docs = vec![text("typedef enum")]; concat(vec![text("typedef "), self.enum_type(e), text(format!(" {};", t.name))])
if let Some(base) = &e.base {
if let Some(d) = self.data_type(base) {
docs.push(text(" "));
docs.push(d);
}
}
docs.push(text(" "));
let items: Vec<ListItem> = e
.members
.iter()
.map(|m| {
let mut d = vec![text(m.name.clone())];
if let Some(v) = &m.value {
d.push(text(" = "));
d.push(self.expr(v));
}
ListItem::from_meta(&m.meta, concat(d)).with_comma(m.comma)
})
.collect();
let items = self.list_entries(items, &e.directives);
// `e.dangling` — comments written before the closing `}` —
// is printed inside the braces; the enum has no other place
// to put it, and dropping it loses a comment.
let broken = !e.directives.is_empty();
docs.push(self.delimited_dangling("{", items, &e.dangling, "}", broken));
docs.push(text(format!(" {};", t.name)));
concat(docs)
} }
TypedefKind::Struct(s) => { TypedefKind::Struct(s) => {
let mut header = format!("typedef {}", s.kw); concat(vec![text("typedef "), self.struct_type(s), text(format!(" {};", t.name))])
if s.packed {
header.push_str(" packed");
}
if let Some(sig) = &s.signing {
header.push(' ');
header.push_str(sig);
}
header.push_str(" {");
let mut inner = Vec::new();
for m in &s.members {
inner.push(Doc::HardLine);
inner.extend(self.leading(&m.meta));
let mut d = Vec::new();
if let Some(ty) = self.data_type(&m.ty) {
d.push(ty);
d.push(text(" "));
}
d.push(self.declarators(&m.declarators));
d.push(text(";"));
inner.push(concat(d));
inner.extend(self.trailing(&m.meta));
}
inner.extend(self.dangling(&s.dangling));
concat(vec![
text(header),
indent(inner),
Doc::HardLine,
text(format!("}} {};", t.name)),
])
} }
} }
} }
/// `enum [base] { A, B }` — one line if it fits, else one member per line.
/// Shared by `typedef enum ...` and by an anonymous enum standing where a
/// type name would (`enum logic [1:0] {IDLE, STOP} state;`).
fn enum_type(&self, e: &EnumType) -> Doc {
let mut docs = vec![text("enum")];
if let Some(base) = &e.base {
if let Some(d) = self.data_type(base) {
docs.push(text(" "));
docs.push(d);
}
}
docs.push(text(" "));
let items: Vec<ListItem> = e
.members
.iter()
.map(|m| {
let mut d = vec![text(m.name.clone())];
if let Some(v) = &m.value {
d.push(text(" = "));
d.push(self.expr(v));
}
ListItem::from_meta(&m.meta, concat(d)).with_comma(m.comma)
})
.collect();
let items = self.list_entries(items, &e.directives);
// `e.dangling` — comments written before the closing `}` — is printed
// inside the braces; the enum has no other place to put it, and
// dropping it loses a comment.
let broken = !e.directives.is_empty();
docs.push(self.delimited_dangling("{", items, &e.dangling, "}", broken));
concat(docs)
}
/// `struct|union [packed] [signing] { ... }`, always one member per line.
/// Shared by `typedef struct ...`, an anonymous struct standing where a
/// type name would, and a struct member whose own type is an inline
/// struct — the recursion is what indents a nested body one more level.
fn struct_type(&self, s: &StructType) -> Doc {
let mut header = s.kw.clone();
if s.packed {
header.push_str(" packed");
}
if let Some(sig) = &s.signing {
header.push(' ');
header.push_str(sig);
}
header.push_str(" {");
let mut inner = Vec::new();
for m in &s.members {
inner.push(Doc::HardLine);
inner.extend(self.leading(&m.meta));
let mut d = Vec::new();
if let Some(ty) = self.data_type(&m.ty) {
d.push(ty);
d.push(text(" "));
}
d.push(self.declarators(&m.declarators));
d.push(text(";"));
inner.push(concat(d));
inner.extend(self.trailing(&m.meta));
}
inner.extend(self.dangling(&s.dangling));
concat(vec![text(header), indent(inner), Doc::HardLine, text("}")])
}
// ------------------------------------------------------------------ // ------------------------------------------------------------------
// Module items // Module items
// ------------------------------------------------------------------ // ------------------------------------------------------------------
@@ -0,0 +1,347 @@
# anonymous enum as a variable declaration (clock_divider.sv:59)
module m;
enum logic [1:0] {IDLE, STOP, WAIT, RELEASE} state, state_next;
endmodule
----
module m;
enum logic [1:0] {IDLE, STOP, WAIT, RELEASE} state, state_next;
endmodule
====
# anonymous enum with no base type
module m;
enum {A, B} x;
endmodule
----
module m;
enum {A, B} x;
endmodule
====
# anonymous enum whose member list does not fit breaks one per line
module m;
enum logic [3:0] {AAAAAAAAAAAAAAAA, BBBBBBBBBBBBBBBB, CCCCCCCCCCCCCCCC, DDDDDDDDDDDDDDDD, EEEE} big;
endmodule
----
module m;
enum logic [3:0] {
AAAAAAAAAAAAAAAA,
BBBBBBBBBBBBBBBB,
CCCCCCCCCCCCCCCC,
DDDDDDDDDDDDDDDD,
EEEE
} big;
endmodule
====
# anonymous enum with member values and comments
module m;
enum logic [1:0] {
// the idle state
IDLE = 2'b00, // nothing to do
RUN = 2'b01
} state;
endmodule
----
module m;
enum logic [1:0] {
// the idle state
IDLE = 2'b00, // nothing to do
RUN = 2'b01
} state;
endmodule
====
# anonymous packed struct and union declarations
module m;
struct packed { logic parity; logic [7:0] data; } s;
union packed { logic [7:0] a; logic [7:0] b; } u;
endmodule
----
module m;
struct packed {
logic parity;
logic [7:0] data;
} s;
union packed {
logic [7:0] a;
logic [7:0] b;
} u;
endmodule
====
# an anonymous aggregate inside a format-off fence keeps its bytes
module m;
// verilog_format: off
enum logic [1:0] { A , B } fenced ;
// verilog_format: on
enum logic [1:0] {A, B} formatted;
endmodule
----
module m;
// verilog_format: off
enum logic [1:0] { A , B } fenced ;
// verilog_format: on
enum logic [1:0] {A, B} formatted;
endmodule
====
# struct packed as a `parameter type` default (ecc_encode.sv:29)
module ecc_encode #(
parameter int unsigned DataWidth = 64,
parameter type data_t = logic [DataWidth-1:0],
parameter type encoded_data_t = struct packed {
logic parity;
code_word_t code_word;
}
) ();
endmodule
----
module ecc_encode #(
parameter int unsigned DataWidth = 64,
parameter type data_t = logic [DataWidth-1:0],
parameter type encoded_data_t = struct packed {
logic parity;
code_word_t code_word;
}
) ();
endmodule
====
# enum as a `parameter type` default, with comments in the body
module m #(
parameter type mode_t = enum logic [1:0] {
// the two modes
FAST,
SLOW
}
) ();
endmodule
----
module m #(
parameter type mode_t = enum logic [1:0] {
// the two modes
FAST,
SLOW
}
) ();
endmodule
====
# a typedef'd type with packed dimensions before the declarator (stream_xbar.sv:98)
module m;
payload_t [NumOut-1:0][NumInp-1:0] out_data;
omega_data_t [NumLevels-1:0][NumRouters-1:0][Radix-1:0] inp_router_data;
pkg::word_t [3:0] scoped;
endmodule
----
module m;
payload_t [NumOut-1:0][NumInp-1:0] out_data;
omega_data_t [NumLevels-1:0][NumRouters-1:0][Radix-1:0] inp_router_data;
pkg::word_t [3:0] scoped;
endmodule
====
# a typedef'd type with packed dimensions as a function local and a class property
module m;
function automatic void f();
my_t [3:0] slice;
my_t scalar;
endfunction
endmodule
class c;
my_t [3:0] prop;
endclass
----
module m;
function automatic void f();
my_t [3:0] slice;
my_t scalar;
endfunction
endmodule
class c;
my_t [3:0] prop;
endclass
====
# an indexed assignment in statement position is still an assignment
module m;
always_comb begin
x[i] = 1;
x[i][j] = 2;
y[a:b] = 3;
pkg::z[i] = 4;
end
endmodule
----
module m;
always_comb begin
x[i] = 1;
x[i][j] = 2;
y[a:b] = 3;
pkg::z[i] = 4;
end
endmodule
====
# a typedef'd enum base type (prim_count_pkg.sv:10)
package p;
typedef logic [3:0] action_mask_t;
typedef enum action_mask_t {Clr = 4'h1,
Set = 4'h2,
Incr = 4'h4,
Decr = 4'h8} action_e;
endpackage
----
package p;
typedef logic [3:0] action_mask_t;
typedef enum action_mask_t {Clr = 4'h1, Set = 4'h2, Incr = 4'h4, Decr = 4'h8} action_e;
endpackage
====
# a nested anonymous struct inside a typedef struct (uart_reg_pkg.sv:30)
package p;
typedef struct packed {
struct packed {
logic q;
} tx_empty;
union packed { logic [1:0] a; logic [1:0] b; } sel;
enum logic [1:0] {P, Q} mode;
logic [7:0] plain;
} uart_reg2hw_t;
endpackage
----
package p;
typedef struct packed {
struct packed {
logic q;
} tx_empty;
union packed {
logic [1:0] a;
logic [1:0] b;
} sel;
enum logic [1:0] {P, Q} mode;
logic [7:0] plain;
} uart_reg2hw_t;
endpackage
====
# `localparam type` at module scope (lossy_valid_to_stream_tb.sv:26)
module m;
localparam type payload_t = logic [$clog2(NumReq)-1:0];
parameter type word_t = logic [31:0];
localparam type alias_t = other_pkg::thing_t;
endmodule
----
module m;
localparam type payload_t = logic [$clog2(NumReq)-1:0];
parameter type word_t = logic [31:0];
localparam type alias_t = other_pkg::thing_t;
endmodule
====
# aligned `localparam type` declarations keep their columns
module m;
localparam type short_t = logic [7:0];
localparam type longer_t = logic [31:0];
endmodule
----
module m;
localparam type short_t = logic [7:0];
localparam type longer_t = logic [31:0];
endmodule
====
# `localparam type` whose default is an anonymous struct
module m;
localparam type hdr_t = struct packed {
logic [7:0] tag;
logic valid;
};
endmodule
----
module m;
localparam type hdr_t = struct packed {
logic [7:0] tag;
logic valid;
};
endmodule
====
# a for loop declaring several variables in its init (prim_sparse_fsm_flop.sv:48)
module m;
function automatic logic f(StateEnumT sig);
logic is_defined = 1'b0;
for (int i = 0, StateEnumT t = t.first(); i < t.num(); i += 1, t = t.next()) begin
is_defined |= (sig === t);
end
return ~is_defined;
endfunction
endmodule
----
module m;
function automatic logic f(StateEnumT sig);
logic is_defined = 1'b0;
for (int i = 0, StateEnumT t = t.first(); i < t.num(); i += 1, t = t.next()) begin
is_defined |= (sig === t);
end
return ~is_defined;
endfunction
endmodule
====
# a for loop that assigns to an existing variable is not a declaration
module m;
initial begin
for (i = 0; i < N; i = i + 1) x = i;
end
endmodule
----
module m;
initial begin
for (i = 0; i < N; i = i + 1) x = i;
end
endmodule
====
# an anonymous enum declaration at the line-length boundary
module m;
enum logic [1:0] {LONG_NAME_ONE, LONG_NAME_TWO, LONG_NAME_THREE} state_of_the_machine_xxxxxxxxxxx;
enum logic [1:0] {LONG_NAME_ONE, LONG_NAME_TWO, LONG_NAME_THREE} state_of_the_machine_xxxxxxxxxxxx;
endmodule
----
module m;
enum logic [1:0] {LONG_NAME_ONE, LONG_NAME_TWO, LONG_NAME_THREE} state_of_the_machine_xxxxxxxxxxx;
enum logic [1:0] {
LONG_NAME_ONE,
LONG_NAME_TWO,
LONG_NAME_THREE
} state_of_the_machine_xxxxxxxxxxxx;
endmodule
====
# an anonymous struct declaration carrying leading and trailing comments
module m;
// the packet header
struct packed {
logic [7:0] tag; // the tag
} hdr; // one header
endmodule
----
module m;
// the packet header
struct packed {
logic [7:0] tag; // the tag
} hdr; // one header
endmodule
====
# an anonymous aggregate as a function or task argument
module m;
function void f(struct packed {logic a;} arg);
endfunction
task t(enum {X, Y} mode);
endtask
endmodule
----
module m;
function void f(
struct packed {
logic a;
} arg
);
endfunction
task t(enum {X, Y} mode);
endtask
endmodule
====
# several declarators on one `type` parameter, and one with no default
module m;
localparam type A = int, B = logic [7:0];
localparam type C;
endmodule
----
module m;
localparam type A = int, B = logic [7:0];
localparam type C;
endmodule
@@ -64,7 +64,10 @@ impl Rule for ExplicitParameterStorageType {
/// Reports every name of a `parameter`/`localparam` declaration that wrote no /// Reports every name of a `parameter`/`localparam` declaration that wrote no
/// storage type. /// storage type.
fn untyped_decl(decl: &ParamDecl, out: &mut Vec<Violation>) { fn untyped_decl(decl: &ParamDecl, out: &mut Vec<Violation>) {
if !decl.ty.name.is_empty() { // A type parameter (`localparam type payload_t = logic [7:0];`) has no
// storage type to declare — the same exemption the parameter-port path
// makes for `parameter type T = int`.
if decl.is_type || !decl.ty.name.is_empty() {
return; return;
} }
for declarator in &decl.declarators { for declarator in &decl.declarators {
@@ -121,6 +124,13 @@ mod tests {
assert_eq!(found.len(), 2, "{found:?}"); assert_eq!(found.len(), 2, "{found:?}");
} }
#[test]
fn an_item_level_type_parameter_is_clean() {
let src = "module m;\n localparam type payload_t = logic [7:0];\n\
parameter type word_t = logic [31:0];\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test] #[test]
fn packed_dimensions_alone_are_not_a_storage_type() { fn packed_dimensions_alone_are_not_a_storage_type() {
assert_eq!(violations("module m;\n parameter [7:0] A = 1;\nendmodule\n").len(), 1); assert_eq!(violations("module m;\n parameter [7:0] A = 1;\nendmodule\n").len(), 1);
+51 -16
View File
@@ -129,7 +129,7 @@ pub struct RawText {
/// two back into source order. vfmt does not evaluate the condition — both /// two back into source order. vfmt does not evaluate the condition — both
/// arms' elements are ordinary elements of the one list, exactly as an /// arms' elements are ordinary elements of the one list, exactly as an
/// `` `ifdef`` at item position already works. /// `` `ifdef`` at item position already works.
#[derive(Debug)] #[derive(Debug, Clone)]
pub struct ListDirective { pub struct ListDirective {
/// The directive line, verbatim. /// The directive line, verbatim.
pub raw: RawText, pub raw: RawText,
@@ -395,20 +395,18 @@ pub struct DataType {
/// rest of the member qualifiers already live; this field carries the /// rest of the member qualifiers already live; this field carries the
/// positions that have no qualifier list of their own. /// positions that have no qualifier list of their own.
/// ///
/// A one-byte enum rather than the text, for the same reason `params` is /// A one-byte enum rather than the text, for the same reason `extra` is
/// boxed: every `Expr` carries a `DataType` through [`ExprKind::Type`], /// boxed: every `Expr` carries a `DataType` through [`ExprKind::Type`],
/// so a rare field must not widen the common case. /// so a rare field must not widen the common case.
pub virt: Option<VirtualKw>, pub virt: Option<VirtualKw>,
pub name: String, pub name: String,
/// The `#( ... )` of a parameterized type reference, verbatim: /// The rare tail of a type: parameterization or an anonymous aggregate
/// `uvm_analysis_port #(bit [31:0]) port;`. Its arguments are types as /// body. See [`TypeExtra`]; read it through [`DataType::params`] /
/// often as expressions (`#(virtual bus_if)`, `#(item #(A, B))`), so vfmt /// [`DataType::inline`].
/// reproduces them as written instead of modelling a second grammar.
/// ///
/// Boxed to keep `DataType` — and through `ExprKind::Type`, every `Expr` /// Boxed — and the two spellings share the one box — to keep `DataType`,
/// — small: a parameterized type reference is rare and every expression /// and through [`ExprKind::Type`] every `Expr`, small.
/// would otherwise carry the whole `RawText` inline. pub extra: Option<Box<TypeExtra>>,
pub params: Option<Box<RawText>>,
pub signing: Option<String>, pub signing: Option<String>,
pub packed: Vec<Dim>, pub packed: Vec<Dim>,
} }
@@ -417,10 +415,44 @@ impl DataType {
pub fn is_implicit(&self) -> bool { pub fn is_implicit(&self) -> bool {
self.virt.is_none() self.virt.is_none()
&& self.name.is_empty() && self.name.is_empty()
&& self.params.is_none() && self.extra.is_none()
&& self.signing.is_none() && self.signing.is_none()
&& self.packed.is_empty() && self.packed.is_empty()
} }
/// The `#( ... )` of a parameterized type reference, if one was written.
pub fn params(&self) -> Option<&RawText> {
match self.extra.as_deref() {
Some(TypeExtra::Params(p)) => Some(p),
_ => None,
}
}
/// The anonymous aggregate that *is* this type, if one was written.
pub fn inline(&self) -> Option<&TypeExtra> {
match self.extra.as_deref() {
Some(e @ (TypeExtra::Enum(_) | TypeExtra::Struct(_))) => Some(e),
_ => None,
}
}
}
/// What a type carries beyond its name, signing and packed dimensions. A type
/// never has two of these at once — an anonymous aggregate has no name to
/// parameterize — so they share one box on [`DataType`].
#[derive(Debug, Clone)]
pub enum TypeExtra {
/// The `#( ... )` of a parameterized type reference, verbatim:
/// `uvm_analysis_port #(bit [31:0]) port;`. Its arguments are types as
/// often as expressions (`#(virtual bus_if)`, `#(item #(A, B))`), so vfmt
/// reproduces them as written instead of modelling a second grammar.
Params(RawText),
/// An anonymous enum standing where a type name would:
/// `enum logic [1:0] {IDLE, STOP} state;`.
Enum(EnumType),
/// An anonymous struct or union standing where a type name would:
/// `struct packed { ... } s;`.
Struct(StructType),
} }
/// How a virtual interface type reference is spelled. The `interface` keyword /// How a virtual interface type reference is spelled. The `interface` keyword
@@ -483,7 +515,7 @@ pub enum TypedefKind {
ForwardClass, ForwardClass,
} }
#[derive(Debug)] #[derive(Debug, Clone)]
pub struct EnumType { pub struct EnumType {
pub base: Option<DataType>, pub base: Option<DataType>,
pub members: Vec<EnumMember>, pub members: Vec<EnumMember>,
@@ -492,7 +524,7 @@ pub struct EnumType {
pub dangling: Vec<Comment>, pub dangling: Vec<Comment>,
} }
#[derive(Debug)] #[derive(Debug, Clone)]
pub struct EnumMember { pub struct EnumMember {
pub meta: Meta, pub meta: Meta,
pub name: String, pub name: String,
@@ -506,7 +538,7 @@ pub struct EnumMember {
pub span: TextRange, pub span: TextRange,
} }
#[derive(Debug)] #[derive(Debug, Clone)]
pub struct StructType { pub struct StructType {
/// "struct" or "union" /// "struct" or "union"
pub kw: String, pub kw: String,
@@ -516,7 +548,7 @@ pub struct StructType {
pub dangling: Vec<Comment>, pub dangling: Vec<Comment>,
} }
#[derive(Debug)] #[derive(Debug, Clone)]
pub struct StructMember { pub struct StructMember {
pub meta: Meta, pub meta: Meta,
pub ty: DataType, pub ty: DataType,
@@ -529,6 +561,9 @@ pub struct StructMember {
pub struct ParamDecl { pub struct ParamDecl {
/// `parameter` or `localparam` /// `parameter` or `localparam`
pub kw: String, pub kw: String,
/// A type parameter: `localparam type payload_t = logic [7:0];`. The
/// declarator's `init` is then an [`ExprKind::Type`], not a value.
pub is_type: bool,
pub ty: DataType, pub ty: DataType,
pub declarators: Vec<Declarator>, pub declarators: Vec<Declarator>,
} }
@@ -556,7 +591,7 @@ pub struct PortDecl {
pub declarators: Vec<Declarator>, pub declarators: Vec<Declarator>,
} }
#[derive(Debug)] #[derive(Debug, Clone)]
pub struct Declarator { pub struct Declarator {
pub meta: Meta, pub meta: Meta,
pub name: String, pub name: String,
+299 -121
View File
@@ -1006,6 +1006,33 @@ impl<'a> Parser<'a> {
i i
} }
/// Does the identifier at the cursor open a declaration whose type is a
/// user-defined name? True when a declarator identifier still follows it
/// past the optional `pkg::` chain, `#( ... )` overrides and packed
/// dimensions: `my_t x`, `pkg::my_t x`, `item #(A, B) req`,
/// `payload_t [NumOut-1:0][NumInp-1:0] out_data` (stream_xbar.sv:98).
///
/// This is what keeps `x[i] = 1;` an assignment: what follows the
/// brackets there is `=`, not a name.
fn at_typed_declarator(&self) -> bool {
let mut p = self.pos;
while self.tokens.get(p + 1).is_some_and(|t| t.is_sym("::")) {
p += 2;
}
let mut next = p + 1;
// A parameterized type puts `#( ... )` between the name and the
// declarator (`uvm_analysis_port #(bit [31:0]) port;`).
if self.tokens.get(next).is_some_and(|t| t.is_sym("#"))
&& self.tokens.get(next + 1).is_some_and(|t| t.is_sym("("))
{
next = self.scan_matching(next + 1, "(", ")");
}
while self.tokens.get(next).is_some_and(|t| t.is_sym("[")) {
next = self.scan_matching(next, "[", "]");
}
self.tokens.get(next).is_some_and(|t| t.kind == TokenKind::Ident)
}
// ------------------------------------------------------------------ // ------------------------------------------------------------------
// Top level // Top level
// ------------------------------------------------------------------ // ------------------------------------------------------------------
@@ -1195,9 +1222,12 @@ impl<'a> Parser<'a> {
_ if GATE_KEYWORDS.contains(&kw.as_str()) => { _ if GATE_KEYWORDS.contains(&kw.as_str()) => {
self.parse_gate_instantiation().map(ItemKind::GateInstantiation) self.parse_gate_instantiation().map(ItemKind::GateInstantiation)
} }
// `enum`/`struct`/`union` here is an anonymous aggregate type
// introducing a variable (`enum logic [1:0] {A, B} state;`) — the
// `typedef` spelling is taken by the arm above.
_ if NET_KEYWORDS.contains(&kw.as_str()) _ if NET_KEYWORDS.contains(&kw.as_str())
|| TYPE_KEYWORDS.contains(&kw.as_str()) || TYPE_KEYWORDS.contains(&kw.as_str())
|| matches!(kw.as_str(), "signed" | "unsigned") => || matches!(kw.as_str(), "signed" | "unsigned" | "enum" | "struct" | "union") =>
{ {
let d = self.parse_data_decl()?; let d = self.parse_data_decl()?;
Ok(ItemKind::DataDecl(d)) Ok(ItemKind::DataDecl(d))
@@ -2131,32 +2161,24 @@ impl<'a> Parser<'a> {
Some(if self.eat_kw("interface") { VirtualKw::Interface } else { VirtualKw::Bare }); Some(if self.eat_kw("interface") { VirtualKw::Interface } else { VirtualKw::Bare });
} }
let t = self.cur(); let t = self.cur();
// An anonymous aggregate stands where a type name does (IEEE 1800
// §6.19, §7.2): `enum logic [1:0] {IDLE, STOP} state, state_next;`
// (clock_divider.sv:59), `struct packed { ... } s;`. The body is the
// same one `typedef` takes, so the two share a parser.
if t.is_kw("enum") {
ty.extra = Some(Box::new(TypeExtra::Enum(self.parse_enum_type()?)));
return Ok(ty);
}
if t.is_kw("struct") || t.is_kw("union") {
ty.extra = Some(Box::new(TypeExtra::Struct(self.parse_struct_type()?)));
return Ok(ty);
}
if t.kind == TokenKind::Keyword && TYPE_KEYWORDS.contains(&t.text.as_str()) { if t.kind == TokenKind::Keyword && TYPE_KEYWORDS.contains(&t.text.as_str()) {
ty.name = self.bump().text; ty.name = self.bump().text;
} else if t.kind == TokenKind::Ident { } else if t.kind == TokenKind::Ident {
// User-defined type only if what follows still leaves an // User-defined type only if what follows still leaves an
// identifier for the declarator name. // identifier for the declarator name.
let mut p = self.pos; if self.at_typed_declarator() {
while self.tokens.get(p + 1).is_some_and(|t| t.is_sym("::")) {
p += 2;
}
let mut next = p + 1;
// A parameterized type puts `#( ... )` between the name and the
// declarator (`uvm_analysis_port #(bit [31:0]) port;`).
if self.tokens.get(next).is_some_and(|t| t.is_sym("#"))
&& self.tokens.get(next + 1).is_some_and(|t| t.is_sym("("))
{
next = self.scan_matching(next + 1, "(", ")");
}
let is_type = match self.tokens.get(next) {
Some(n) if n.kind == TokenKind::Ident => true,
Some(n) if n.is_sym("[") => {
let after = self.scan_matching(next, "[", "]");
self.tokens.get(after).is_some_and(|t| t.kind == TokenKind::Ident)
}
_ => false,
};
if is_type {
let mut name = self.expect_ident()?; let mut name = self.expect_ident()?;
while self.cur().is_sym("::") { while self.cur().is_sym("::") {
self.bump(); self.bump();
@@ -2165,7 +2187,7 @@ impl<'a> Parser<'a> {
} }
ty.name = name; ty.name = name;
if self.at_type_params() { if self.at_type_params() {
ty.params = Some(Box::new(self.parse_type_params()?)); ty.extra = Some(Box::new(TypeExtra::Params(self.parse_type_params()?)));
} }
} }
} }
@@ -2202,13 +2224,14 @@ impl<'a> Parser<'a> {
fn parse_type_expr(&mut self) -> PResult<Expr> { fn parse_type_expr(&mut self) -> PResult<Expr> {
let start = self.here(); let start = self.here();
let ty = self.parse_opt_data_type()?; let ty = self.parse_type_ref()?;
if ty.is_implicit() { if ty.is_implicit() {
// Fall back: a plain identifier type (e.g. `= my_type_t`). // Nothing that can be a type stands here. `parse_type_ref` takes a
let name = self.expect_ident()?; // bare identifier, so whatever is at the cursor is not one and
let mut t = DataType { name, ..DataType::default() }; // `expect_ident` always fails — naming the offending token the way
t.packed = self.parse_dims()?; // this position has always named it.
return Ok(self.expr_at(start, ExprKind::Type(t))); self.expect_ident()?;
return self.error("expected a type");
} }
Ok(self.expr_at(start, ExprKind::Type(ty))) Ok(self.expr_at(start, ExprKind::Type(ty)))
} }
@@ -2219,20 +2242,34 @@ impl<'a> Parser<'a> {
fn parse_param_decl(&mut self) -> PResult<ParamDecl> { fn parse_param_decl(&mut self) -> PResult<ParamDecl> {
let kw = self.bump().text; let kw = self.bump().text;
let ty = self.parse_opt_data_type()?; // `localparam type payload_t = logic [$clog2(NumReq)-1:0];` — a type
let declarators = self.parse_declarators()?; // parameter outside the `#( ... )` list
Ok(ParamDecl { kw, ty, declarators }) // (lossy_valid_to_stream_tb.sv:26). Its default is a type, not a value.
let is_type = self.eat_kw("type");
let ty = if is_type { DataType::default() } else { self.parse_opt_data_type()? };
let declarators = self.parse_declarator_list(is_type)?;
Ok(ParamDecl { kw, is_type, ty, declarators })
} }
/// Parse declarators up to (but not consuming) the terminating `;`. /// Parse declarators up to (but not consuming) the terminating `;`.
fn parse_declarators(&mut self) -> PResult<Vec<Declarator>> { fn parse_declarators(&mut self) -> PResult<Vec<Declarator>> {
self.parse_declarator_list(false)
}
/// Parse declarators; `type_init` makes each `= ...` a type rather than an
/// expression, which is what a `type` parameter's default is.
fn parse_declarator_list(&mut self, type_init: bool) -> PResult<Vec<Declarator>> {
let mut out = Vec::new(); let mut out = Vec::new();
loop { loop {
let start = self.here(); let start = self.here();
let mut meta = self.take_meta(); let mut meta = self.take_meta();
let Name { text: name, span: name_span } = self.expect_name()?; let Name { text: name, span: name_span } = self.expect_name()?;
let unpacked = self.parse_dims()?; let unpacked = self.parse_dims()?;
let init = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; let init = if self.eat_sym("=") {
Some(if type_init { self.parse_type_expr()? } else { self.parse_expr()? })
} else {
None
};
let span = self.span_from(start); let span = self.span_from(start);
self.take_before_sep(&mut meta, ","); self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(","); let more = self.eat_sym(",");
@@ -2313,78 +2350,18 @@ impl<'a> Parser<'a> {
}); });
} }
if self.cur().is_kw("enum") { if self.cur().is_kw("enum") {
self.bump(); let e = self.parse_enum_type()?;
let base = {
let t = self.cur();
if t.is_sym("{") {
None
} else {
Some(self.parse_opt_data_type()?)
}
};
self.expect_sym("{")?;
let mut members = Vec::new();
let mut directives = Vec::new();
self.take_list_directives(&mut directives, 0);
loop {
let start = self.here();
let mut meta = self.take_meta();
let Name { text: name, span: name_span } = self.expect_name()?;
// Enum member ranges (`VAL[4]`) are rare; unsupported.
let value = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let comma = self.eat_sym(",");
meta.trailing = self.take_trailing();
members.push(EnumMember { meta, name, name_span, value, comma, span });
let dirs = self.take_list_directives(&mut directives, members.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym("}")) {
break;
}
}
let dangling = self.take_dangling();
self.expect_sym("}")?;
let Name { text: name, span: name_span } = self.expect_name()?; let Name { text: name, span: name_span } = self.expect_name()?;
let unpacked = self.parse_dims()?; let unpacked = self.parse_dims()?;
self.expect_sym(";")?; self.expect_sym(";")?;
return Ok(Typedef { return Ok(Typedef { name, name_span, unpacked, kind: TypedefKind::Enum(e) });
name,
name_span,
unpacked,
kind: TypedefKind::Enum(EnumType { base, members, directives, dangling }),
});
} }
if self.cur().is_kw("struct") || self.cur().is_kw("union") { if self.cur().is_kw("struct") || self.cur().is_kw("union") {
let kw = self.bump().text; let s = self.parse_struct_type()?;
let packed = self.eat_kw("packed");
let signing = if self.cur().is_kw("signed") || self.cur().is_kw("unsigned") {
Some(self.bump().text)
} else {
None
};
self.expect_sym("{")?;
let mut members = Vec::new();
while !self.cur().is_sym("}") && !self.at_eof() {
let start = self.here();
let mut meta = self.take_meta();
let ty = self.parse_opt_data_type()?;
let declarators = self.parse_declarators()?;
self.expect_sym(";")?;
let span = self.span_from(start);
meta.trailing = self.take_trailing();
members.push(StructMember { meta, ty, declarators, span });
}
let dangling = self.take_dangling();
self.expect_sym("}")?;
let Name { text: name, span: name_span } = self.expect_name()?; let Name { text: name, span: name_span } = self.expect_name()?;
let unpacked = self.parse_dims()?; let unpacked = self.parse_dims()?;
self.expect_sym(";")?; self.expect_sym(";")?;
return Ok(Typedef { return Ok(Typedef { name, name_span, unpacked, kind: TypedefKind::Struct(s) });
name,
name_span,
unpacked,
kind: TypedefKind::Struct(StructType { kw, packed, signing, members, dangling }),
});
} }
let ty = self.parse_opt_data_type()?; let ty = self.parse_opt_data_type()?;
let Name { text: name, span: name_span } = self.expect_name()?; let Name { text: name, span: name_span } = self.expect_name()?;
@@ -2393,6 +2370,94 @@ impl<'a> Parser<'a> {
Ok(Typedef { name, name_span, unpacked, kind: TypedefKind::Alias(ty) }) Ok(Typedef { name, name_span, unpacked, kind: TypedefKind::Alias(ty) })
} }
/// `enum [base] { A, B = 2 }` — the cursor is on `enum` and stops on the
/// token after the closing `}`. Shared by `typedef enum ...` and by an
/// anonymous enum used as a type in place (IEEE 1800 §6.19).
fn parse_enum_type(&mut self) -> PResult<EnumType> {
self.expect_kw("enum")?;
// The base type may be a keyword (`logic [1:0]`) or a typedef'd name
// (`typedef enum action_mask_t {...}`, prim_count_pkg.sv:10).
let base = if self.cur().is_sym("{") { None } else { Some(self.parse_type_ref()?) };
self.expect_sym("{")?;
let mut members = Vec::new();
let mut directives = Vec::new();
self.take_list_directives(&mut directives, 0);
loop {
let start = self.here();
let mut meta = self.take_meta();
let Name { text: name, span: name_span } = self.expect_name()?;
// Enum member ranges (`VAL[4]`) are rare; unsupported.
let value = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let comma = self.eat_sym(",");
meta.trailing = self.take_trailing();
members.push(EnumMember { meta, name, name_span, value, comma, span });
let dirs = self.take_list_directives(&mut directives, members.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym("}")) {
break;
}
}
let dangling = self.take_dangling();
self.expect_sym("}")?;
Ok(EnumType { base, members, directives, dangling })
}
/// `struct|union [packed] [signing] { members }` — the cursor is on the
/// keyword and stops on the token after the closing `}`. Shared by
/// `typedef struct ...`, an anonymous struct used as a type in place, and
/// a struct member whose own type is an inline struct (uart_reg_pkg.sv:30).
fn parse_struct_type(&mut self) -> PResult<StructType> {
let kw = self.bump().text;
let packed = self.eat_kw("packed");
let signing = if self.cur().is_kw("signed") || self.cur().is_kw("unsigned") {
Some(self.bump().text)
} else {
None
};
self.expect_sym("{")?;
let mut members = Vec::new();
while !self.cur().is_sym("}") && !self.at_eof() {
let start = self.here();
let mut meta = self.take_meta();
let ty = self.parse_opt_data_type()?;
let declarators = self.parse_declarators()?;
self.expect_sym(";")?;
let span = self.span_from(start);
meta.trailing = self.take_trailing();
members.push(StructMember { meta, ty, declarators, span });
}
let dangling = self.take_dangling();
self.expect_sym("}")?;
Ok(StructType { kw, packed, signing, members, dangling })
}
/// A data type in a position where one is *required* — an enum base type,
/// a `type` parameter's default. Unlike [`Parser::parse_opt_data_type`],
/// which only takes an identifier when a declarator name follows it, a
/// bare `my_type_t` here is the whole type.
fn parse_type_ref(&mut self) -> PResult<DataType> {
let ty = self.parse_opt_data_type()?;
if !ty.is_implicit() || self.cur().kind != TokenKind::Ident {
return Ok(ty);
}
let mut name = self.expect_ident()?;
while self.cur().is_sym("::") {
self.bump();
name.push_str("::");
name.push_str(&self.expect_ident()?);
}
let mut ty = DataType { name, ..DataType::default() };
if self.at_type_params() {
ty.extra = Some(Box::new(TypeExtra::Params(self.parse_type_params()?)));
}
if self.cur().is_kw("signed") || self.cur().is_kw("unsigned") {
ty.signing = Some(self.bump().text);
}
ty.packed = self.parse_dims()?;
Ok(ty)
}
// ------------------------------------------------------------------ // ------------------------------------------------------------------
// Module items // Module items
// ------------------------------------------------------------------ // ------------------------------------------------------------------
@@ -3206,10 +3271,17 @@ impl<'a> Parser<'a> {
let mut init = Vec::new(); let mut init = Vec::new();
if !self.cur().is_sym(";") { if !self.cur().is_sym(";") {
loop { 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 ty = {
let t = self.cur(); let t = self.cur();
if t.kind == TokenKind::Keyword let kw_type = t.kind == TokenKind::Keyword
&& TYPE_KEYWORDS.contains(&t.text.as_str()) && TYPE_KEYWORDS.contains(&t.text.as_str());
if kw_type || (t.kind == TokenKind::Ident && self.at_typed_declarator())
{ {
Some(self.parse_opt_data_type()?) Some(self.parse_opt_data_type()?)
} else { } else {
@@ -3383,7 +3455,17 @@ impl<'a> Parser<'a> {
// also start a statement. // also start a statement.
_ if NET_KEYWORDS.contains(&kw.as_str()) _ if NET_KEYWORDS.contains(&kw.as_str())
|| TYPE_KEYWORDS.contains(&kw.as_str()) || TYPE_KEYWORDS.contains(&kw.as_str())
|| matches!(kw.as_str(), "var" | "automatic" | "static" | "const" | "virtual") => || matches!(
kw.as_str(),
"var"
| "automatic"
| "static"
| "const"
| "virtual"
| "enum"
| "struct"
| "union"
) =>
{ {
// A type keyword followed by `'` is a cast expression, not a // A type keyword followed by `'` is a cast expression, not a
// declaration. // declaration.
@@ -3459,25 +3541,12 @@ impl<'a> Parser<'a> {
} }
fn parse_assign_or_expr_stmt(&mut self) -> PResult<StmtKind> { fn parse_assign_or_expr_stmt(&mut self) -> PResult<StmtKind> {
// Declaration with a user-defined type: `my_t x;` / `my_t x = e;` // Declaration with a user-defined type: `my_t x;` / `my_t x = e;` /
if self.cur().kind == TokenKind::Ident { // `my_t [N-1:0] x;`. An assignment (`x[i] = 1;`) is not one: nothing
let mut p = self.pos; // that could be a declarator name follows its brackets.
while self.tokens.get(p + 1).is_some_and(|t| t.is_sym("::")) { if self.cur().kind == TokenKind::Ident && self.at_typed_declarator() {
p += 2; let d = self.parse_data_decl()?;
} return Ok(StmtKind::VarDecl(d));
let mut n = p + 1;
// `item #(A, B) req;` declares a variable of a parameterized type;
// the overrides sit between the type name and the declarator.
if self.tokens.get(n).is_some_and(|t| t.is_sym("#"))
&& self.tokens.get(n + 1).is_some_and(|t| t.is_sym("("))
{
n = self.scan_matching(n + 1, "(", ")");
}
let next = &self.tokens[n.min(self.tokens.len() - 1)];
if next.kind == TokenKind::Ident {
let d = self.parse_data_decl()?;
return Ok(StmtKind::VarDecl(d));
}
} }
// The statement's own meta drained the pending comments, so anything // The statement's own meta drained the pending comments, so anything
// trailing from here on was written inside this statement. // trailing from here on was written inside this statement.
@@ -5303,7 +5372,7 @@ mod tests {
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a declaration") }; let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a declaration") };
assert_eq!(d.ty.name, "port_t"); assert_eq!(d.ty.name, "port_t");
assert_eq!(d.ty.params.as_ref().expect("type parameters").text, "#(bit [3:0])"); assert_eq!(d.ty.params().expect("type parameters").text, "#(bit [3:0])");
assert!(matches!(m.items[1].kind, ItemKind::Instantiation(_))); assert!(matches!(m.items[1].kind, ItemKind::Instantiation(_)));
} }
@@ -5410,7 +5479,7 @@ mod tests {
let c = class_of(&f); let c = class_of(&f);
let ItemKind::DataDecl(d) = &c.items[0].kind else { panic!("expected a declaration") }; let ItemKind::DataDecl(d) = &c.items[0].kind else { panic!("expected a declaration") };
assert_eq!(d.ty.name, "item_t"); assert_eq!(d.ty.name, "item_t");
assert!(d.ty.params.is_some()); assert!(d.ty.params().is_some());
assert_eq!(d.declarators[0].name, "q"); assert_eq!(d.declarators[0].name, "q");
} }
@@ -5639,4 +5708,113 @@ mod tests {
assert_eq!(fun.args[0].ty.virt, Some(VirtualKw::Interface)); assert_eq!(fun.args[0].ty.virt, Some(VirtualKw::Interface));
assert_eq!(fun.args[0].ty.name, "bus_if"); assert_eq!(fun.args[0].ty.name, "bus_if");
} }
#[test]
fn an_anonymous_enum_declares_a_variable() {
// corpus/common_cells/src/deprecated/clock_divider.sv:59
let f =
parse_ok("module m;\n enum logic [1:0] {IDLE, STOP} state, state_next;\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a declaration") };
let Some(TypeExtra::Enum(e)) = d.ty.inline() else { panic!("expected an inline enum") };
assert_eq!(e.members.len(), 2);
assert_eq!(e.base.as_ref().map(|b| b.name.as_str()), Some("logic"));
assert_eq!(d.declarators.len(), 2);
}
#[test]
fn an_anonymous_struct_declares_a_variable() {
let f = parse_ok("module m;\n struct packed {logic a;} s;\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a declaration") };
let Some(TypeExtra::Struct(st)) = d.ty.inline() else {
panic!("expected an inline struct")
};
assert_eq!(st.kw, "struct");
assert!(st.packed);
assert_eq!(d.declarators[0].name, "s");
}
#[test]
fn a_struct_member_may_itself_be_an_inline_aggregate() {
// corpus/opentitan/hw/ip/uart/rtl/uart_reg_pkg.sv:30
let f = parse_ok(
"package p;\n typedef struct packed {\n struct packed {logic q;} tx;\n } r_t;\nendpackage\n",
);
let ItemKind::Package { items, .. } = &f.items[0].kind else {
panic!("expected a package")
};
let ItemKind::Typedef(t) = &items[0].kind else { panic!("expected a typedef") };
let TypedefKind::Struct(st) = &t.kind else { panic!("expected a struct") };
assert!(matches!(st.members[0].ty.inline(), Some(TypeExtra::Struct(_))));
}
#[test]
fn an_enum_base_type_may_be_a_typedef_name() {
// corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_count_pkg.sv:10
let f = parse_ok(
"package p;\n typedef enum action_mask_t {Clr = 4'h1} action_e;\nendpackage\n",
);
let ItemKind::Package { items, .. } = &f.items[0].kind else {
panic!("expected a package")
};
let ItemKind::Typedef(t) = &items[0].kind else { panic!("expected a typedef") };
let TypedefKind::Enum(e) = &t.kind else { panic!("expected an enum") };
assert_eq!(e.base.as_ref().map(|b| b.name.as_str()), Some("action_mask_t"));
}
#[test]
fn packed_dimensions_may_follow_a_typedef_type_name() {
// corpus/common_cells/src/stream_xbar.sv:98
let f = parse_ok("module m;\n payload_t [A-1:0][B-1:0] out_data;\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::DataDecl(d) = &m.items[0].kind else { panic!("expected a declaration") };
assert_eq!(d.ty.name, "payload_t");
assert_eq!(d.ty.packed.len(), 2);
assert_eq!(d.declarators[0].name, "out_data");
}
#[test]
fn an_indexed_assignment_is_not_a_declaration() {
let f = parse_ok("module m;\n always_comb begin\n x[i] = 1;\n end\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Always { stmt, .. } = &m.items[0].kind else { panic!("expected an always") };
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
assert!(
matches!(stmts[0].kind, StmtKind::Assign { .. }),
"expected an assignment, got {:?}",
stmts[0].kind
);
}
#[test]
fn a_type_parameter_may_be_declared_as_an_item() {
// corpus/common_cells/test/lossy_valid_to_stream_tb.sv:26
let f = parse_ok("module m;\n localparam type payload_t = logic [7:0];\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::ParamDecl(d) = &m.items[0].kind else { panic!("expected a parameter") };
assert!(d.is_type);
assert!(matches!(d.declarators[0].init.as_ref().map(|e| &e.kind), Some(ExprKind::Type(_))));
}
#[test]
fn a_for_init_may_declare_a_typedef_typed_variable() {
// corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_sparse_fsm_flop.sv:48
let f = parse_ok(
"module m;\n initial for (int i = 0, state_e t = t.first(); i < 2; i += 1, t = t.next()) x = i;\nendmodule\n",
);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") };
let StmtKind::For { init, step, .. } = &stmt.kind else { panic!("expected a for") };
assert_eq!(init.len(), 2);
assert_eq!(init[0].ty.as_ref().map(|t| t.name.as_str()), Some("int"));
assert_eq!(init[1].ty.as_ref().map(|t| t.name.as_str()), Some("state_e"));
assert_eq!(step.len(), 2);
}
#[test]
fn an_unterminated_anonymous_enum_is_an_error() {
assert!(parse_err("module m;\n enum logic [1:0] {A, B state;\nendmodule\n")
.contains("expected"));
}
} }
+183
View File
@@ -0,0 +1,183 @@
# types-decls
## Goal
Close the `types-decls` bucket of `scripts/score.sh`: the seven declaration
shapes that real RTL writes and vfmt could not parse. All of them are about a
**type standing somewhere vfmt only accepted a name** — an anonymous
`enum`/`struct`/`union` used as a type in place, a typedef'd name carrying
packed dimensions, a `type` parameter outside the `#( ... )` list — plus a
`for` loop whose init declares more than one variable.
## Assumptions
- An anonymous aggregate is *the* type: it never shares a `DataType` with a
name, signing or packed dimensions of its own. Any dimensions written after
the closing `}` belong to the declarator, which is where `parse_declarators`
already puts them.
- `enum` / `struct` / `union` at **item** and **statement** position always
opens a data declaration. The `typedef` spelling is taken by an earlier arm,
and there is no other construct those keywords can begin there.
- At item position, an identifier followed by balanced `[...]` groups and then
another identifier is a declaration, not an expression. A *range select
followed by a name* is not a legal statement, so nothing is stolen from the
expression grammar. The same test gates statement position, where it is what
keeps `x[i] = 1;` an assignment: what follows the brackets there is `=`.
- Enum member names introduced by an *anonymous* enum are not entered into the
semantic model's scopes (only `typedef enum` members are). Nothing in the
formatter needs them; see Handshakes.
- An anonymous `struct`/`union` body always breaks one member per line, like
the `typedef struct` path it shares. An anonymous `enum` body is a group: one
line if it fits, else one member per line — again the `typedef enum` rule.
Both are the layout the corpus already writes.
## Handshakes
**Consumed**
- `vlog_parser::parser` — `parse_opt_data_type` is the one door every type
position goes through (declarations, ports, `typedef` bases, tf arguments,
struct members, `parameter type` defaults). Teaching *it* about anonymous
aggregates is what made shapes 1, 2 and 5 land together.
- `vlog_formatter::format` — `delimited_dangling` (the fit-or-break list) and
`indent`/`Doc::HardLine` for the struct body; both were already what the
`typedef` path used.
- `vlog_formatter::verify` — **not modified**. Every shape here adds tokens to
the AST rather than normalizing them away, so the existing equivalence and
convergence checks cover the new output unchanged.
**Promised / changed for other modules**
- `ast::DataType` lost `params: Option<Box<RawText>>` and gained
`extra: Option<Box<TypeExtra>>`, read through the accessors
`DataType::params()` and `DataType::inline()`. The two rare tails share one
box on purpose: `DataType` rides inside every `Expr` through
`ExprKind::Type`, and a second `Option<Box<..>>` field pushed `DimKind` past
clippy's `large_enum_variant` threshold. Only `format.rs` and two parser
sites read the field.
- `ast::ParamDecl` gained `is_type: bool` (`localparam type payload_t = ...;`).
`vlog_linter`'s `explicit-parameter-storage-type` now exempts it, matching
the exemption the parameter-*port* path already made for
`parameter type T = int` — a type parameter has no storage type to declare.
Fixed here rather than filed, because the false positive is created by this
change.
- `ast::{EnumType, EnumMember, StructType, StructMember, Declarator,
ListDirective}` now derive `Clone`, so `DataType` can keep deriving it.
- No new `ItemKind` / `StmtKind` / `ExprKind` variants, so no exhaustive-match
arms were needed in `vlog_linter::visit`, `vlog_semantic` or `vfmt_server`.
**Requests for other modules (not done here)**
- `vlog_semantic::bind` declares `typedef enum` members and `typedef struct`
members as symbols (`bind.rs:395`, `bind.rs:406`). The equivalent members of
an *anonymous* aggregate — `enum {A, B} x;`, the nested `struct packed {...}
q;` of a register-package typedef — are not declared, so go-to-definition
and hover do not find them. Purely an LSP completeness gap; the formatter
and the corpus metric do not depend on it.
- `vlog_linter`'s `enum-name-style` / `struct-union-name-style` only look at
`ItemKind::Typedef`, so an anonymous aggregate is out of their reach by
construction. That is correct today (an anonymous type has no name to
style), but a future rule about *member* naming would want the inline bodies
too.
## Status / TODO
- [x] 1. Anonymous `enum` as a variable declaration, with and without a base
type — `corpus/common_cells/src/deprecated/clock_divider.sv:59`,
`generic_fifo.sv:61`, `generic_fifo_adv.sv:39`
- [x] 1b. Anonymous packed `struct` / `union` declarations (no corpus hit;
same machinery, cases added)
- [x] 2. `struct packed { ... }` / `enum { ... }` as a `parameter type`
default — `corpus/common_cells/src/ecc_decode.sv:36`,
`ecc_encode.sv:29`
- [x] 3. A typedef'd type with packed dimensions before the declarator —
`corpus/common_cells/src/stream_omega_net.sv:162`,
`stream_xbar.sv:98`; also as a function local and a class property
- [x] 4. `typedef enum <typedef'd_base_t> { ... } name_t;` —
`corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_count_pkg.sv:10`
- [x] 5. A nested anonymous aggregate as a struct member —
`corpus/opentitan/hw/ip/uart/rtl/uart_reg_pkg.sv:30`
- [x] 6. `localparam type` / `parameter type` as a body item —
`corpus/common_cells/test/lossy_valid_to_stream_tb.sv:26`
- [x] 7. A `for` loop declaring several variables in its init —
`corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_sparse_fsm_flop.sv:48`
- [x] Cases in `crates/vlog_formatter/tests/cases/types_decls.cases`
(22 cases: one per shape, the negative `x[i] = 1;` statement, a
`// verilog_format: off` fence, comment attachment, and the
line-length boundary), plus 9 parser unit tests
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test` clean
- [x] No corpus regression: the passing set after is a strict superset
## Work log
### 2026-08-21 — dev
**Baseline** `{"passing":740,"total":820,"pct":90.2,"failures_by_category":
{"dv-statements":26,"expressions":21,"directive-split":14,"types-decls":11,
"invalid-or-fragment":3,"lex-macro-number":2,"other":2,"not-verilog":1}}`
**After** `{"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}}`
All 11 `types-decls` files pass; the category is gone from the JSON. No file
that passed before fails now (`comm` on the two `.score-results.tsv` pass
sets is empty in the regression direction).
**Parser.** The shape of the change is one refactor plus six small openings:
- `parse_typedef`'s enum and struct bodies moved out into `parse_enum_type` /
`parse_struct_type`, which run from the keyword through the closing `}`.
`typedef` now calls them and appends the name; so does everything below.
- `parse_opt_data_type` takes an `enum`/`struct`/`union` at the cursor and
stores the body in `DataType::extra`. Because that function is the single
door to every type position, this one hook delivered shapes 1, 2 (through
`parse_type_expr`, which a `parameter type` default already used) and 5
(through `parse_struct_type`'s own member loop — the recursion is free).
- `at_typed_declarator` replaces the two hand-rolled copies of the
"identifier type?" lookahead (in `parse_opt_data_type` and
`parse_assign_or_expr_stmt`) with one that also skips a run of balanced
`[...]` groups. Shape 3, at item, statement and class-member position at
once. `scan_matching` is strictly increasing on a `[`, so the skip loop
terminates.
- `parse_enum_type`'s base type goes through the new `parse_type_ref`, which
falls back to a bare identifier (plus `::` chain, `#( ... )` and packed
dims) when `parse_opt_data_type` declines — shape 4. `parse_type_expr` was
a cut-down copy of that fallback and now delegates to it.
- `parse_param_decl` eats an optional `type` keyword and parses each `= ...`
as a type rather than an expression — shape 6. `parse_declarators` grew a
`parse_declarator_list(type_init)` sibling for that.
- The `for` init accepts an identifier type when `at_typed_declarator` says a
declarator follows it — shape 7. The comma-separated step list already
worked.
- `parse_keyword_item` and `parse_keyword_stmt` route `enum`/`struct`/`union`
to `parse_data_decl` instead of erroring.
**Formatter.** `typedef`'s two big arms became `enum_type` / `struct_type`,
which `data_type` also calls for an inline aggregate — so a nested struct
member indents one more level for free, and an anonymous enum inherits the
fit-or-break group the typedef path already had. `param_decl` and
`param_decl_cells` print the `type` keyword; putting it in the *prefix* cell
is what keeps a run of aligned `localparam type` lines aligned.
**Decision: one box, not two.** Adding `inline: Option<Box<InlineType>>`
beside `params: Option<Box<RawText>>` grew `DataType` by 8 bytes, which grew
`Expr` (it carries a `DataType` through `ExprKind::Type`), which took
`DimKind::Range { a: Expr, b: Option<Expr> }` from 200 to 208 bytes and
tripped clippy's `large_enum_variant` at its 200-byte threshold. Rather than
`#[allow]` a lint on a shared AST node for a rare field, the two mutually
exclusive tails were merged into `extra: Option<Box<TypeExtra>>` with
`params()` / `inline()` accessors — which is what `params`' own doc comment
had been asking for since it was written. `DataType` is back to its original
size and clippy is clean with no suppressions.
**Not fixed, and why.**
`corpus/ibex/vendor/google_riscv-dv/src/isa/custom/riscv_custom_instr_enum.sv`
is an `include` fragment — a bare `CUSTOM_1,` at top level, meant to be
pasted inside an enum body. It is not a translation unit and vfmt should keep
rejecting it. It is classified `invalid-or-fragment`, not `types-decls`, in
both the before and after TSVs, so it was never in this bucket's count.
## QA log
## Review