diff --git a/crates/vfmt/src/main.rs b/crates/vfmt/src/main.rs index f45ac66..09861d7 100644 --- a/crates/vfmt/src/main.rs +++ b/crates/vfmt/src/main.rs @@ -39,12 +39,8 @@ OPTIONS: } fn parse_args() -> Result { - 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 { } "--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(); diff --git a/crates/vlog_formatter/src/format.rs b/crates/vlog_formatter/src/format.rs index 879ed73..51611f8 100644 --- a/crates/vlog_formatter/src/format.rs +++ b/crates/vlog_formatter/src/format.rs @@ -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 = 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 = list - .iter() - .map(|c| ListItem::from_meta(&c.meta, self.connection(c))) - .collect(); + let items: Vec = + 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 = 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); diff --git a/crates/vlog_formatter/src/printer.rs b/crates/vlog_formatter/src/printer.rs index 4d9a392..f988e6d 100644 --- a/crates/vlog_formatter/src/printer.rs +++ b/crates/vlog_formatter/src/printer.rs @@ -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)); diff --git a/crates/vlog_formatter/tests/cases.rs b/crates/vlog_formatter/tests/cases.rs index d420b3b..0957212 100644 --- a/crates/vlog_formatter/tests/cases.rs +++ b/crates/vlog_formatter/tests/cases.rs @@ -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}")), } } diff --git a/crates/vlog_formatter/tests/fixtures.rs b/crates/vlog_formatter/tests/fixtures.rs index cef1bd6..18b2f22 100644 --- a/crates/vlog_formatter/tests/fixtures.rs +++ b/crates/vlog_formatter/tests/fixtures.rs @@ -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", diff --git a/crates/vlog_parser/src/ast.rs b/crates/vlog_parser/src/ast.rs index 8595e3e..a71563f 100644 --- a/crates/vlog_parser/src/ast.rs +++ b/crates/vlog_parser/src/ast.rs @@ -31,7 +31,12 @@ pub struct Item { #[derive(Debug)] pub enum ItemKind { Module(Module), - Package { kw: String, name: String, items: Vec, dangling: Vec }, + Package { + kw: String, + name: String, + items: Vec, + dangling: Vec, + }, Directive(String), Import(Vec), 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), - GenerateRegion { items: Vec, dangling: Vec }, + GenerateRegion { + items: Vec, + dangling: Vec, + }, GenIf(GenIf), GenFor(GenFor), GenCase(GenCase), @@ -412,11 +423,26 @@ pub enum StmtKind { step: Vec, body: Box, }, - While { cond: Expr, body: Box }, - DoWhile { body: Box, cond: Expr }, - Repeat { count: Expr, body: Box }, - Forever { body: Box }, - Foreach { target: Expr, vars: Vec, body: Box }, + While { + cond: Expr, + body: Box, + }, + DoWhile { + body: Box, + cond: Expr, + }, + Repeat { + count: Expr, + body: Box, + }, + Forever { + body: Box, + }, + Foreach { + target: Expr, + vars: Vec, + body: Box, + }, /// 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 }, + ForceRelease { + kw: String, + lhs: Expr, + rhs: Option, + }, /// Procedural timing control: `#10 stmt;`, `@(posedge clk) stmt;`, /// `#10;`, `@(ev);` - Timing { control: TimingControl, stmt: Option> }, - Wait { cond: Expr, stmt: Option> }, + Timing { + control: TimingControl, + stmt: Option>, + }, + Wait { + cond: Expr, + stmt: Option>, + }, 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 }, - Binary { lhs: Box, op: String, rhs: Box }, - Ternary { cond: Box, then: Box, els: Box }, - Call { callee: Box, args: Vec }, - Index { base: Box, index: Box }, - Range { base: Box, op: String, msb: Box, lsb: Box }, - Member { base: Box, name: String }, - Scope { base: Box, name: String }, + Unary { + op: String, + expr: Box, + }, + Binary { + lhs: Box, + op: String, + rhs: Box, + }, + Ternary { + cond: Box, + then: Box, + els: Box, + }, + Call { + callee: Box, + args: Vec, + }, + Index { + base: Box, + index: Box, + }, + Range { + base: Box, + op: String, + msb: Box, + lsb: Box, + }, + Member { + base: Box, + name: String, + }, + Scope { + base: Box, + name: String, + }, Concat(Vec), - Repl { count: Box, inner: Vec }, + Repl { + count: Box, + inner: Vec, + }, Paren(Box), /// `ty'(expr)` cast; `ty` kept as raw text. - Cast { ty: String, expr: Box }, + Cast { + ty: String, + expr: Box, + }, /// `'{...}` assignment pattern. AssignPattern(Vec), - Postfix { expr: Box, op: String }, - Inside { lhs: Box, ranges: Vec }, + Postfix { + expr: Box, + op: String, + }, + Inside { + lhs: Box, + ranges: Vec, + }, /// `[a:b]` inside an `inside` range list or value range. - ValueRange { lo: Box, hi: Box }, + ValueRange { + lo: Box, + hi: Box, + }, /// A type used in expression position (`parameter type T = logic [7:0]`). Type(DataType), /// `(min : typ : max)` delay expression. - MinTypMax { min: Box, typ: Box, max: Box }, + MinTypMax { + min: Box, + typ: Box, + max: Box, + }, } #[derive(Debug, Clone)] diff --git a/crates/vlog_parser/src/lexer.rs b/crates/vlog_parser/src/lexer.rs index 55f5804..c151825 100644 --- a/crates/vlog_parser/src/lexer.rs +++ b/crates/vlog_parser/src/lexer.rs @@ -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, 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] diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index 50b9ce1..512cdc8 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -27,13 +27,26 @@ impl std::error::Error for ParseError {} type PResult = Result; 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, @@ -53,7 +65,8 @@ pub struct Parser { } pub fn parse(tokens: Vec) -> PResult { - 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 { 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()?;