TODO §38 (docs/features/parser-skips). Closes the jtag_if.sv and
SimDTM.sv skips from the §11 sweep.
38.1 `Parser::at_rival_header`: in a module/interface/program body, a
continuing directive at the unit's own entry level followed by the same
keyword and name is a header written twice across the arms, not a
nested unit. The error routes into the existing conditional split
(`at_split_conditional` now fires on a rival as well as an open
bracket; `scan_split_extent` runs to the unit's real closer, counting
nested units of the same kind), so the whole unit is one Verbatim item
in both modes. jtag_if.sv now formats (body verbatim, the standing
directive-split trade).
38.2 `DataDecl::delay: Option<NetDelay { expr, after_type }>`: a net
delay is accepted before or after the type (IEEE 1800 §6.7 puts it
after), never both, and printed where it was written. SimDTM.sv now
formats; its four `#0.1` lines come back byte-identical.
Byte-identity vs 0.41.0: 0 of 820 corpus files differ; over 2 554
opentitan files exactly the two named files change outcome.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
464 lines
18 KiB
Rust
464 lines
18 KiB
Rust
//! Declarations and the types they name: a `DataType` with its packed
|
|
//! dimensions, unpacked dimensions, the declarator list of a
|
|
//! `logic a, b = 1;`, `parameter`/`localparam` and their alignment,
|
|
//! `typedef`, and `enum`/`struct` bodies.
|
|
//!
|
|
//! An expression inside a dimension is printed by `expr_compact`, which
|
|
//! belongs to the expression module; only the brackets are this one's.
|
|
|
|
use crate::align::{self, Align, ColSpec, Row};
|
|
use crate::doc::*;
|
|
use vlog_parser::ast::*;
|
|
|
|
use super::comment::is_line_comment;
|
|
use super::list::ListItem;
|
|
use super::{name_doc, Fmt};
|
|
|
|
/// A `parameter`/`localparam` declaration's two alignment columns: the name,
|
|
/// and the `=` of its value.
|
|
const PARAM_DECL_COLS: &[ColSpec] = &[ColSpec { flush: 1, min: 1 }, ColSpec { flush: 1, min: 1 }];
|
|
|
|
impl<'a> Fmt<'a> {
|
|
/// Format a data type; `None` if fully implicit.
|
|
pub(super) fn data_type(&self, ty: &DataType) -> Option<Doc> {
|
|
if ty.is_implicit() {
|
|
return None;
|
|
}
|
|
let mut docs = Vec::new();
|
|
let mut need_space = false;
|
|
// `virtual clk_rst_if`, `virtual interface bus_if`.
|
|
if let Some(v) = ty.virt {
|
|
docs.push(text(v.text()));
|
|
need_space = true;
|
|
}
|
|
if !ty.name.is_empty() {
|
|
if need_space {
|
|
docs.push(text(" "));
|
|
}
|
|
docs.push(name_doc(&ty.name));
|
|
need_space = true;
|
|
}
|
|
// `uvm_analysis_port #(bit [31:0]) port;` — spaced before the `#(`,
|
|
// like an instantiation's overrides and unlike the tight `#(` of a
|
|
// parameterized name in expression position.
|
|
if let Some(params) = ty.params() {
|
|
if need_space {
|
|
docs.push(text(" "));
|
|
}
|
|
docs.push(self.raw_inline(params));
|
|
need_space = true;
|
|
}
|
|
if let Some(s) = &ty.signing {
|
|
if need_space {
|
|
docs.push(text(" "));
|
|
}
|
|
docs.push(text(s.clone()));
|
|
need_space = true;
|
|
}
|
|
if !ty.packed.is_empty() {
|
|
// A dimension that opens with a comment writes its own space.
|
|
if need_space && ty.packed[0].comments.opens_clean() {
|
|
docs.push(text(" "));
|
|
}
|
|
for d in &ty.packed {
|
|
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))
|
|
}
|
|
|
|
pub(super) fn dim(&self, d: &Dim) -> Doc {
|
|
let c = &d.comments;
|
|
let brackets = match &d.kind {
|
|
DimKind::Range { a, b } => {
|
|
let rest = b.as_ref().map(|b| (":", self.expr_compact(b)));
|
|
self.bracket_slots(c, self.expr_compact(a), rest)
|
|
}
|
|
// `[]` and `[*]` have no operand, so the one inner slot they own
|
|
// is the gap before the `]`, which is where `parse_dims` puts
|
|
// anything written between the brackets.
|
|
DimKind::Dynamic => self.bracket_slots(c, text(""), None),
|
|
DimKind::Wildcard => self.bracket_slots(c, text("*"), None),
|
|
};
|
|
if c.opens_clean() {
|
|
return brackets;
|
|
}
|
|
// `logic /*c*/ [3:0]` — the gap before the `[` belongs to the
|
|
// dimension, since nothing to its left has a slot for it. The space
|
|
// in front is the dimension's own: a caller that would have written
|
|
// one asks [`SegmentComments::opens_clean`] and leaves it out.
|
|
let mut docs = Vec::new();
|
|
self.inline_comments_spaced(&c.before_open, &mut docs);
|
|
docs.push(brackets);
|
|
concat(docs)
|
|
}
|
|
|
|
pub(super) fn unpacked_dims(&self, dims: &[Dim]) -> Vec<Doc> {
|
|
let mut docs = Vec::new();
|
|
if !dims.is_empty() {
|
|
if dims[0].comments.opens_clean() {
|
|
docs.push(text(" "));
|
|
}
|
|
for d in dims {
|
|
docs.push(self.dim(d));
|
|
}
|
|
}
|
|
docs
|
|
}
|
|
|
|
fn declarators(&self, decls: &[Declarator]) -> Doc {
|
|
let items: Vec<ListItem> = decls
|
|
.iter()
|
|
.map(|d| {
|
|
let mut docs = vec![name_doc(&d.name)];
|
|
docs.extend(self.unpacked_dims(&d.unpacked));
|
|
if let Some(init) = &d.init {
|
|
self.slot_comments(&d.eq_comments.before, &mut docs);
|
|
docs.push(text(if d.eq_comments.before.is_empty() { " =" } else { "=" }));
|
|
if d.eq_comments.after.is_empty() {
|
|
docs.push(group(vec![self.assign_rhs(self.expr(init))]));
|
|
} else {
|
|
self.inline_comments_spaced(&d.eq_comments.after, &mut docs);
|
|
docs.push(group(vec![self.expr(init)]));
|
|
}
|
|
}
|
|
ListItem::from_meta(&d.meta, concat(docs))
|
|
})
|
|
.collect();
|
|
if items.len() == 1 {
|
|
let item = items.into_iter().next().unwrap();
|
|
let mut docs = self.leading(&Meta { leading: item.leading, ..Meta::default() });
|
|
docs.push(item.doc);
|
|
let mut ends_line = self.inline_comments(&item.before_sep, &mut docs);
|
|
if let Some(tr) = item.trailing {
|
|
docs.push(if ends_line { Doc::HardLine } else { text(" ") });
|
|
docs.push(self.comment(&tr));
|
|
ends_line = is_line_comment(&tr.text);
|
|
}
|
|
// The caller appends the `;`; a line comment runs to end of line,
|
|
// so it has to go on the next one.
|
|
if ends_line {
|
|
docs.push(Doc::HardLine);
|
|
}
|
|
return concat(docs);
|
|
}
|
|
// Multiple declarators: allow one-per-line continuation.
|
|
let mut inner = Vec::new();
|
|
let last = items.len() - 1;
|
|
for (i, item) in items.into_iter().enumerate() {
|
|
let meta = Meta { leading: item.leading, ..Meta::default() };
|
|
inner.extend(self.leading(&meta));
|
|
inner.push(item.doc);
|
|
let ends_line = self.inline_comments(&item.before_sep, &mut inner);
|
|
if i < last {
|
|
if ends_line {
|
|
inner.push(Doc::HardLine);
|
|
}
|
|
inner.push(text(","));
|
|
} else if ends_line {
|
|
inner.push(Doc::HardLine);
|
|
}
|
|
if let Some(tr) = item.trailing {
|
|
inner.push(text(" "));
|
|
inner.push(self.comment(&tr));
|
|
if i < last || is_line_comment(&tr.text) {
|
|
inner.push(Doc::HardLine);
|
|
}
|
|
} else if i < last {
|
|
inner.push(Doc::Line);
|
|
}
|
|
}
|
|
group(vec![indent(inner)])
|
|
}
|
|
|
|
/// A `parameter`/`localparam` declaration. With an alignment plan it is
|
|
/// laid out as cells padded to the group's columns; without one it takes
|
|
/// the flush path every other declaration takes.
|
|
///
|
|
/// The two must agree byte-for-byte when the padding collapses, because
|
|
/// that is exactly what the printer's line-limit fallback does — and the
|
|
/// next pass, seeing no excess spaces, comes back through the flush path.
|
|
pub(super) fn param_decl(&self, d: &ParamDecl, align: Option<&Align>) -> Doc {
|
|
if let (Some(a), [decl]) = (align, &d.declarators[..]) {
|
|
if let Some(init) = &decl.init {
|
|
return align::render(
|
|
&self.param_decl_cells(d, decl, init),
|
|
PARAM_DECL_COLS,
|
|
Some(a),
|
|
);
|
|
}
|
|
}
|
|
let mut docs = Vec::new();
|
|
self.word_then(&d.kw, &d.after_kw, &mut docs);
|
|
if d.is_type {
|
|
docs.push(text("type "));
|
|
}
|
|
if let Some(t) = self.data_type(&d.ty) {
|
|
docs.push(t);
|
|
docs.push(text(" "));
|
|
}
|
|
docs.push(self.declarators(&d.declarators));
|
|
concat(docs)
|
|
}
|
|
|
|
/// A `parameter`/`localparam` declaration split at its two alignment
|
|
/// columns: the keyword and type, the name, and the `= value`.
|
|
fn param_decl_cells(&self, d: &ParamDecl, decl: &Declarator, init: &Expr) -> Vec<Doc> {
|
|
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) {
|
|
prefix.push(text(" "));
|
|
prefix.push(t);
|
|
}
|
|
let mut name = vec![name_doc(&decl.name)];
|
|
name.extend(self.unpacked_dims(&decl.unpacked));
|
|
vec![
|
|
concat(prefix),
|
|
concat(name),
|
|
concat(vec![text("="), group(vec![self.assign_rhs(self.expr(init))])]),
|
|
]
|
|
}
|
|
|
|
/// The alignment plan for the `parameter`/`localparam` declarations among
|
|
/// a run of module (or package, or class) items.
|
|
pub(super) fn param_decl_aligns(&self, items: &[Item], depth: usize) -> Vec<Option<Align>> {
|
|
let rows: Vec<Option<Row>> = items.iter().map(|i| self.param_decl_row(i)).collect();
|
|
if rows.iter().all(Option::is_none) {
|
|
return vec![None; items.len()];
|
|
}
|
|
// Unlike a bracketed list, an item sequence prints the blank lines the
|
|
// source wrote, so a blank line is a boundary the next pass sees too.
|
|
let breaks: Vec<bool> = items
|
|
.iter()
|
|
.map(|i| i.meta.blank_before || !i.meta.leading.is_empty() || !i.meta.attrs.is_empty())
|
|
.collect();
|
|
self.align_groups(&rows, &breaks, PARAM_DECL_COLS, depth)
|
|
}
|
|
|
|
/// Measure a `parameter`/`localparam` item as an alignment row.
|
|
///
|
|
/// Only the plain shape joins a group: one declarator, with a value, no
|
|
/// comments of its own, not inside a fenced region. Anything else formats
|
|
/// the way it always has and splits the group in two.
|
|
fn param_decl_row(&self, item: &Item) -> Option<Row> {
|
|
let ItemKind::ParamDecl(d) = &item.kind else { return None };
|
|
if !item.meta.attrs.is_empty() || self.is_verbatim(item.span) {
|
|
return None;
|
|
}
|
|
let [decl] = &d.declarators[..] else { return None };
|
|
if !decl.meta.leading.is_empty()
|
|
|| !decl.meta.before_sep.is_empty()
|
|
|| decl.meta.trailing.is_some()
|
|
// A comment after the keyword makes this row a width no other row
|
|
// shares, so it never joins an alignment group.
|
|
|| !d.after_kw.is_empty()
|
|
{
|
|
return None;
|
|
}
|
|
let init = decl.init.as_ref()?;
|
|
let eq = self.eq_offset(init.span.start, decl.name_span.end)?;
|
|
// The tail is the `;` the item ends with.
|
|
Self::row_of(&self.param_decl_cells(d, decl, init), vec![decl.name_span.start, eq], 1)
|
|
}
|
|
|
|
/// Byte offset of the `=` between a declarator's name and its value, or
|
|
/// `None` when anything but whitespace stands between the two.
|
|
fn eq_offset(&self, value_start: u32, after_name: u32) -> Option<u32> {
|
|
let bytes = self.src.as_bytes();
|
|
let mut pos = value_start as usize;
|
|
while pos > 0 && matches!(bytes[pos - 1], b' ' | b'\t' | b'\r' | b'\n') {
|
|
pos -= 1;
|
|
}
|
|
(pos > after_name as usize && bytes.get(pos - 1) == Some(&b'=')).then_some(pos as u32 - 1)
|
|
}
|
|
|
|
pub(super) fn data_decl(&self, d: &DataDecl) -> Doc {
|
|
let mut docs = Vec::new();
|
|
if let Some(net) = &d.net {
|
|
docs.push(text(format!("{net} ")));
|
|
}
|
|
self.net_delay(d, false, &mut docs);
|
|
self.qualifier_run(&d.qualifiers, &mut docs);
|
|
if let Some(t) = self.data_type(&d.ty) {
|
|
docs.push(t);
|
|
docs.push(text(" "));
|
|
}
|
|
self.net_delay(d, true, &mut docs);
|
|
docs.push(self.declarators(&d.declarators));
|
|
concat(docs)
|
|
}
|
|
|
|
/// `#5 ` — the declaration's net delay and the space after it, but only
|
|
/// when it was written on the side of the data type `after_type` names.
|
|
/// IEEE 1800 §6.7 allows either side and lucisv prints it where the
|
|
/// source put it; moving it across the type would reorder tokens, which
|
|
/// `verify.rs` refuses.
|
|
fn net_delay(&self, d: &DataDecl, after_type: bool, docs: &mut Vec<Doc>) {
|
|
let Some(delay) = d.delay.as_ref().filter(|n| n.after_type == after_type) else {
|
|
return;
|
|
};
|
|
docs.push(text("#"));
|
|
docs.push(self.expr(&delay.expr));
|
|
docs.push(text(" "));
|
|
}
|
|
|
|
pub(super) fn port_decl(&self, d: &PortDecl) -> Doc {
|
|
let mut docs = vec![text(format!("{} ", d.dir))];
|
|
if let Some(net) = &d.net {
|
|
docs.push(text(format!("{net} ")));
|
|
}
|
|
if let Some(t) = self.data_type(&d.ty) {
|
|
docs.push(t);
|
|
docs.push(text(" "));
|
|
}
|
|
docs.push(self.declarators(&d.declarators));
|
|
concat(docs)
|
|
}
|
|
|
|
pub(super) fn typedef(&self, t: &Typedef) -> Doc {
|
|
let mut docs = Vec::new();
|
|
self.word_then("typedef", &t.after_kw, &mut docs);
|
|
let base = match &t.kind {
|
|
TypedefKind::ForwardClass => Some(text("class")),
|
|
TypedefKind::Alias(ty) => self.data_type(ty),
|
|
TypedefKind::Enum(e) => Some(self.enum_type(e)),
|
|
TypedefKind::Struct(s) => Some(self.struct_type(s)),
|
|
};
|
|
match base {
|
|
Some(d) => {
|
|
docs.push(d);
|
|
if t.before_name.is_empty() {
|
|
docs.push(text(" "));
|
|
} else {
|
|
self.inline_comments_spaced(&t.before_name, &mut docs);
|
|
}
|
|
}
|
|
None => self.slot_comments(&t.before_name, &mut docs),
|
|
}
|
|
docs.push(name_doc(&t.name));
|
|
docs.extend(self.unpacked_dims(&t.unpacked));
|
|
docs.push(self.semi(&t.before_semi));
|
|
concat(docs)
|
|
}
|
|
|
|
/// `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")];
|
|
let mut spaced = false;
|
|
if !e.after_kw.is_empty() {
|
|
self.inline_comments_spaced(&e.after_kw, &mut docs);
|
|
spaced = true;
|
|
}
|
|
if let Some(base) = &e.base {
|
|
if let Some(d) = self.data_type(base) {
|
|
if !spaced {
|
|
docs.push(text(" "));
|
|
}
|
|
docs.push(d);
|
|
spaced = false;
|
|
}
|
|
}
|
|
if e.before_open.is_empty() {
|
|
if !spaced {
|
|
docs.push(text(" "));
|
|
}
|
|
} else {
|
|
self.inline_comments_spaced(&e.before_open, &mut docs);
|
|
}
|
|
let items = self.list_entries(self.enum_member_items(&e.members), &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)
|
|
}
|
|
|
|
/// One list entry per enum member. Shared by the `enum { ... }` body and
|
|
/// by an enum-member fragment, so the two lay a member out identically.
|
|
pub(super) fn enum_member_items(&self, members: &[EnumMember]) -> Vec<ListItem> {
|
|
members
|
|
.iter()
|
|
.map(|m| {
|
|
let mut d = vec![name_doc(&m.name)];
|
|
// Tight against the name: `OtbnDmem[16]` is one enum name
|
|
// range, not a name with a dimension beside it.
|
|
d.extend(m.range.iter().map(|r| self.dim(r)));
|
|
if let Some(v) = &m.value {
|
|
self.slot_comments(&m.eq_comments.before, &mut d);
|
|
d.push(text(if m.eq_comments.before.is_empty() { " =" } else { "=" }));
|
|
if m.eq_comments.after.is_empty() {
|
|
d.push(text(" "));
|
|
} else {
|
|
self.inline_comments_spaced(&m.eq_comments.after, &mut d);
|
|
}
|
|
d.push(self.expr(v));
|
|
}
|
|
ListItem::from_meta(&m.meta, concat(d)).with_comma(m.comma)
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// `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 c = &s.header_comments;
|
|
// `union tagged packed`, in the LRM's order, each word followed by
|
|
// whatever the source wrote after it.
|
|
let mut head = Vec::new();
|
|
self.word_then(&s.kw, &c.after_kw, &mut head);
|
|
if s.tagged {
|
|
self.word_then("tagged", &c.after_tagged, &mut head);
|
|
}
|
|
if s.packed {
|
|
self.word_then("packed", &c.after_packed, &mut head);
|
|
}
|
|
if let Some(sig) = &s.signing {
|
|
self.word_then(sig, &c.after_signing, &mut head);
|
|
}
|
|
head.push(text("{"));
|
|
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();
|
|
self.qualifier_run(&m.qualifiers, &mut d);
|
|
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![concat(head), indent(inner), Doc::HardLine, text("}")])
|
|
}
|
|
}
|