Normalize whole tree with cargo fmt under rustfmt.toml

One-time mechanical pass; no behavior change (full test suite green
before and after). From here on, cargo fmt --check is the standard.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-18 23:41:18 -07:00
1 parent 8effef9b6b
commit d2cd44c428
8 files changed
+191 -149

No files matched your search

+3 -8
View File
@@ -39,12 +39,8 @@ OPTIONS:
}
fn parse_args() -> Result<Options, String> {
let mut opts = Options {
check: false,
stdout: false,
config: Config::default(),
inputs: Vec::new(),
};
let mut opts =
Options { check: false, stdout: false, config: Config::default(), inputs: Vec::new() };
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
@@ -57,8 +53,7 @@ fn parse_args() -> Result<Options, String> {
}
"--indent" => {
let v = args.next().ok_or("--indent requires a value")?;
opts.config.indent_width =
v.parse().map_err(|_| format!("invalid indent: {v}"))?;
opts.config.indent_width = v.parse().map_err(|_| format!("invalid indent: {v}"))?;
}
"-h" | "--help" => {
print_help();
+20 -70
View File
@@ -206,12 +206,7 @@ impl<'a> Fmt<'a> {
/// `( expr )` with break opportunity inside.
fn parens(&self, e: &Expr) -> Doc {
group(vec![
text("("),
indent(vec![Doc::SoftLine, self.expr(e)]),
Doc::SoftLine,
text(")"),
])
group(vec![text("("), indent(vec![Doc::SoftLine, self.expr(e)]), Doc::SoftLine, text(")")])
}
/// Sequence of items/statements at one indent level, preserving single
@@ -307,12 +302,7 @@ impl<'a> Fmt<'a> {
body.extend(self.item_seq(items));
}
body.extend(self.dangling(dangling));
concat(vec![
text("generate"),
indent(body),
Doc::HardLine,
text("endgenerate"),
])
concat(vec![text("generate"), indent(body), Doc::HardLine, text("endgenerate")])
}
ItemKind::GenIf(g) => self.gen_if(g),
ItemKind::GenFor(g) => self.gen_for(g),
@@ -322,9 +312,7 @@ impl<'a> Fmt<'a> {
ItemKind::Defparam(pairs) => {
let parts: Vec<Doc> = pairs
.iter()
.map(|(l, r)| {
concat(vec![self.expr(l), text(" = "), self.expr(r)])
})
.map(|(l, r)| concat(vec![self.expr(l), text(" = "), self.expr(r)]))
.collect();
let mut docs = vec![text("defparam ")];
docs.extend(join(parts, text(", ")));
@@ -507,12 +495,8 @@ impl<'a> Fmt<'a> {
text(" : "),
self.expr_compact(els),
]),
Expr::Paren(inner) => {
concat(vec![text("("), self.expr_compact(inner), text(")")])
}
Expr::Unary { op, expr } => {
concat(vec![text(op.clone()), self.expr_compact(expr)])
}
Expr::Paren(inner) => concat(vec![text("("), self.expr_compact(inner), text(")")]),
Expr::Unary { op, expr } => concat(vec![text(op.clone()), self.expr_compact(expr)]),
_ => self.expr(e),
}
}
@@ -792,10 +776,8 @@ impl<'a> Fmt<'a> {
fn connections(&self, conns: &Connections) -> Doc {
match conns {
Connections::Named(list) => {
let items: Vec<ListItem> = list
.iter()
.map(|c| ListItem::from_meta(&c.meta, self.connection(c)))
.collect();
let items: Vec<ListItem> =
list.iter().map(|c| ListItem::from_meta(&c.meta, self.connection(c))).collect();
self.delimited("(", items, ")", false)
}
Connections::Ordered(list) => {
@@ -963,11 +945,9 @@ impl<'a> Fmt<'a> {
fn for_step(&self, step: &ForStep) -> Doc {
match step {
ForStep::Assign(a) => concat(vec![
self.expr(&a.lhs),
text(format!(" {} ", a.op)),
self.expr(&a.rhs),
]),
ForStep::Assign(a) => {
concat(vec![self.expr(&a.lhs), text(format!(" {} ", a.op)), self.expr(&a.rhs)])
}
ForStep::Expr(e) => self.expr(e),
}
}
@@ -1022,12 +1002,7 @@ impl<'a> Fmt<'a> {
body.extend(self.stmt_seq(&f.stmts));
}
body.extend(self.dangling(&f.dangling));
concat(vec![
concat(header),
indent(body),
Doc::HardLine,
text("endfunction"),
])
concat(vec![concat(header), indent(body), Doc::HardLine, text("endfunction")])
}
fn task(&self, t: &TaskDecl) -> Doc {
@@ -1153,9 +1128,7 @@ impl<'a> Fmt<'a> {
docs.push(text(join_kw.clone()));
concat(docs)
}
StmtKind::If { qualifier, cond, then, els } => {
self.if_stmt(qualifier, cond, then, els)
}
StmtKind::If { qualifier, cond, then, els } => self.if_stmt(qualifier, cond, then, els),
StmtKind::Case { qualifier, kw, expr, items, dangling } => {
let mut head = String::new();
if let Some(q) = qualifier {
@@ -1167,11 +1140,7 @@ impl<'a> Fmt<'a> {
let mut docs = vec![text(head), self.parens(expr)];
let mut body = Vec::new();
for item in items {
body.push(if item.meta.blank_before {
Doc::BlankLine
} else {
Doc::HardLine
});
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
body.extend(self.leading(&item.meta));
body.push(self.case_item(item));
if let Some(tr) = &item.meta.trailing {
@@ -1341,13 +1310,7 @@ impl<'a> Fmt<'a> {
docs.push(text("else"));
}
// `else if` chains stay flat.
if let StmtKind::If {
qualifier: eq,
cond: ec,
then: et,
els: ee,
} = &els.kind
{
if let StmtKind::If { qualifier: eq, cond: ec, then: et, els: ee } = &els.kind {
docs.push(text(" "));
let mut meta_docs = self.leading(&els.meta);
docs.append(&mut meta_docs);
@@ -1428,12 +1391,8 @@ impl<'a> Fmt<'a> {
self.expr_compact(lsb),
text("]"),
]),
Expr::Member { base, name } => {
concat(vec![self.expr(base), text(format!(".{name}"))])
}
Expr::Scope { base, name } => {
concat(vec![self.expr(base), text(format!("::{name}"))])
}
Expr::Member { base, name } => concat(vec![self.expr(base), text(format!(".{name}"))]),
Expr::Scope { base, name } => concat(vec![self.expr(base), text(format!("::{name}"))]),
Expr::Concat(items) => {
let items: Vec<ListItem> =
items.iter().map(|i| ListItem::plain(self.expr(i))).collect();
@@ -1482,13 +1441,9 @@ impl<'a> Fmt<'a> {
concat(vec![text("["), self.expr(lo), text(":"), self.expr(hi), text("]")])
}
Expr::Type(ty) => self.data_type(ty).unwrap_or_else(|| text("")),
Expr::MinTypMax { min, typ, max } => concat(vec![
self.expr(min),
text(":"),
self.expr(typ),
text(":"),
self.expr(max),
]),
Expr::MinTypMax { min, typ, max } => {
concat(vec![self.expr(min), text(":"), self.expr(typ), text(":"), self.expr(max)])
}
}
}
@@ -1499,12 +1454,7 @@ impl<'a> Fmt<'a> {
let prec = Self::binary_prec(op);
let mut operands: Vec<&Expr> = Vec::new();
let mut ops: Vec<&str> = Vec::new();
fn walk<'e>(
e: &'e Expr,
prec: u8,
operands: &mut Vec<&'e Expr>,
ops: &mut Vec<&'e str>,
) {
fn walk<'e>(e: &'e Expr, prec: u8, operands: &mut Vec<&'e Expr>, ops: &mut Vec<&'e str>) {
match e {
Expr::Binary { lhs, op, rhs } if Fmt::binary_prec(op) == prec => {
walk(lhs, prec, operands, ops);
+1 -2
View File
@@ -41,8 +41,7 @@ impl Printer {
}
}
Doc::Group(items) => {
let flat = !contains_hard_line(items)
&& self.fits(col, items, &stack);
let flat = !contains_hard_line(items) && self.fits(col, items, &stack);
let m = if flat { Mode::Flat } else { Mode::Break };
for item in items.iter().rev() {
stack.push((ind, m, item));
+3 -4
View File
@@ -174,10 +174,9 @@ fn case_tables() {
}
match format_source(&case.expected, &config) {
Ok(twice) if twice == case.expected => {}
Ok(twice) => failures.push(format!(
"{at}: not idempotent\n{}",
diff(&case.expected, &twice)
)),
Ok(twice) => {
failures.push(format!("{at}: not idempotent\n{}", diff(&case.expected, &twice)))
}
Err(e) => failures.push(format!("{at}: reformatting output failed: {e}")),
}
}
+2 -7
View File
@@ -24,9 +24,7 @@ fn fixtures_match_snapshots_and_are_idempotent() {
let mut entries: Vec<_> = std::fs::read_dir(fixture_dir())
.expect("fixtures dir")
.map(|e| e.expect("dir entry").path())
.filter(|p| {
matches!(p.extension().and_then(|e| e.to_str()), Some("v") | Some("sv"))
})
.filter(|p| matches!(p.extension().and_then(|e| e.to_str()), Some("v") | Some("sv")))
.collect();
entries.sort();
assert!(!entries.is_empty(), "no fixtures found");
@@ -81,10 +79,7 @@ fn fixtures_match_snapshots_and_are_idempotent() {
fn small_cases() {
// (input, expected) pairs for focused behaviors.
let cases: &[(&str, &str)] = &[
(
"module m;endmodule",
"module m;\nendmodule\n",
),
("module m;endmodule", "module m;\nendmodule\n"),
(
"module m(input a,output b);assign b=~a;endmodule",
"module m (input a, output b);\n assign b = ~a;\nendmodule\n",
+108 -25
View File
@@ -31,7 +31,12 @@ pub struct Item {
#[derive(Debug)]
pub enum ItemKind {
Module(Module),
Package { kw: String, name: String, items: Vec<Item>, dangling: Vec<Comment> },
Package {
kw: String,
name: String,
items: Vec<Item>,
dangling: Vec<Comment>,
},
Directive(String),
Import(Vec<String>),
Timeunit(String),
@@ -42,13 +47,19 @@ pub enum ItemKind {
PortDecl(PortDecl),
ContAssign(ContAssign),
/// The body statement carries any `@(...)`/`#delay` timing control.
Always { kw: String, stmt: Stmt },
Always {
kw: String,
stmt: Stmt,
},
Initial(Stmt),
Final(Stmt),
Instantiation(Instantiation),
GateInstantiation(GateInstantiation),
Genvar(Vec<String>),
GenerateRegion { items: Vec<Item>, dangling: Vec<Comment> },
GenerateRegion {
items: Vec<Item>,
dangling: Vec<Comment>,
},
GenIf(GenIf),
GenFor(GenFor),
GenCase(GenCase),
@@ -412,11 +423,26 @@ pub enum StmtKind {
step: Vec<ForStep>,
body: Box<Stmt>,
},
While { cond: Expr, body: Box<Stmt> },
DoWhile { body: Box<Stmt>, cond: Expr },
Repeat { count: Expr, body: Box<Stmt> },
Forever { body: Box<Stmt> },
Foreach { target: Expr, vars: Vec<String>, body: Box<Stmt> },
While {
cond: Expr,
body: Box<Stmt>,
},
DoWhile {
body: Box<Stmt>,
cond: Expr,
},
Repeat {
count: Expr,
body: Box<Stmt>,
},
Forever {
body: Box<Stmt>,
},
Foreach {
target: Expr,
vars: Vec<String>,
body: Box<Stmt>,
},
/// Blocking/nonblocking/compound assignment.
Assign {
lhs: Expr,
@@ -426,11 +452,21 @@ pub enum StmtKind {
rhs: Expr,
},
/// `force`/`release`/`deassign` statements, raw pieces.
ForceRelease { kw: String, lhs: Expr, rhs: Option<Expr> },
ForceRelease {
kw: String,
lhs: Expr,
rhs: Option<Expr>,
},
/// Procedural timing control: `#10 stmt;`, `@(posedge clk) stmt;`,
/// `#10;`, `@(ev);`
Timing { control: TimingControl, stmt: Option<Box<Stmt>> },
Wait { cond: Expr, stmt: Option<Box<Stmt>> },
Timing {
control: TimingControl,
stmt: Option<Box<Stmt>>,
},
Wait {
cond: Expr,
stmt: Option<Box<Stmt>>,
},
ExprStmt(Expr),
/// `-> event_name;`
EventTrigger(Expr),
@@ -496,29 +532,76 @@ pub enum Expr {
Str(String),
/// Explicitly empty (used for `.port()` connections).
Empty,
Unary { op: String, expr: Box<Expr> },
Binary { lhs: Box<Expr>, op: String, rhs: Box<Expr> },
Ternary { cond: Box<Expr>, then: Box<Expr>, els: Box<Expr> },
Call { callee: Box<Expr>, args: Vec<Expr> },
Index { base: Box<Expr>, index: Box<Expr> },
Range { base: Box<Expr>, op: String, msb: Box<Expr>, lsb: Box<Expr> },
Member { base: Box<Expr>, name: String },
Scope { base: Box<Expr>, name: String },
Unary {
op: String,
expr: Box<Expr>,
},
Binary {
lhs: Box<Expr>,
op: String,
rhs: Box<Expr>,
},
Ternary {
cond: Box<Expr>,
then: Box<Expr>,
els: Box<Expr>,
},
Call {
callee: Box<Expr>,
args: Vec<Expr>,
},
Index {
base: Box<Expr>,
index: Box<Expr>,
},
Range {
base: Box<Expr>,
op: String,
msb: Box<Expr>,
lsb: Box<Expr>,
},
Member {
base: Box<Expr>,
name: String,
},
Scope {
base: Box<Expr>,
name: String,
},
Concat(Vec<Expr>),
Repl { count: Box<Expr>, inner: Vec<Expr> },
Repl {
count: Box<Expr>,
inner: Vec<Expr>,
},
Paren(Box<Expr>),
/// `ty'(expr)` cast; `ty` kept as raw text.
Cast { ty: String, expr: Box<Expr> },
Cast {
ty: String,
expr: Box<Expr>,
},
/// `'{...}` assignment pattern.
AssignPattern(Vec<PatternItem>),
Postfix { expr: Box<Expr>, op: String },
Inside { lhs: Box<Expr>, ranges: Vec<Expr> },
Postfix {
expr: Box<Expr>,
op: String,
},
Inside {
lhs: Box<Expr>,
ranges: Vec<Expr>,
},
/// `[a:b]` inside an `inside` range list or value range.
ValueRange { lo: Box<Expr>, hi: Box<Expr> },
ValueRange {
lo: Box<Expr>,
hi: Box<Expr>,
},
/// A type used in expression position (`parameter type T = logic [7:0]`).
Type(DataType),
/// `(min : typ : max)` delay expression.
MinTypMax { min: Box<Expr>, typ: Box<Expr>, max: Box<Expr> },
MinTypMax {
min: Box<Expr>,
typ: Box<Expr>,
max: Box<Expr>,
},
}
#[derive(Debug, Clone)]
+22 -14
View File
@@ -49,9 +49,9 @@ struct RawLexer<'a> {
/// Multi-character operators, longest first so greedy matching works.
const OPERATORS: &[&str] = &[
"<<<=", ">>>=", "===", "!==", "==?", "!=?", "<<<", ">>>", "<<=", ">>=", "**", "==", "!=",
"<=", ">=", "&&", "||", "<<", ">>", "->", "=>", "::", "+:", "-:", "+=", "-=", "*=", "/=",
"%=", "&=", "|=", "^=", "++", "--", "~&", "~|", "~^", "^~", "##", "'{",
"<<<=", ">>>=", "===", "!==", "==?", "!=?", "<<<", ">>>", "<<=", ">>=", "**", "==", "!=", "<=",
">=", "&&", "||", "<<", ">>", "->", "=>", "::", "+:", "-:", "+=", "-=", "*=", "/=", "%=", "&=",
"|=", "^=", "++", "--", "~&", "~|", "~^", "^~", "##", "'{",
];
const SINGLE_OPS: &[u8] = b"+-*/%&|^~!<>=?:;,.#@()[]{}'$";
@@ -456,8 +456,7 @@ impl<'a> RawLexer<'a> {
let start = self.pos;
self.bump(); // '
let c = self.peek();
if matches!(c, b'0' | b'1' | b'x' | b'X' | b'z' | b'Z') && !is_ident_char(self.peek_at(1))
{
if matches!(c, b'0' | b'1' | b'x' | b'X' | b'z' | b'Z') && !is_ident_char(self.peek_at(1)) {
// Unbased unsized literal: '0 '1 'x 'z
self.bump();
return Ok(self.text_from(start));
@@ -493,8 +492,21 @@ fn is_ident_char(c: u8) -> bool {
fn is_base_intro(c: u8) -> bool {
matches!(
c,
b's' | b'S' | b'd' | b'D' | b'b' | b'B' | b'o' | b'O' | b'h' | b'H' | b'0' | b'1' | b'x'
| b'X' | b'z' | b'Z'
b's' | b'S'
| b'd'
| b'D'
| b'b'
| b'B'
| b'o'
| b'O'
| b'h'
| b'H'
| b'0'
| b'1'
| b'x'
| b'X'
| b'z'
| b'Z'
)
}
@@ -547,8 +559,8 @@ pub fn tokenize(source: &str) -> Result<Vec<Token>, LexError> {
for raw in raws {
match raw.kind {
RawKind::LineComment | RawKind::BlockComment => {
let same_line_as_prev = raw.newlines_before == 0 && !tokens.is_empty()
&& pending.is_empty();
let same_line_as_prev =
raw.newlines_before == 0 && !tokens.is_empty() && pending.is_empty();
if same_line_as_prev {
// Trailing comment for the previous real token.
let prev = tokens.last_mut().unwrap();
@@ -596,11 +608,7 @@ mod tests {
use super::*;
fn kinds(src: &str) -> Vec<(TokenKind, String)> {
tokenize(src)
.unwrap()
.into_iter()
.map(|t| (t.kind, t.text))
.collect()
tokenize(src).unwrap().into_iter().map(|t| (t.kind, t.text)).collect()
}
#[test]
+32 -19
View File
@@ -27,13 +27,26 @@ impl std::error::Error for ParseError {}
type PResult<T> = Result<T, ParseError>;
const TYPE_KEYWORDS: &[&str] = &[
"logic", "reg", "bit", "byte", "shortint", "int", "longint", "integer", "time", "realtime",
"real", "shortreal", "string", "chandle", "event", "void",
"logic",
"reg",
"bit",
"byte",
"shortint",
"int",
"longint",
"integer",
"time",
"realtime",
"real",
"shortreal",
"string",
"chandle",
"event",
"void",
];
const NET_KEYWORDS: &[&str] = &[
"wire", "tri", "tri0", "tri1", "wand", "wor", "trireg", "supply0", "supply1", "uwire",
];
const NET_KEYWORDS: &[&str] =
&["wire", "tri", "tri0", "tri1", "wand", "wor", "trireg", "supply0", "supply1", "uwire"];
const GATE_KEYWORDS: &[&str] = &[
"and", "or", "nand", "nor", "xor", "xnor", "not", "buf", "bufif0", "bufif1", "notif0",
@@ -41,9 +54,8 @@ const GATE_KEYWORDS: &[&str] = &[
"rtran", "tranif0", "tranif1", "rtranif0", "rtranif1",
];
const ASSIGN_OPS: &[&str] = &[
"=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "<<<=", ">>>=",
];
const ASSIGN_OPS: &[&str] =
&["=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "<<<=", ">>>="];
pub struct Parser {
tokens: Vec<Token>,
@@ -53,7 +65,8 @@ pub struct Parser {
}
pub fn parse(tokens: Vec<Token>) -> PResult<SourceFile> {
let mut p = Parser { tokens, pos: 0, pending_leading: Vec::new(), pending_trailing: Vec::new() };
let mut p =
Parser { tokens, pos: 0, pending_leading: Vec::new(), pending_trailing: Vec::new() };
p.parse_source_file()
}
@@ -319,8 +332,10 @@ impl Parser {
}
_ if NET_KEYWORDS.contains(&kw.as_str())
|| TYPE_KEYWORDS.contains(&kw.as_str())
|| matches!(kw.as_str(), "var" | "automatic" | "static" | "const" | "signed"
| "unsigned") =>
|| matches!(
kw.as_str(),
"var" | "automatic" | "static" | "const" | "signed" | "unsigned"
) =>
{
let d = self.parse_data_decl()?;
Ok(ItemKind::DataDecl(d))
@@ -647,7 +662,9 @@ impl Parser {
let t = self.cur();
if t.kind == TokenKind::Keyword && NET_KEYWORDS.contains(&t.text.as_str()) {
net = Some(self.bump().text);
} else if t.is_kw("var") || t.is_kw("automatic") || t.is_kw("static")
} else if t.is_kw("var")
|| t.is_kw("automatic")
|| t.is_kw("static")
|| t.is_kw("const")
{
qualifiers.push(self.bump().text);
@@ -1398,11 +1415,8 @@ impl Parser {
(None, Some(Box::new(self.parse_stmt()?)))
} else {
let then = Box::new(self.parse_stmt()?);
let els = if self.eat_kw("else") {
Some(Box::new(self.parse_stmt()?))
} else {
None
};
let els =
if self.eat_kw("else") { Some(Box::new(self.parse_stmt()?)) } else { None };
(Some(then), els)
};
Ok(StmtKind::Assert { kw, cond, then, els })
@@ -1495,8 +1509,7 @@ impl Parser {
fn parse_for_step(&mut self) -> PResult<ForStep> {
let lhs = self.parse_unary()?;
let op = self.cur().text.clone();
if self.cur().kind == TokenKind::Symbol
&& (ASSIGN_OPS.contains(&op.as_str()) || op == "<=")
if self.cur().kind == TokenKind::Symbol && (ASSIGN_OPS.contains(&op.as_str()) || op == "<=")
{
self.bump();
let rhs = self.parse_expr()?;